MainApplicationContext.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2022 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerSystemTrayApp.Properties;
  16. using Microsoft.Win32;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.IO;
  21. using System.Management;
  22. using System.Net;
  23. using System.Net.NetworkInformation;
  24. using System.Net.Sockets;
  25. using System.ServiceProcess;
  26. using System.Text;
  27. using System.Windows.Forms;
  28. using TechnitiumLibrary.IO;
  29. namespace DnsServerSystemTrayApp
  30. {
  31. public class MainApplicationContext : ApplicationContext
  32. {
  33. #region variables
  34. const int SERVICE_WAIT_TIMEOUT_SECONDS = 30;
  35. private readonly ServiceController _service = new ServiceController("DnsService");
  36. readonly string _configFile;
  37. readonly List<DnsProvider> _dnsProviders = new List<DnsProvider>();
  38. private NotifyIcon TrayIcon;
  39. private ContextMenuStrip TrayIconContextMenu;
  40. private ToolStripMenuItem DashboardMenuItem;
  41. private ToolStripMenuItem NetworkDnsMenuItem;
  42. private ToolStripMenuItem DefaultNetworkDnsMenuItem;
  43. private ToolStripMenuItem ManageNetworkDnsMenuItem;
  44. private ToolStripMenuItem ServiceMenuItem;
  45. private ToolStripMenuItem StartServiceMenuItem;
  46. private ToolStripMenuItem RestartServiceMenuItem;
  47. private ToolStripMenuItem StopServiceMenuItem;
  48. private ToolStripMenuItem AboutMenuItem;
  49. private ToolStripMenuItem AutoStartMenuItem;
  50. private ToolStripMenuItem ExitMenuItem;
  51. #endregion
  52. #region constructor
  53. public MainApplicationContext(string configFile, string[] args, ref bool exitApp)
  54. {
  55. _configFile = configFile;
  56. LoadConfig();
  57. InitializeComponent();
  58. if (args.Length > 0)
  59. {
  60. switch (args[0])
  61. {
  62. case "--network-dns-default-exit":
  63. SetNetworkDnsToDefault(true);
  64. exitApp = true;
  65. break;
  66. case "--network-dns-default":
  67. SetNetworkDnsToDefault();
  68. break;
  69. case "--network-dns-item":
  70. foreach (DnsProvider dnsProvider in _dnsProviders)
  71. {
  72. if (dnsProvider.Name.Equals(args[1]))
  73. {
  74. NetworkDnsMenuSubItem_Click(new ToolStripMenuItem(dnsProvider.Name) { Tag = dnsProvider }, EventArgs.Empty);
  75. break;
  76. }
  77. }
  78. break;
  79. case "--network-dns-manage":
  80. ManageNetworkDnsMenuItem_Click(this, EventArgs.Empty);
  81. break;
  82. case "--service-start":
  83. StartServiceMenuItem_Click(this, EventArgs.Empty);
  84. break;
  85. case "--service-restart":
  86. RestartServiceMenuItem_Click(this, EventArgs.Empty);
  87. break;
  88. case "--service-stop":
  89. StopServiceMenuItem_Click(this, EventArgs.Empty);
  90. break;
  91. case "--first-run":
  92. bool usingLoopbackAsDns = false;
  93. try
  94. {
  95. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  96. {
  97. if (nic.OperationalStatus != OperationalStatus.Up)
  98. continue;
  99. foreach (IPAddress dnsAddress in nic.GetIPProperties().DnsAddresses)
  100. {
  101. if (IPAddress.IsLoopback(dnsAddress))
  102. {
  103. usingLoopbackAsDns = true;
  104. break;
  105. }
  106. }
  107. if (usingLoopbackAsDns)
  108. break;
  109. }
  110. }
  111. catch
  112. { }
  113. if (!usingLoopbackAsDns && MessageBox.Show("Do you want to update this computer's network connections to use the locally running Technitium DNS Server?\r\n\r\nNote! It is recommended that you use the locally running Technitium DNS Server unless you explicitly want to keep using your existing network DNS configuration.", "Switch Network DNS? - Technitium DNS Server", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
  114. SetNetworkDns(new DnsProvider("Technitium", new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback }));
  115. break;
  116. }
  117. }
  118. }
  119. #endregion
  120. #region IDisposable
  121. protected override void Dispose(bool disposing)
  122. {
  123. if (disposing)
  124. {
  125. TrayIcon?.Dispose();
  126. }
  127. base.Dispose(disposing);
  128. }
  129. #endregion
  130. #region private
  131. private void InitializeComponent()
  132. {
  133. //
  134. // TrayIconContextMenu
  135. //
  136. TrayIconContextMenu = new ContextMenuStrip();
  137. TrayIconContextMenu.SuspendLayout();
  138. //
  139. // TrayIcon
  140. //
  141. TrayIcon = new NotifyIcon();
  142. TrayIcon.Icon = Resources.logo2;
  143. TrayIcon.Visible = true;
  144. TrayIcon.MouseUp += TrayIcon_MouseUp;
  145. TrayIcon.ContextMenuStrip = TrayIconContextMenu;
  146. TrayIcon.Text = Resources.ServiceName;
  147. //
  148. // DashboardMenuItem
  149. //
  150. DashboardMenuItem = new ToolStripMenuItem();
  151. DashboardMenuItem.Name = "DashboardMenuItem";
  152. DashboardMenuItem.Text = Resources.DashboardMenuItem;
  153. DashboardMenuItem.Click += DashboardMenuItem_Click;
  154. //
  155. // NetworkDnsMenuItem
  156. //
  157. NetworkDnsMenuItem = new ToolStripMenuItem();
  158. NetworkDnsMenuItem.Name = "NetworkDnsMenuItem";
  159. NetworkDnsMenuItem.Text = Resources.NetworkDnsMenuItem;
  160. DefaultNetworkDnsMenuItem = new ToolStripMenuItem("Default");
  161. DefaultNetworkDnsMenuItem.Click += DefaultNetworkDnsMenuItem_Click;
  162. ManageNetworkDnsMenuItem = new ToolStripMenuItem("Manage");
  163. ManageNetworkDnsMenuItem.Click += ManageNetworkDnsMenuItem_Click;
  164. //
  165. // ServiceMenuItem
  166. //
  167. ServiceMenuItem = new ToolStripMenuItem();
  168. ServiceMenuItem.Name = "ServiceMenuItem";
  169. ServiceMenuItem.Text = Resources.ServiceMenuItem;
  170. StartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStartMenuItem);
  171. StartServiceMenuItem.Click += StartServiceMenuItem_Click;
  172. RestartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceRestartMenuItem);
  173. RestartServiceMenuItem.Click += RestartServiceMenuItem_Click;
  174. StopServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStopMenuItem);
  175. StopServiceMenuItem.Click += StopServiceMenuItem_Click;
  176. ServiceMenuItem.DropDownItems.AddRange(new ToolStripItem[]
  177. {
  178. StartServiceMenuItem,
  179. RestartServiceMenuItem,
  180. StopServiceMenuItem
  181. });
  182. //
  183. // AboutMenuItem
  184. //
  185. AboutMenuItem = new ToolStripMenuItem();
  186. AboutMenuItem.Name = "AboutMenuItem";
  187. AboutMenuItem.Text = Resources.AboutMenuItem;
  188. AboutMenuItem.Click += AboutMenuItem_Click;
  189. //
  190. // AutoStartMenuItem
  191. //
  192. AutoStartMenuItem = new ToolStripMenuItem();
  193. AutoStartMenuItem.Name = "AutoStartMenuItem";
  194. AutoStartMenuItem.Text = "&Auto Start Icon";
  195. AutoStartMenuItem.Click += AutoStartMenuItem_Click;
  196. //
  197. // ExitMenuItem
  198. //
  199. ExitMenuItem = new ToolStripMenuItem();
  200. ExitMenuItem.Name = "ExitMenuItem";
  201. ExitMenuItem.Text = Resources.ExitMenuItem;
  202. ExitMenuItem.Click += ExitMenuItem_Click;
  203. TrayIconContextMenu.Items.AddRange(new ToolStripItem[]
  204. {
  205. DashboardMenuItem,
  206. new ToolStripSeparator(),
  207. NetworkDnsMenuItem,
  208. ServiceMenuItem,
  209. AboutMenuItem,
  210. new ToolStripSeparator(),
  211. AutoStartMenuItem,
  212. ExitMenuItem
  213. });
  214. TrayIconContextMenu.ResumeLayout(false);
  215. }
  216. private void LoadConfig()
  217. {
  218. try
  219. {
  220. using (FileStream fS = new FileStream(_configFile, FileMode.Open, FileAccess.Read))
  221. {
  222. BinaryReader bR = new BinaryReader(fS);
  223. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DT")
  224. throw new InvalidDataException("Invalid DNS Server System Tray App config file format.");
  225. switch (bR.ReadByte())
  226. {
  227. case 1:
  228. int count = bR.ReadInt32();
  229. _dnsProviders.Clear();
  230. for (int i = 0; i < count; i++)
  231. _dnsProviders.Add(new DnsProvider(bR));
  232. _dnsProviders.Sort();
  233. break;
  234. default:
  235. throw new NotSupportedException("DNS Server System Tray App config file format is not supported.");
  236. }
  237. }
  238. }
  239. catch (FileNotFoundException)
  240. {
  241. _dnsProviders.Clear();
  242. _dnsProviders.AddRange(DnsProvider.GetDefaultProviders());
  243. _dnsProviders.Sort();
  244. }
  245. catch (Exception ex)
  246. {
  247. MessageBox.Show("Error occured while loading config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  248. }
  249. }
  250. private void SaveConfig()
  251. {
  252. try
  253. {
  254. using (FileStream fS = new FileStream(_configFile, FileMode.Create, FileAccess.Write))
  255. {
  256. BinaryWriter bW = new BinaryWriter(fS);
  257. bW.Write(Encoding.ASCII.GetBytes("DT"));
  258. bW.Write((byte)1);
  259. bW.Write(_dnsProviders.Count);
  260. foreach (DnsProvider dnsProvider in _dnsProviders)
  261. dnsProvider.WriteTo(bW);
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. MessageBox.Show("Error occured while saving config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  267. }
  268. }
  269. private static void SetNetworkDns(DnsProvider dnsProvider)
  270. {
  271. if (!Program.IsAdmin)
  272. {
  273. Program.RunAsAdmin("--network-dns-item " + dnsProvider.Name);
  274. return;
  275. }
  276. try
  277. {
  278. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  279. {
  280. if (nic.OperationalStatus != OperationalStatus.Up)
  281. continue;
  282. IPInterfaceProperties properties = nic.GetIPProperties();
  283. if ((properties.DnsAddresses.Count > 0) && !properties.DnsAddresses[0].IsIPv6SiteLocal)
  284. SetNameServer(nic, dnsProvider.Addresses);
  285. }
  286. MessageBox.Show("The network DNS servers were set to " + dnsProvider.Name + " successfully.", dnsProvider.Name + " Configured - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  287. }
  288. catch (Exception ex)
  289. {
  290. MessageBox.Show("Error occured while setting " + dnsProvider.Name + " as network DNS server. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  291. }
  292. }
  293. private static void SetNameServer(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  294. {
  295. SetNameServerIPv4(nic, dnsAddresses);
  296. SetNameServerIPv6(nic, dnsAddresses);
  297. }
  298. private static void SetNameServerIPv4(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  299. {
  300. ManagementClass networkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
  301. ManagementObjectCollection instances = networkAdapterConfig.GetInstances();
  302. foreach (ManagementObject obj in instances)
  303. {
  304. if ((bool)obj["IPEnabled"] && obj["SettingID"].Equals(nic.Id))
  305. {
  306. List<string> dnsServers = new List<string>();
  307. foreach (IPAddress dnsAddress in dnsAddresses)
  308. {
  309. if (dnsAddress.AddressFamily != AddressFamily.InterNetwork)
  310. continue;
  311. dnsServers.Add(dnsAddress.ToString());
  312. }
  313. ManagementBaseObject objParameter = obj.GetMethodParameters("SetDNSServerSearchOrder");
  314. objParameter["DNSServerSearchOrder"] = dnsServers.ToArray();
  315. ManagementBaseObject response = obj.InvokeMethod("SetDNSServerSearchOrder", objParameter, null);
  316. uint returnValue = (uint)response.GetPropertyValue("ReturnValue");
  317. switch (returnValue)
  318. {
  319. case 0: //success
  320. case 1: //reboot required
  321. break;
  322. case 64:
  323. throw new Exception("Method not supported on this platform. WMI error code: " + returnValue);
  324. case 65:
  325. throw new Exception("Unknown failure. WMI error code: " + returnValue);
  326. case 70:
  327. throw new Exception("Invalid IP address. WMI error code: " + returnValue);
  328. case 96:
  329. throw new Exception("Unable to notify DNS service. WMI error code: " + returnValue);
  330. case 97:
  331. throw new Exception("Interface not configurable. WMI error code: " + returnValue);
  332. default:
  333. throw new Exception("WMI error code: " + returnValue);
  334. }
  335. break;
  336. }
  337. }
  338. }
  339. private static void SetNameServerIPv6(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  340. {
  341. //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\{}
  342. string nameServer = null;
  343. foreach (IPAddress dnsAddress in dnsAddresses)
  344. {
  345. if (dnsAddress.AddressFamily != AddressFamily.InterNetworkV6)
  346. continue;
  347. if (nameServer == null)
  348. nameServer = dnsAddress.ToString();
  349. else
  350. nameServer += "," + dnsAddress.ToString();
  351. }
  352. if (nameServer == null)
  353. nameServer = "";
  354. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\" + nic.Id, true))
  355. {
  356. if (key != null)
  357. key.SetValue("NameServer", nameServer, RegistryValueKind.String);
  358. }
  359. }
  360. private static bool AddressExists(ICollection<IPAddress> checkAddresses, ICollection<IPAddress> addresses)
  361. {
  362. foreach (IPAddress checkAddress in checkAddresses)
  363. {
  364. foreach (IPAddress address in addresses)
  365. {
  366. if (checkAddress.Equals(address))
  367. return true;
  368. }
  369. }
  370. return false;
  371. }
  372. private void TrayIcon_MouseUp(object sender, MouseEventArgs e)
  373. {
  374. if (e.Button == MouseButtons.Right)
  375. {
  376. #region Network DNS
  377. List<IPAddress> networkDnsAddresses = new List<IPAddress>();
  378. try
  379. {
  380. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  381. {
  382. if (nic.OperationalStatus != OperationalStatus.Up)
  383. continue;
  384. networkDnsAddresses.AddRange(nic.GetIPProperties().DnsAddresses);
  385. }
  386. }
  387. catch
  388. { }
  389. NetworkDnsMenuItem.DropDownItems.Clear();
  390. NetworkDnsMenuItem.DropDownItems.Add(DefaultNetworkDnsMenuItem);
  391. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  392. bool noItemChecked = true;
  393. DefaultNetworkDnsMenuItem.Checked = false;
  394. foreach (DnsProvider dnsProvider in _dnsProviders)
  395. {
  396. ToolStripMenuItem item = new ToolStripMenuItem(dnsProvider.Name);
  397. item.Tag = dnsProvider;
  398. item.Click += NetworkDnsMenuSubItem_Click;
  399. if (AddressExists(networkDnsAddresses, dnsProvider.Addresses))
  400. {
  401. item.Checked = true;
  402. noItemChecked = false;
  403. }
  404. NetworkDnsMenuItem.DropDownItems.Add(item);
  405. }
  406. if (noItemChecked)
  407. {
  408. foreach (IPAddress dnsAddress in networkDnsAddresses)
  409. {
  410. if (!dnsAddress.IsIPv6SiteLocal)
  411. {
  412. DefaultNetworkDnsMenuItem.Checked = true;
  413. break;
  414. }
  415. }
  416. }
  417. if (_dnsProviders.Count > 0)
  418. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  419. NetworkDnsMenuItem.DropDownItems.Add(ManageNetworkDnsMenuItem);
  420. #endregion
  421. #region service
  422. try
  423. {
  424. _service.Refresh();
  425. switch (_service.Status)
  426. {
  427. case ServiceControllerStatus.Stopped:
  428. DashboardMenuItem.Enabled = false;
  429. StartServiceMenuItem.Enabled = true;
  430. RestartServiceMenuItem.Enabled = false;
  431. StopServiceMenuItem.Enabled = false;
  432. break;
  433. case ServiceControllerStatus.Running:
  434. DashboardMenuItem.Enabled = true;
  435. StartServiceMenuItem.Enabled = false;
  436. RestartServiceMenuItem.Enabled = true;
  437. StopServiceMenuItem.Enabled = true;
  438. break;
  439. default:
  440. DashboardMenuItem.Enabled = false;
  441. StartServiceMenuItem.Enabled = false;
  442. RestartServiceMenuItem.Enabled = false;
  443. StopServiceMenuItem.Enabled = false;
  444. break;
  445. }
  446. ServiceMenuItem.Enabled = true;
  447. }
  448. catch
  449. {
  450. DashboardMenuItem.Enabled = false;
  451. ServiceMenuItem.Enabled = false;
  452. }
  453. #endregion
  454. #region auto start
  455. try
  456. {
  457. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  458. {
  459. if (key != null)
  460. {
  461. string autoStartPath = key.GetValue("Technitium DNS System Tray") as string;
  462. AutoStartMenuItem.Checked = (autoStartPath != null) && autoStartPath.Equals("\"" + Program.APP_PATH + "\"");
  463. }
  464. }
  465. }
  466. catch
  467. { }
  468. #endregion
  469. TrayIcon.ShowContextMenu();
  470. }
  471. }
  472. private void DashboardMenuItem_Click(object sender, EventArgs e)
  473. {
  474. int port = 5380;
  475. try
  476. {
  477. //try finding port number from dns config file
  478. string dnsConfigFile = Path.Combine(Path.GetDirectoryName(Program.APP_PATH), "config", "dns.config");
  479. using (FileStream fS = new FileStream(dnsConfigFile, FileMode.Open, FileAccess.Read))
  480. {
  481. BinaryReader bR = new BinaryReader(fS);
  482. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
  483. throw new InvalidDataException("DNS Server config file format is invalid.");
  484. int version = bR.ReadByte();
  485. if (version >= 28)
  486. {
  487. port = bR.ReadInt32();
  488. }
  489. else if (version > 1)
  490. {
  491. string serverDomain = bR.ReadShortString();
  492. port = bR.ReadInt32();
  493. }
  494. }
  495. }
  496. catch
  497. { }
  498. ProcessStartInfo processInfo = new ProcessStartInfo("http://localhost:" + port.ToString());
  499. processInfo.UseShellExecute = true;
  500. processInfo.Verb = "open";
  501. Process.Start(processInfo);
  502. }
  503. private void DefaultNetworkDnsMenuItem_Click(object sender, EventArgs e)
  504. {
  505. SetNetworkDnsToDefault();
  506. }
  507. private void SetNetworkDnsToDefault(bool silent = false)
  508. {
  509. if (!Program.IsAdmin)
  510. {
  511. if (!silent)
  512. Program.RunAsAdmin("--network-dns-default");
  513. return;
  514. }
  515. try
  516. {
  517. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  518. {
  519. if (nic.OperationalStatus != OperationalStatus.Up)
  520. continue;
  521. SetNameServerIPv6(nic, Array.Empty<IPAddress>());
  522. try
  523. {
  524. IPInterfaceProperties properties = nic.GetIPProperties();
  525. if (properties.GetIPv4Properties().IsDhcpEnabled)
  526. {
  527. SetNameServerIPv4(nic, Array.Empty<IPAddress>());
  528. }
  529. else if (properties.GatewayAddresses.Count > 0)
  530. {
  531. SetNameServerIPv4(nic, new IPAddress[] { properties.GatewayAddresses[0].Address });
  532. }
  533. else
  534. {
  535. SetNameServerIPv4(nic, Array.Empty<IPAddress>());
  536. }
  537. }
  538. catch (NetworkInformationException)
  539. { }
  540. }
  541. if (!silent)
  542. MessageBox.Show("The network DNS servers were set to default successfully.", "Default DNS Set - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  543. }
  544. catch (Exception ex)
  545. {
  546. if (!silent)
  547. MessageBox.Show("Error occured while setting default network DNS servers. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  548. }
  549. }
  550. private void ManageNetworkDnsMenuItem_Click(object sender, EventArgs e)
  551. {
  552. if (!Program.IsAdmin)
  553. {
  554. Program.RunAsAdmin("--network-dns-manage");
  555. return;
  556. }
  557. using (frmManageDnsProviders frm = new frmManageDnsProviders(_dnsProviders))
  558. {
  559. if (frm.ShowDialog() == DialogResult.OK)
  560. {
  561. _dnsProviders.Clear();
  562. _dnsProviders.AddRange(frm.DnsProviders);
  563. _dnsProviders.Sort();
  564. SaveConfig();
  565. }
  566. }
  567. }
  568. private void NetworkDnsMenuSubItem_Click(object sender, EventArgs e)
  569. {
  570. ToolStripMenuItem item = sender as ToolStripMenuItem;
  571. DnsProvider dnsProvider = item.Tag as DnsProvider;
  572. SetNetworkDns(dnsProvider);
  573. }
  574. private void StartServiceMenuItem_Click(object sender, EventArgs e)
  575. {
  576. if (!Program.IsAdmin)
  577. {
  578. Program.RunAsAdmin("--service-start");
  579. return;
  580. }
  581. try
  582. {
  583. _service.Start();
  584. _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  585. MessageBox.Show("The service was started successfully.", "Service Started - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  586. }
  587. catch (System.ServiceProcess.TimeoutException ex)
  588. {
  589. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  590. }
  591. catch (Exception ex)
  592. {
  593. MessageBox.Show("Error occured while starting service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  594. }
  595. }
  596. private void RestartServiceMenuItem_Click(object sender, EventArgs e)
  597. {
  598. if (!Program.IsAdmin)
  599. {
  600. Program.RunAsAdmin("--service-restart");
  601. return;
  602. }
  603. try
  604. {
  605. _service.Stop();
  606. _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  607. _service.Start();
  608. _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  609. MessageBox.Show("The service was restarted successfully.", "Service Restarted - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  610. }
  611. catch (System.ServiceProcess.TimeoutException ex)
  612. {
  613. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  614. }
  615. catch (Exception ex)
  616. {
  617. MessageBox.Show("Error occured while restarting service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  618. }
  619. }
  620. private void StopServiceMenuItem_Click(object sender, EventArgs e)
  621. {
  622. if (!Program.IsAdmin)
  623. {
  624. Program.RunAsAdmin("--service-stop");
  625. return;
  626. }
  627. try
  628. {
  629. _service.Stop();
  630. _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  631. MessageBox.Show("The service was stopped successfully.", "Service Stopped - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  632. }
  633. catch (System.ServiceProcess.TimeoutException ex)
  634. {
  635. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  636. }
  637. catch (Exception ex)
  638. {
  639. MessageBox.Show("Error occured while stopping service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  640. }
  641. }
  642. private void AboutMenuItem_Click(object sender, EventArgs e)
  643. {
  644. using (frmAbout frm = new frmAbout())
  645. {
  646. frm.ShowDialog();
  647. }
  648. }
  649. private void AutoStartMenuItem_Click(object sender, EventArgs e)
  650. {
  651. if (AutoStartMenuItem.Checked)
  652. {
  653. //remove
  654. try
  655. {
  656. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  657. {
  658. if (key != null)
  659. key.DeleteValue("Technitium DNS System Tray", false);
  660. }
  661. }
  662. catch (Exception ex)
  663. {
  664. MessageBox.Show("Error occured while removing auto start registry entry. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  665. }
  666. }
  667. else
  668. {
  669. //add
  670. try
  671. {
  672. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  673. {
  674. if (key != null)
  675. key.SetValue("Technitium DNS System Tray", "\"" + Program.APP_PATH + "\"", RegistryValueKind.String);
  676. }
  677. }
  678. catch (Exception ex)
  679. {
  680. MessageBox.Show("Error occured while adding auto start registry entry. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  681. }
  682. }
  683. }
  684. private void ExitMenuItem_Click(object sender, EventArgs e)
  685. {
  686. if (MessageBox.Show(Resources.AreYouSureYouWantToQuit, Resources.Quit + " - " + Resources.ServiceName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
  687. Application.Exit();
  688. }
  689. #endregion
  690. }
  691. }