/// <summary> /// Queries asn.cymru.com for a TXT record /// {Reverse-IPaddress}.origin.asn.cymru.com /// </summary> /// <param name="ipAddress"></param> /// <returns></returns> //internal string GetASN(string ipAddress) //{ // string asnResult = string.Empty; // try // { // Response resp = _resolver.Query(string.Join(".", ipAddress.Split('.').Reverse()) + ".origin.asn.cymru.com", QType.TXT, QClass.IN); // if (resp.Answers.Count > 0) // { // RecordTXT txtRecord = resp.Answers[0].RECORD as RecordTXT; // if (!Object.Equals(txtRecord, null)) // asnResult = txtRecord.ASN; // } // } // catch (Exception e) // { // ExceptionExtensions.LogError(e, "Dig.GetASN", "IPAddress: " + ipAddress); // } // return asnResult; //} internal string GetASN(string ipAddress) { string asnResult = string.Empty; try { DnsQuery _dnsQuery = new DnsQuery(_dnsServers, string.Join(".", ipAddress.Split('.').Reverse()) + ".origin.asn.cymru.com"); if (Object.Equals(null, _dnsQuery)) { ExceptionExtensions.LogError(new ArgumentNullException("dnsQuery is NULL"), "Dig.GetASN", "dns servers count: " + _dnsServers.Count); return(null); } DnsAnswer resp = _dnsQuery.QueryServers(RecordType.TXT); if (!Object.Equals(null, resp) && resp.Answers.Count > 0) { TxtRecord txtRecord = resp.Answers[0].Data as TxtRecord; if (!Object.Equals(txtRecord, null)) { asnResult = txtRecord.ASN; } } } catch (Exception e) { ExceptionExtensions.LogError(e, "Dig.GetASN", "IPAddress: " + ipAddress); } return(asnResult); }
static void Main(string[] args) { Mono.Zeroconf.RegisterService bonjourBrowserService = null; //------------------------------------------------- //begin setup zeroconf bonjourBrowserService = new RegisterService(); bonjourBrowserService.Name = "CNCTouch Wi-fi Server"; bonjourBrowserService.RegType = "_cnctouch._tcp"; bonjourBrowserService.ReplyDomain = "local."; bonjourBrowserService.Port = 2030; // TxtRecords are optional TxtRecord txt_record = new TxtRecord(); txt_record.Add("Password", "false"); bonjourBrowserService.TxtRecord = txt_record; bonjourBrowserService.Register(); // End setup zeroconf //--------------------------------------------------- Console.ReadKey(); }
private void PluginForm_Load(object sender, EventArgs e) { Console.WriteLine("PluginForm_Load"); CheckForIllegalCrossThreadCalls = false; //Pluginmain.loopstop = false; Console.WriteLine("CLR version from PluginForm_Load: {0}", Environment.Version); //------------------------------------------------- //begin setup zeroconf bonjourBrowserService = new RegisterService(); // <-- this line is where we get the problem bonjourBrowserService.Name = "CNCTouch Wi-fi Server"; bonjourBrowserService.RegType = "_cnctouch._tcp"; bonjourBrowserService.ReplyDomain = "local."; bonjourBrowserService.Port = 2030; // TxtRecords are optional TxtRecord txt_record = new TxtRecord(); txt_record.Add("Password", "false"); bonjourBrowserService.TxtRecord = txt_record; bonjourBrowserService.Register(); // End setup zeroconf //--------------------------------------------------- }
public static String ClientQuery(string domain) { List <IPAddress> dnss = new List <IPAddress> { }; dnss.AddRange(Dns.GetHostAddresses(dns)); var dnsClient = new DnsClient(dnss, 60); DnsMessage dnsMessage = dnsClient.Resolve(domain, RecordType.Txt); if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) { Console.WriteLine("DNS request failed"); return(null); } else { foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords) { TxtRecord txtRecord = dnsRecord as TxtRecord; if (txtRecord != null) { return(txtRecord.TextData.ToString()); } } return(null); } }
private void PublishZeroconf() { var name = "Lightswitch " + Environment.MachineName; _netservice = new RegisterService { Name = name, RegType = "_lightswitch._tcp", ReplyDomain = "", Port = (short)PortSetting }; _netservice.Response += netservice_Response; // TxtRecords are optional var txtRecord = new TxtRecord { { "txtvers", "1" }, { "ServiceName", name }, { "MachineName", Environment.MachineName }, { "OS", Environment.OSVersion.ToString() }, { "IPAddress", "127.0.0.1" }, { "Version", Utils.ApplicationNameAndVersion } }; //txt_record.Add("Password", "false"); _netservice.TxtRecord = txtRecord; _netservice.Register(); }
private static async Task ValidateChallengeCompletion(AuthorizationChallenge challenge, string domainName) { var maxRetries = 50; var delay = TimeSpan.FromSeconds(5); if (challenge.Type != "dns-01") { throw new Exception("Invalid challenge type."); } Program.LogLine($"Trying to validate an entry exists for _acme-challenge.{domainName} every {delay} for a maximum of {maxRetries * delay}", true); for (var i = 0; i < maxRetries; i++) { var lookup = new LookupClient(IPAddress.Parse("1.1.1.1")); IDnsQueryResponse result = await lookup.QueryAsync($"_acme-challenge.{domainName}", QueryType.TXT); TxtRecord record = result.Answers.TxtRecords().Where(txt => txt.Text.Contains(challenge.AuthorizationToken)).FirstOrDefault(); if (record != null) { Program.LogLine($"Succesfully validated a DNS entry exists for {domainName}.", true); return; } await Task.Delay(delay); } throw new Exception($"Failed to validate {domainName}"); }
/// <summary> /// Publish the service via Bonjour protocol to the network /// </summary> internal void PublishBonjourService() { if (_servicePublishing) { Logger.Debug("WifiRemote: Already in the process of publishing the Bonjour service. Aborting publish ..."); return; } _servicePublishing = true; try { _publishService = new RegisterService(); _publishService.Name = _serviceName; _publishService.RegType = serviceType; _publishService.ReplyDomain = _domain; _publishService.Port = Convert.ToInt16(_port); // Get the MAC addresses and set it as bonjour txt record // Needed by the clients to implement wake on lan TxtRecord txt_record = new TxtRecord(); txt_record.Add("hwAddr", GetHardwareAddresses()); _publishService.TxtRecord = txt_record; _publishService.Response += PublishService_Response; _publishService.Register(); } catch (Exception ex) { Logger.Debug("WifiRemote: Bonjour enabled but failed to publish!", ex); Logger.Info("WifiRemote: Disabling Bonjour for this session. If not installed get it at http://support.apple.com/downloads/Bonjour_for_Windows"); _disableBonjour = true; return; } }
void UpdateService() { if (service != null) { DestroyService(); } service = new RegisterService(); service.Name = "Augmenta - " + _name; service.RegType = "_osc._udp"; service.ReplyDomain = "local."; service.UPort = (ushort)_port; if (_keys != null && _keys.Count > 0) { TxtRecord txt = new TxtRecord(); foreach (KeyValuePair <string, string> kv in _keys) { txt.Add(kv.Key, kv.Value); } service.TxtRecord = txt; } service.Register(); }
/// <summary> /// Acts as a Factory which reads QType from Immutable IResource param to return concrete type which implements IResource. /// </summary> /// <param name="data"></param> /// <param name="position"></param> /// <param name="resource"></param> /// <returns></returns> private static IResource ReadAnswer(ref byte[] data, int position, IResource resource) { switch (resource.Type) { case QType.TXT: return(TxtRecord.Parse(data, position, resource)); case QType.MX: return(MxRecord.Parse(data, position, resource)); case QType.A: return(ARecord.Parse(data, position, resource)); case QType.SOA: return(SoaRecord.Parse(data, position, resource)); case QType.NS: return(NsRecord.Parse(data, position, resource)); case QType.CNAME: return(CNameRecord.Parse(data, position, resource)); } return(null); //TODO: Thrown Exception Here }
/// <summary> /// Start new broadcast service /// </summary> /// <param name="type">Type of discovery</param> /// <param name="nameToBroadcast">The name of the service that needs to be broadcasted</param> /// <param name="physicalLocation">The physical location of the service that needs to be broadcasted</param> /// <param name="code">code to be broadcasted (e.g. device id)</param> /// <param name="addressToBroadcast">The address of the service that needs to be broadcasted</param> public void Start(DiscoveryType type, string nameToBroadcast, string physicalLocation, string code, Uri addressToBroadcast) { DiscoveryType = type; switch (DiscoveryType) { case DiscoveryType.WsDiscovery: { Ip = Net.GetIp(IpType.All); Port = 7985; Address = "http://" + Ip + ":" + Port + "/"; _discoveryHost = new ServiceHost(new DiscoveyService()); var serviceEndpoint = _discoveryHost.AddServiceEndpoint(typeof(IDiscovery), new WebHttpBinding(), Net.GetUrl(Ip, Port, "")); serviceEndpoint.Behaviors.Add(new WebHttpBehavior()); var broadcaster = new EndpointDiscoveryBehavior(); broadcaster.Extensions.Add(nameToBroadcast.ToXElement <string>()); broadcaster.Extensions.Add(physicalLocation.ToXElement <string>()); broadcaster.Extensions.Add(addressToBroadcast.ToString().ToXElement <string>()); broadcaster.Extensions.Add(code.ToXElement <string>()); serviceEndpoint.Behaviors.Add(broadcaster); _discoveryHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior()); _discoveryHost.Description.Endpoints.Add(new UdpDiscoveryEndpoint()); _discoveryHost.Open(); IsRunning = true; Debug.WriteLine(DiscoveryType.ToString() + " is started"); } break; case DiscoveryType.Zeroconf: { _service = new RegisterService { Name = nameToBroadcast, RegType = "_am._tcp", ReplyDomain = "local", Port = 3689 }; // TxtRecords are optional var txtRecord = new TxtRecord { { "name", nameToBroadcast }, { "addr", addressToBroadcast.ToString() }, { "loc", physicalLocation }, { "code", code } }; _service.TxtRecord = txtRecord; _service.Response += service_Response; _service.Register(); Debug.WriteLine(DiscoveryType.ToString() + " is started"); } break; } }
public bool Publish(int port, string appendToName) { Port = port; RegisterService service; try { service = new RegisterService(); } catch (Exception e) { BonjourInstalled = false; log.Error("Unable to register service: " + e.Message); ShowBonjourDialog(); return(false); } string name; try { name = Environment.MachineName.ToLower(); } catch (Exception e) { name = "PocketStrafe Companion"; } name += (" - " + appendToName); service.Name = name; service.RegType = "_IAmTheBirdman._udp"; service.ReplyDomain = "local."; service.Port = (short)port; TxtRecord record = null; log.Info(String.Format("!! Registering name = '{0}', type = '{1}', domain = '{2}'", service.Name, service.RegType, service.ReplyDomain)); service.Response += OnRegisterServiceResponse; service.Register(); PublishedServices.Add(service); DeviceNames.Add(appendToName); DeviceCount = DeviceNames.Count; return(true); }
/// <summary> /// Register the Zeroconf service and initialises the receiving thread for communication with the client. /// If pressed again, the button will terminate the receiving thread to end communication with the client. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected internal void BtnStart_Click(object sender, RoutedEventArgs e) { if (service_Running == false) { service_Running = true; Console.WriteLine("Sample service publisher using arkane.Mono.Zeroconf version\n"); service.Name = "Assistive Technology Server"; service.RegType = "_assistive-tech._udp"; service.ReplyDomain = "local."; service.Port = 1024; TxtRecord txt_record = new TxtRecord { { "service", "Assistive Technology Technology" }, { "version", "1.0.0" } }; service.TxtRecord = txt_record; receiver.Client.ReceiveTimeout = 120000; try { // Register the service if it is not registered // The if mainly serves to prevent a second registration if (!service_registered) { service.Register(); service_registered = true; } string txtMsg = "service has been registered"; Console.WriteLine("{0} " + txtMsg, service.Name); DisplayMessage(txtMsg, true); // Change the text of the Start button to Stop Services BtnStart.Content = "Stop Service"; } catch (Exception ex) { DisplayMessage(ex.Message, true); Console.WriteLine("Service Error: {0}", ex.ToString()); } // Start a thread with the method GetMessge ctThread = new Thread(GetMessage); ctThread.Start(); } else { EndZeroconfService(); BtnStart.Content = "Start Services"; } }
public override async Task <bool> TestAsync(IEnumerable <string> hostNames) { try { foreach (var hostName in hostNames.Select(n => n.StartsWith("*.") ? n.Substring(2) : n).Distinct(StringComparer.OrdinalIgnoreCase)) { var acmeChallengeName = $"_acme-challenge.{hostName}"; // Test NS configuration of domain var cnameQuery = await lookupClient.QueryAsync(acmeChallengeName, QueryType.CNAME).ConfigureAwait(true); var cnameRecord = cnameQuery.Answers.CnameRecords().SingleOrDefault(); if (cnameRecord == null) { Log.WriteLine($"No DNS CNAME record found for {acmeChallengeName}"); return(false); } var fullName = cnameRecord.CanonicalName.Value.TrimEnd('.'); if (!fullName.EndsWith("." + dnsDomain, StringComparison.OrdinalIgnoreCase)) { Log.WriteLine($"The DNS CNAME record for {acmeChallengeName} points to {fullName} which is not part of {dnsDomain}"); return(false); } Log.WriteVerboseLine($"The DNS CNAME record for {acmeChallengeName} points to {fullName}"); // Test DNS roundtrip with GUID to prevent caching issues var id = Guid.NewGuid().ToString("n"); using (var record = new TxtRecord(this, $"_{id}.{dnsDomain}", id)) { var query = await lookupClient.QueryAsync(record.FullName, QueryType.TXT).ConfigureAwait(true); var txtRecord = query.Answers.TxtRecords().SingleOrDefault(); if (txtRecord == null) { Log.WriteLine($"The DNS TXT test record was added to {dnsDomain} on {dnsServer}, but could not be retrieved via DNS"); return(false); } if (!txtRecord.Text.Contains(id)) { Log.WriteLine($"The DNS TXT test record does not have the expected content"); return(false); } } } return(true); } catch (ManagementException ex) { Log.WriteLine($"Error 0x{(int)ex.ErrorCode:x} occurred while communicating to the DNS server: {ex.Message}"); return(false); } }
/// <summary> /// Do DNS queries to get any TXT records associated with the custom hostname the user has entered. /// Puts the string output of all of the TXT records into the AppService argument so the list can be used later. /// </summary> /// <param name="appService"></param> public static void GetHostnameTxtRecords(AppService appService, DNSCheckErrors dnsCheckErrors) { //IDnsResolver resolver = new DnsStubResolver(); // This is moved into the AppService class itself to prevent making the string multiple times // string fullHostnameDNSStyle = appService.CustomHostname + "."; try { //List<TxtRecord> txtRecords = DnsResolverExtensions.Resolve<TxtRecord>(resolver, appService.CustomHostname, RecordType.Txt, RecordClass.Any); List <string> txts = new List <string>(); DnsMessage dnsMessage = DnsClient.Default.Resolve(DomainName.Parse(appService.CustomHostname), RecordType.Txt); if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) { throw new Exception("DNS request failed"); } else { foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords) { if (dnsRecord.RecordType == RecordType.Txt && dnsRecord.Name.ToString() == appService.CustomHostnameDNSStyle) { TxtRecord txtRecord = dnsRecord as TxtRecord; if (txtRecord != null) { txts.Add(txtRecord.TextData.ToString()); } } } } /* foreach (TxtRecord txtRecord in txtRecords) * { * txts.Add(txtRecord.TextData.ToString()); * } */ appService.HostnameTxtRecords = txts; } catch { dnsCheckErrors.hostnameTxtRecordLookupFailed = true; dnsCheckErrors.currentDNSFailures++; } }
private void AdvertiseService() { try { Logger.Debug("Adding Zeroconf Service _giver._tcp"); TxtRecord txt = new TxtRecord(); txt.Add("User Name", Application.Preferences.UserName); txt.Add("Machine Name", Environment.MachineName); txt.Add("Version", Defines.Version); if (Application.Preferences.PhotoType.CompareTo(Preferences.Local) == 0) { txt.Add("PhotoType", Preferences.Local); txt.Add("Photo", "none"); } else if (Application.Preferences.PhotoType.CompareTo(Preferences.Gravatar) == 0) { txt.Add("PhotoType", Preferences.Gravatar); txt.Add("Photo", Giver.Utilities.GetMd5Sum(Application.Preferences.PhotoLocation)); } else if (Application.Preferences.PhotoType.CompareTo(Preferences.Uri) == 0) { txt.Add("PhotoType", Preferences.Uri); txt.Add("Photo", Application.Preferences.PhotoLocation); } else { txt.Add("PhotoType", Preferences.None); txt.Add("Photo", "none"); } client.Name = "giver on " + Application.Preferences.UserName + "@" + Environment.MachineName; client.RegType = "_giver._tcp"; client.ReplyDomain = "local."; client.Port = (short)port; client.TxtRecord = txt; client.Register(); Logger.Debug("Avahi Service _giver._tcp is added"); } catch (Exception e) { Logger.Debug("Exception adding service: {0}", e.Message); Logger.Debug("Exception is: {0}", e); } }
private static void StartBonjourService() { RegisterService service = new RegisterService(); service.Name = ServiceName; service.RegType = "_hap._tcp"; service.ReplyDomain = "local."; service.Port = unchecked ((short)PORT); //documentated work around // TxtRecords are optional TxtRecord txt_record = new TxtRecord(); txt_record.Add("c#", "1"); txt_record.Add("ff", "0"); txt_record.Add("id", "22:32:43:54:54:01"); txt_record.Add("md", ServiceName); txt_record.Add("pv", "1.0"); txt_record.Add("s#", "1"); txt_record.Add("sf", "1"); txt_record.Add("ci", "2"); service.TxtRecord = txt_record; service.Response += OnRegisterServiceResponse; service.Register(); //ServiceBrowser browser = new ServiceBrowser(); //browser.ServiceAdded += delegate (object o, ServiceBrowseEventArgs aargs) //{ // Console.WriteLine("Found Service: {0}", aargs.Service.Name); // aargs.Service.Resolved += delegate (object oo, ServiceResolvedEventArgs argss) // { // IResolvableService s = (IResolvableService)argss.Service; // Console.WriteLine("Resolved Service: {0} - {1}:{2} ({3} TXT record entries)", // s.FullName, s.HostEntry.AddressList[0], s.Port, s.TxtRecord.Count); // }; // aargs.Service.Resolve(); //}; //browser.Browse("_hap._tcp", "local"); }
public void Register(ushort backup_port, ushort notify_port, ushort rest_port, string server_id, bool is_accepting, bool home_sharing) { m_svc.Name = Environment.MachineName; m_svc.Port = (short)backup_port; m_svc.RegType = SVC_TYPE; m_svc.ReplyDomain = "local."; var txt = new TxtRecord(); txt.Add("server_id", server_id); txt.Add("ws_port", backup_port.ToString()); txt.Add("notify_port", notify_port.ToString()); txt.Add("rest_port", rest_port.ToString()); txt.Add("version", "1.0"); txt.Add("service_name", ServiceName); txt.Add("waiting_for_pair", is_accepting ? "true" : "false"); txt.Add("home_sharing", home_sharing ? "true" : "false"); m_svc.TxtRecord = txt; m_svc.Register(); }
/// <summary> /// Publish ZeroConf, so that WaveBox may advertise itself using mDNS to capable devices /// </summary> public bool Start() { string serverUrl = ServerUtility.GetServerUrl(); if ((object)serverUrl == null) { logger.Error("Could not start ZeroConf service, due to null ServerUrl"); return(false); } // If we're already registered, dispose of it and create a new one if ((object)ZeroConf != null) { this.Stop(); } // Create and register the service try { ZeroConf = new RegisterService(); ZeroConf.Name = Hostname; ZeroConf.RegType = RegType; ZeroConf.ReplyDomain = ReplyDomain; ZeroConf.Port = (short)Injection.Kernel.Get <IServerSettings>().Port; TxtRecord record = new TxtRecord(); record.Add(ServerUrlKey, serverUrl); ZeroConf.TxtRecord = record; ZeroConf.Register(); } catch (Exception e) { logger.Error(e); this.Stop(); return(false); } return(true); }
public async Task SetTxtRecord(string record, string zoneName) { CheckInit(); try { var recordSetParams = new RecordSet(); recordSetParams.TTL = 3600; recordSetParams.TxtRecords = new List <TxtRecord>(); var txt = new TxtRecord(); txt.Value = new List <string>(); txt.Value.Add(record); recordSetParams.TxtRecords.Add(txt); // Create the actual record set in Azure DNS var recordSet = await _client.RecordSets.CreateOrUpdateAsync(_domainRG.DnsZoneRG, zoneName, "@", RecordType.TXT, recordSetParams); } catch (Exception) { throw; } }
public static void Main() { Application.Init(); // Register a sample service RegisterService service = new RegisterService("Fruity Music", null, "_daap._tcp"); TxtRecord record = new TxtRecord(); record.Add("A", "Apples"); record.Add("B", "Bananas"); record.Add("C", "Carrots"); service.Port = 8080; service.TxtRecord = record; service.RegisterAsync(); // Listen for events of some service type ServiceBrowser browser = new ServiceBrowser("_daap._tcp"); browser.ServiceAdded += OnServiceAdded; browser.ServiceRemoved += OnServiceRemoved; browser.StartAsync(); // Unregister our service in 10 seconds GLib.Timeout.Add(10000, delegate { service.Dispose(); return(false); }); // Stop browsing and quit in 15 seconds GLib.Timeout.Add(15000, delegate { browser.Dispose(); Application.Quit(); return(false); }); Application.Run(); }
/// <summary> /// Uses {IP}origin.asn.cymru.com to get ASN and then additional information /// from {AS#}asn.cymru.com to get company name /// </summary> /// <param name="p"></param> /// <returns>Company name from AS records</returns> public string GetWebHostName(string domainName) { string companyName = "None"; string asn = string.Empty; try { IPAddress ip = GetIPAddress(domainName); if (!Object.Equals(ip, null)) { asn = GetASN(ip.ToString()); if (asn.Contains(" ")) { asn = asn.Split(' ')[0]; } DnsQuery _dnsQuery = new DnsQuery(_dnsServers, string.Format("AS{0}.asn.cymru.com", asn)); DnsAnswer resp = _dnsQuery.QueryServers(RecordType.TXT); if (!Object.Equals(resp, null) && resp.Answers.Count > 0 && !Object.Equals(resp.Answers[0], null)) { TxtRecord txtRecord = resp.Answers[0].Data as TxtRecord; if (!Object.Equals(txtRecord, null)) { companyName = txtRecord.COMPANY; } } } } catch (Exception e) { ExceptionExtensions.LogError(e, "Dig.GetWebHostName", "Domain: " + domainName); } return(GetCompanyFromRecordName(companyName, domainName, DigTypeEnum.WEB)); }
/// <summary> /// Create record in Azure DNS /// </summary> /// <param name="record"></param> /// <returns></returns> public override async Task <bool> CreateRecord(DnsValidationRecord record) { var zone = await GetHostedZone(record.Authority.Domain); if (zone == null) { return(false); } // Create or update record set parameters var txtRecord = new TxtRecord(new[] { record.Value }); if (!_recordSets.ContainsKey(zone)) { _recordSets.Add(zone, new Dictionary <string, RecordSet?>()); } var zoneRecords = _recordSets[zone]; var relativeKey = RelativeRecordName(zone, record.Authority.Domain); if (!zoneRecords.ContainsKey(relativeKey)) { zoneRecords.Add( relativeKey, new RecordSet { TTL = 0, TxtRecords = new List <TxtRecord> { txtRecord } }); } else if (zoneRecords[relativeKey] != null) { zoneRecords[relativeKey] !.TxtRecords.Add(txtRecord); } return(true); }
internal static RecordSetData DeserializeRecordSetData(JsonElement element) { Optional <string> etag = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional <IDictionary <string, string> > metadata = default; Optional <long> ttl = default; Optional <string> fqdn = default; Optional <string> provisioningState = default; Optional <WritableSubResource> targetResource = default; Optional <IList <ARecord> > aRecords = default; Optional <IList <AaaaRecord> > aaaaRecords = default; Optional <IList <MxRecord> > mxRecords = default; Optional <IList <NsRecord> > nsRecords = default; Optional <IList <PtrRecord> > ptrRecords = default; Optional <IList <SrvRecord> > srvRecords = default; Optional <IList <TxtRecord> > txtRecords = default; Optional <CnameRecord> cnameRecord = default; Optional <SoaRecord> soaRecord = default; Optional <IList <CaaRecord> > caaRecords = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("etag")) { etag = property.Value.GetString(); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = new ResourceType(property.Value.GetString()); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("metadata")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (var property1 in property0.Value.EnumerateObject()) { dictionary.Add(property1.Name, property1.Value.GetString()); } metadata = dictionary; continue; } if (property0.NameEquals("TTL")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } ttl = property0.Value.GetInt64(); continue; } if (property0.NameEquals("fqdn")) { fqdn = property0.Value.GetString(); continue; } if (property0.NameEquals("provisioningState")) { provisioningState = property0.Value.GetString(); continue; } if (property0.NameEquals("targetResource")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } targetResource = JsonSerializer.Deserialize <WritableSubResource>(property0.Value.ToString()); continue; } if (property0.NameEquals("ARecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <ARecord> array = new List <ARecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(ARecord.DeserializeARecord(item)); } aRecords = array; continue; } if (property0.NameEquals("AAAARecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <AaaaRecord> array = new List <AaaaRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(AaaaRecord.DeserializeAaaaRecord(item)); } aaaaRecords = array; continue; } if (property0.NameEquals("MXRecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <MxRecord> array = new List <MxRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(MxRecord.DeserializeMxRecord(item)); } mxRecords = array; continue; } if (property0.NameEquals("NSRecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <NsRecord> array = new List <NsRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(NsRecord.DeserializeNsRecord(item)); } nsRecords = array; continue; } if (property0.NameEquals("PTRRecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <PtrRecord> array = new List <PtrRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(PtrRecord.DeserializePtrRecord(item)); } ptrRecords = array; continue; } if (property0.NameEquals("SRVRecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <SrvRecord> array = new List <SrvRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(SrvRecord.DeserializeSrvRecord(item)); } srvRecords = array; continue; } if (property0.NameEquals("TXTRecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <TxtRecord> array = new List <TxtRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(TxtRecord.DeserializeTxtRecord(item)); } txtRecords = array; continue; } if (property0.NameEquals("CNAMERecord")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } cnameRecord = CnameRecord.DeserializeCnameRecord(property0.Value); continue; } if (property0.NameEquals("SOARecord")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } soaRecord = SoaRecord.DeserializeSoaRecord(property0.Value); continue; } if (property0.NameEquals("caaRecords")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <CaaRecord> array = new List <CaaRecord>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(CaaRecord.DeserializeCaaRecord(item)); } caaRecords = array; continue; } } continue; } } return(new RecordSetData(id, name, type, systemData, etag.Value, Optional.ToDictionary(metadata), Optional.ToNullable(ttl), fqdn.Value, provisioningState.Value, targetResource, Optional.ToList(aRecords), Optional.ToList(aaaaRecords), Optional.ToList(mxRecords), Optional.ToList(nsRecords), Optional.ToList(ptrRecords), Optional.ToList(srvRecords), Optional.ToList(txtRecords), cnameRecord.Value, soaRecord.Value, Optional.ToList(caaRecords))); }
private void OnResolveFound(int @interface, Protocol protocol, string name, string type, string domain, string host, Protocol aprotocol, string address, ushort port, byte [][] txt, LookupResultFlags flags) { Name = name; RegType = type; AvahiInterface = @interface; AvahiProtocol = protocol; ReplyDomain = domain; TxtRecord = new TxtRecord (txt); this.full_name = String.Format ("{0}.{1}.{2}", name.Replace (" ", "\\032"), type, domain); this.port = (short)port; this.host_target = host; host_entry = new IPHostEntry (); host_entry.AddressList = new IPAddress[1]; if (IPAddress.TryParse (address, out host_entry.AddressList[0]) && protocol == Protocol.IPv6) { host_entry.AddressList[0].ScopeId = @interface; } host_entry.HostName = host; OnResolved (); }
private SpfQualifier CheckHostInternal(IPAddress ip, string sender, string domain, bool expandExplanation, out string explanation) { explanation = String.Empty; if (String.IsNullOrEmpty(domain)) { return(SpfQualifier.None); } if (String.IsNullOrEmpty(sender)) { sender = "postmaster@unknown"; } else if (!sender.Contains('@')) { sender = "postmaster@" + sender; } SpfQualifier result; T record; if (!TryLoadRecords(domain, out record, out result)) { return(result); } if ((record.Terms == null) || (record.Terms.Count == 0)) { return(SpfQualifier.Neutral); } if (record.Terms.OfType <SpfModifier>().GroupBy(m => m.Type).Where(g => (g.Key == SpfModifierType.Exp) || (g.Key == SpfModifierType.Redirect)).Any(g => g.Count() > 1)) { return(SpfQualifier.PermError); } #region Evaluate mechanism foreach (SpfMechanism mechanism in record.Terms.OfType <SpfMechanism>()) { if (LookupCount > DnsLookupLimit) { return(SpfQualifier.PermError); } SpfQualifier qualifier = CheckMechanism(mechanism, ip, sender, domain); if (qualifier != SpfQualifier.None) { result = qualifier; break; } } #endregion #region Evaluate modifiers if (result == SpfQualifier.None) { SpfModifier redirectModifier = record.Terms.OfType <SpfModifier>().FirstOrDefault(m => m.Type == SpfModifierType.Redirect); if (redirectModifier != null) { string redirectDomain = ExpandDomain(redirectModifier.Domain ?? String.Empty, ip, sender, domain); if (String.IsNullOrEmpty(redirectDomain) || (redirectDomain.Equals(domain, StringComparison.InvariantCultureIgnoreCase))) { result = SpfQualifier.PermError; } else { result = CheckHostInternal(ip, sender, redirectDomain, expandExplanation, out explanation); if (result == SpfQualifier.None) { result = SpfQualifier.PermError; } } } } else if ((result == SpfQualifier.Fail) && expandExplanation) { SpfModifier expModifier = record.Terms.OfType <SpfModifier>().Where(m => m.Type == SpfModifierType.Exp).FirstOrDefault(); if (expModifier != null) { string target = ExpandDomain(expModifier.Domain, ip, sender, domain); if (String.IsNullOrEmpty(target)) { explanation = String.Empty; } else { DnsMessage dnsMessage = ResolveDns(target, RecordType.Txt); if ((dnsMessage != null) && (dnsMessage.ReturnCode == ReturnCode.NoError)) { TxtRecord txtRecord = dnsMessage.AnswerRecords.OfType <TxtRecord>().FirstOrDefault(); if (txtRecord != null) { explanation = ExpandDomain(txtRecord.TextData, ip, sender, domain); } } } } } #endregion return((result != SpfQualifier.None) ? result : SpfQualifier.Neutral); }
public static (List <DnsRecordBase> list, ReturnCode statusCode) ResolveOverHttpsByDnsJson(string clientIpAddress, string domainName, string dohUrl, bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A) { string dnsStr; List <DnsRecordBase> recordList = new List <DnsRecordBase>(); try { dnsStr = MyCurl.GetString(dohUrl + @"?ct=application/dns-json&" + $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}", DnsSettings.Http2Enable, proxyEnable, wProxy, DnsSettings.AllowAutoRedirect); } catch (WebException e) { HttpWebResponse response = (HttpWebResponse)e.Response; try { BackgroundLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {e.Status} | {domainName} | {response.ResponseUri}"); if (DnsSettings.HTTPStatusNotify) { MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误", $"异常 :{Convert.ToInt32(response.StatusCode)} {response.StatusCode} {Environment.NewLine} {domainName}", ToolTipIcon.Warning); } if (response.StatusCode == HttpStatusCode.BadRequest) { DnsSettings.DnsMsgEnable = true; } } catch (Exception exception) { BackgroundLog($@"| - Catch WebException : {exception.Message} | {e.Status} | {domainName} | {dohUrl}" + @"?ct=application/dns-json&" + $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}"); if (DnsSettings.HTTPStatusNotify) { MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误", $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning); } } if (dohUrl != DnsSettings.HttpsDnsUrl) { return(new List <DnsRecordBase>(), ReturnCode.ServerFailure); } BackgroundLog($@"| -- SecondDoH : {DnsSettings.SecondHttpsDnsUrl}"); return(ResolveOverHttpsByDnsJson(clientIpAddress, domainName, DnsSettings.SecondHttpsDnsUrl, proxyEnable, wProxy, type)); } JsonValue dnsJsonValue = Json.Parse(dnsStr); int statusCode = dnsJsonValue.AsObjectGetInt("Status"); if (statusCode != 0) { return(new List <DnsRecordBase>(), (ReturnCode)statusCode); } if (dnsStr.Contains("\"Answer\"")) { var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer"); foreach (var itemJsonValue in dnsAnswerJsonList) { string answerAddr = itemJsonValue.AsObjectGetString("data"); string answerDomainName = itemJsonValue.AsObjectGetString("name"); int answerType = itemJsonValue.AsObjectGetInt("type"); int ttl = itemJsonValue.AsObjectGetInt("TTL"); switch (type) { case RecordType.A when Convert.ToInt32(RecordType.A) == answerType && !DnsSettings.Ipv4Disable: { ARecord aRecord = new ARecord( DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr)); recordList.Add(aRecord); break; } case RecordType.A: { if (Convert.ToInt32(RecordType.CName) == answerType) { CNameRecord cRecord = new CNameRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(cRecord); //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr)); //return recordList; } break; } case RecordType.Aaaa when Convert.ToInt32(RecordType.Aaaa) == answerType && !DnsSettings.Ipv6Disable: { AaaaRecord aaaaRecord = new AaaaRecord( DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr)); recordList.Add(aaaaRecord); break; } case RecordType.Aaaa: { if (Convert.ToInt32(RecordType.CName) == answerType) { CNameRecord cRecord = new CNameRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(cRecord); } break; } case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName): { CNameRecord cRecord = new CNameRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(cRecord); break; } case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns): { NsRecord nsRecord = new NsRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(nsRecord); break; } case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx): { MxRecord mxRecord = new MxRecord( DomainName.Parse(answerDomainName), ttl, ushort.Parse(answerAddr.Split(' ')[0]), DomainName.Parse(answerAddr.Split(' ')[1])); recordList.Add(mxRecord); break; } case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt): { TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr); recordList.Add(txtRecord); break; } case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr): { PtrRecord ptrRecord = new PtrRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(ptrRecord); break; } default: statusCode = Convert.ToInt32(ReturnCode.ServerFailure); break; } } } return(recordList, (ReturnCode)statusCode); }
private static IDictionary <string, object> Run() { var resourceGroup = new ResourceGroup("emoos-dev", new ResourceGroupArgs { Location = "WestEurope" }); Output <string> resourceGroupName = resourceGroup.Name; var planSkuArgs = new PlanSkuArgs { Tier = "Basic", Size = "B1" }; var plan = new Plan("DevAppServicePlan", new PlanArgs { ResourceGroupName = resourceGroupName, Kind = "Linux", Sku = planSkuArgs, Reserved = true }); var appSettings = new InputMap <string> { { "WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false" } }; var image = "sqeezy/emoos.solutions:latest"; var siteConfig = new AppServiceSiteConfigArgs { AlwaysOn = false, LinuxFxVersion = $"DOCKER|{image}" }; var appService = new AppService("DevAppService", new AppServiceArgs { ResourceGroupName = resourceGroupName, AppServicePlanId = plan.Id, AppSettings = appSettings, HttpsOnly = false, SiteConfig = siteConfig }); var emoosDns = new Zone("emoos.solutions", new ZoneArgs { ResourceGroupName = "emoos", Name = "emoos.solutions" }, new CustomResourceOptions { ImportId = DnsId, Protect = true }); var txtRecord = new TxtRecord("@", new TxtRecordArgs { Name = "@", ResourceGroupName = emoosDns.ResourceGroupName, Ttl = 60, ZoneName = emoosDns.Name, Records = new InputList <TxtRecordRecordsArgs> { new TxtRecordRecordsArgs { Value = appService.DefaultSiteHostname } } }); var cname = new CNameRecord("dev", new CNameRecordArgs { Name = "dev", ResourceGroupName = emoosDns.ResourceGroupName, Ttl = 60, ZoneName = emoosDns.Name, Record = appService.DefaultSiteHostname }); var hostNameBinding = new CustomHostnameBinding("dev.emoos.solutions", new CustomHostnameBindingArgs { AppServiceName = appService.Name, Hostname = "dev.emoos.solutions", ResourceGroupName = resourceGroupName // SslState = "SniEnabled", // Thumbprint = "19A0220DE45552EE931E0959B10F6DDDAD5F946B" }); return(new Dictionary <string, object?> { { "default route", appService.DefaultSiteHostname }, { "resource group", resourceGroup.Name } // {"domain binding", hostNameBinding.Hostname} }); }
private async Task <ValidationResult> CheckHostInternalAsync(IPAddress ip, DomainName domain, string sender, bool expandExplanation, State state, CancellationToken token) { if ((domain == null) || (domain.Equals(DomainName.Root))) { return(new ValidationResult() { Result = SpfQualifier.None, Explanation = String.Empty }); } if (String.IsNullOrEmpty(sender)) { sender = "postmaster@unknown"; } else if (!sender.Contains('@')) { sender = "postmaster@" + sender; } LoadRecordResult loadResult = await LoadRecordsAsync(domain, token); if (!loadResult.CouldBeLoaded) { return(new ValidationResult() { Result = loadResult.ErrorResult, Explanation = String.Empty }); } T record = loadResult.Record; if ((record.Terms == null) || (record.Terms.Count == 0)) { return new ValidationResult() { Result = SpfQualifier.Neutral, Explanation = String.Empty } } ; if (record.Terms.OfType <SpfModifier>().GroupBy(m => m.Type).Where(g => (g.Key == SpfModifierType.Exp) || (g.Key == SpfModifierType.Redirect)).Any(g => g.Count() > 1)) { return new ValidationResult() { Result = SpfQualifier.PermError, Explanation = String.Empty } } ; ValidationResult result = new ValidationResult() { Result = loadResult.ErrorResult }; #region Evaluate mechanism foreach (SpfMechanism mechanism in record.Terms.OfType <SpfMechanism>()) { if (state.DnsLookupCount > DnsLookupLimit) { return new ValidationResult() { Result = SpfQualifier.PermError, Explanation = String.Empty } } ; SpfQualifier qualifier = await CheckMechanismAsync(mechanism, ip, domain, sender, state, token); if (qualifier != SpfQualifier.None) { result.Result = qualifier; break; } } #endregion #region Evaluate modifiers if (result.Result == SpfQualifier.None) { SpfModifier redirectModifier = record.Terms.OfType <SpfModifier>().FirstOrDefault(m => m.Type == SpfModifierType.Redirect); if (redirectModifier != null) { if (++state.DnsLookupCount > 10) { return new ValidationResult() { Result = SpfQualifier.PermError, Explanation = String.Empty } } ; DomainName redirectDomain = await ExpandDomainAsync(redirectModifier.Domain ?? String.Empty, ip, domain, sender, token); if ((redirectDomain == null) || (redirectDomain == DomainName.Root) || (redirectDomain.Equals(domain))) { result.Result = SpfQualifier.PermError; } else { result = await CheckHostInternalAsync(ip, redirectDomain, sender, expandExplanation, state, token); if (result.Result == SpfQualifier.None) { result.Result = SpfQualifier.PermError; } } } } else if ((result.Result == SpfQualifier.Fail) && expandExplanation) { SpfModifier expModifier = record.Terms.OfType <SpfModifier>().FirstOrDefault(m => m.Type == SpfModifierType.Exp); if (expModifier != null) { DomainName target = await ExpandDomainAsync(expModifier.Domain, ip, domain, sender, token); if ((target == null) || (target.Equals(DomainName.Root))) { result.Explanation = String.Empty; } else { DnsResolveResult <TxtRecord> dnsResult = await ResolveDnsAsync <TxtRecord>(target, RecordType.Txt, token); if ((dnsResult != null) && (dnsResult.ReturnCode == ReturnCode.NoError)) { TxtRecord txtRecord = dnsResult.Records.FirstOrDefault(); if (txtRecord != null) { result.Explanation = (await ExpandMacroAsync(txtRecord.TextData, ip, domain, sender, token)).ToString(); } } } } } #endregion if (result.Result == SpfQualifier.None) { result.Result = SpfQualifier.Neutral; } return(result); }
public override void ExecuteCmdlet() { DnsRecordBase result = null; switch (this.ParameterSetName) { case ParameterSetA: { result = new ARecord { Ipv4Address = this.Ipv4Address }; break; } case ParameterSetAaaa: { result = new AaaaRecord { Ipv6Address = this.Ipv6Address }; break; } case ParameterSetMx: { result = new MxRecord { Preference = this.Preference, Exchange = this.Exchange }; break; } case ParameterSetNs: { result = new NsRecord { Nsdname = this.Nsdname }; break; } case ParameterSetSrv: { result = new SrvRecord { Priority = this.Priority, Port = this.Port, Target = this.Target, Weight = this.Weight }; break; } case ParameterSetTxt: { result = new TxtRecord { Value = this.Value }; break; } case ParameterSetCName: { result = new CnameRecord { Cname = this.Cname }; break; } case ParameterSetPtr: { result = new PtrRecord {Ptrdname = this.Ptrdname}; break; } default: { throw new PSArgumentException(string.Format(ProjectResources.Error_UnknownParameterSetName, this.ParameterSetName)); } } WriteObject(result); }
private static void RegisterService(string serviceDescription) { Match match = Regex.Match(serviceDescription, @"(_[a-z]+._tcp|udp)\s*(\d+)\s*(.*)"); if (match.Groups.Count < 4) { throw new ApplicationException("Invalid service description syntax"); } string type = match.Groups[1].Value.Trim(); short port = Convert.ToInt16(match.Groups[2].Value); string name = match.Groups[3].Value.Trim(); int txt_pos = name.IndexOf("TXT"); string txt_data = null; if (txt_pos > 0) { txt_data = name.Substring(txt_pos).Trim(); name = name.Substring(0, txt_pos).Trim(); if (txt_data == String.Empty) { txt_data = null; } } RegisterService service = new RegisterService(); service.Name = name; service.RegType = type; service.ReplyDomain = "local."; service.Port = port; TxtRecord record = null; if (txt_data != null) { Match tmatch = Regex.Match(txt_data, @"TXT\s*\[(.*)\]"); if (tmatch.Groups.Count != 2) { throw new ApplicationException("Invalid TXT record definition syntax"); } txt_data = tmatch.Groups[1].Value; foreach (string part in Regex.Split(txt_data, @"'\s*,")) { string expr = part.Trim(); if (!expr.EndsWith("'")) { expr += "'"; } Match pmatch = Regex.Match(expr, @"(\w+\s*\w*)\s*=\s*['](.*)[']\s*"); string key = pmatch.Groups[1].Value.Trim(); string val = pmatch.Groups[2].Value.Trim(); if (key == null || key == String.Empty || val == null || val == String.Empty) { throw new ApplicationException("Invalid key = 'value' syntax for TXT record item"); } if (record == null) { record = new TxtRecord(); } record.Add(key, val); } } if (record != null) { service.TxtRecord = record; } Console.WriteLine("*** Registering name = '{0}', type = '{1}', domain = '{2}'", service.Name, service.RegType, service.ReplyDomain); service.Response += OnRegisterServiceResponse; service.Register(); }
private static (List <dynamic> list, ReturnCode statusCode) ResolveOverHttps(string clientIpAddress, string domainName, bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A) { string dnsStr; List <dynamic> recordList = new List <dynamic>(); using (MWebClient webClient = new MWebClient()) { webClient.Headers["User-Agent"] = "AuroraDNSC/0.1"; // webClient.AllowAutoRedirect = false; if (proxyEnable) { webClient.Proxy = wProxy; } try { dnsStr = webClient.DownloadString( DnsSettings.HttpsDnsUrl + @"?ct=application/dns-json&" + $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}"); } catch (WebException e) { HttpWebResponse response = (HttpWebResponse)e.Response; try { BgwLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {domainName}"); } catch (Exception exception) { BgwLog($@"| - Catch WebException : {exception.Message} | {domainName}"); //MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误", // $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning); } return(new List <dynamic>(), ReturnCode.ServerFailure); } } JsonValue dnsJsonValue = Json.Parse(dnsStr); int statusCode = dnsJsonValue.AsObjectGetInt("Status"); if (statusCode != 0) { return(new List <dynamic>(), (ReturnCode)statusCode); } if (dnsStr.Contains("\"Answer\"")) { var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer"); foreach (var itemJsonValue in dnsAnswerJsonList) { string answerAddr = itemJsonValue.AsObjectGetString("data"); string answerDomainName = itemJsonValue.AsObjectGetString("name"); int answerType = itemJsonValue.AsObjectGetInt("type"); int ttl = itemJsonValue.AsObjectGetInt("TTL"); switch (type) { case RecordType.A: { if (Convert.ToInt32(RecordType.A) == answerType) { ARecord aRecord = new ARecord( DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr)); recordList.Add(aRecord); } else if (Convert.ToInt32(RecordType.CName) == answerType) { CNameRecord cRecord = new CNameRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(cRecord); //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr)); //return recordList; } break; } case RecordType.Aaaa: { if (Convert.ToInt32(RecordType.Aaaa) == answerType) { AaaaRecord aaaaRecord = new AaaaRecord( DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr)); recordList.Add(aaaaRecord); } else if (Convert.ToInt32(RecordType.CName) == answerType) { CNameRecord cRecord = new CNameRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(cRecord); } break; } case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName): { CNameRecord cRecord = new CNameRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(cRecord); break; } case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns): { NsRecord nsRecord = new NsRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(nsRecord); break; } case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx): { MxRecord mxRecord = new MxRecord( DomainName.Parse(answerDomainName), ttl, ushort.Parse(answerAddr.Split(' ')[0]), DomainName.Parse(answerAddr.Split(' ')[1])); recordList.Add(mxRecord); break; } case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt): { TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr); recordList.Add(txtRecord); break; } case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr): { PtrRecord ptrRecord = new PtrRecord( DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr)); recordList.Add(ptrRecord); break; } default: { statusCode = Convert.ToInt32(ReturnCode.ServerFailure); break; } } } } return(recordList, (ReturnCode)statusCode); }
protected void DeleteRecordEntry(object param) { List <object> objList = param as List <object>; RecordSet rs = objList?[0] as RecordSet; switch (GetRecordType(rs?.Type)) { case RecordType.A: { ARecord record = objList?[1] as ARecord; if (record != null) { rs.Properties.ARecords.Remove(record); } } break; case RecordType.AAAA: { AaaaRecord record = objList?[1] as AaaaRecord; if (record != null) { rs.Properties.AaaaRecords.Remove(record); } } break; case RecordType.MX: { MxRecord record = objList?[1] as MxRecord; if (record != null) { rs.Properties.MxRecords.Remove(record); } } break; case RecordType.SRV: { SrvRecord record = objList?[1] as SrvRecord; if (record != null) { rs.Properties.SrvRecords.Remove(record); } } break; case RecordType.TXT: { TxtRecord record = objList?[1] as TxtRecord; if (record != null) { rs.Properties.TxtRecords.Remove(record); } } break; } var r = new List <RecordSet>(Records); Records.Clear(); Records = new System.Collections.ObjectModel.ObservableCollection <RecordSet>(r); }