├── Sample.csproj
├── LICENSE
├── README.md
└── Function.cs
/Sample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | netcoreapp3.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Creative Commons Legal Code
2 |
3 | CC0 1.0 Universal
4 |
5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12 | HEREUNDER.
13 |
14 | Statement of Purpose
15 |
16 | The laws of most jurisdictions throughout the world automatically confer
17 | exclusive Copyright and Related Rights (defined below) upon the creator
18 | and subsequent owner(s) (each and all, an "owner") of an original work of
19 | authorship and/or a database (each, a "Work").
20 |
21 | Certain owners wish to permanently relinquish those rights to a Work for
22 | the purpose of contributing to a commons of creative, cultural and
23 | scientific works ("Commons") that the public can reliably and without fear
24 | of later claims of infringement build upon, modify, incorporate in other
25 | works, reuse and redistribute as freely as possible in any form whatsoever
26 | and for any purposes, including without limitation commercial purposes.
27 | These owners may contribute to the Commons to promote the ideal of a free
28 | culture and the further production of creative, cultural and scientific
29 | works, or to gain reputation or greater distribution for their Work in
30 | part through the use and efforts of others.
31 |
32 | For these and/or other purposes and motivations, and without any
33 | expectation of additional consideration or compensation, the person
34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35 | is an owner of Copyright and Related Rights in the Work, voluntarily
36 | elects to apply CC0 to the Work and publicly distribute the Work under its
37 | terms, with knowledge of his or her Copyright and Related Rights in the
38 | Work and the meaning and intended legal effect of CC0 on those rights.
39 |
40 | 1. Copyright and Related Rights. A Work made available under CC0 may be
41 | protected by copyright and related or neighboring rights ("Copyright and
42 | Related Rights"). Copyright and Related Rights include, but are not
43 | limited to, the following:
44 |
45 | i. the right to reproduce, adapt, distribute, perform, display,
46 | communicate, and translate a Work;
47 | ii. moral rights retained by the original author(s) and/or performer(s);
48 | iii. publicity and privacy rights pertaining to a person's image or
49 | likeness depicted in a Work;
50 | iv. rights protecting against unfair competition in regards to a Work,
51 | subject to the limitations in paragraph 4(a), below;
52 | v. rights protecting the extraction, dissemination, use and reuse of data
53 | in a Work;
54 | vi. database rights (such as those arising under Directive 96/9/EC of the
55 | European Parliament and of the Council of 11 March 1996 on the legal
56 | protection of databases, and under any national implementation
57 | thereof, including any amended or successor version of such
58 | directive); and
59 | vii. other similar, equivalent or corresponding rights throughout the
60 | world based on applicable law or treaty, and any national
61 | implementations thereof.
62 |
63 | 2. Waiver. To the greatest extent permitted by, but not in contravention
64 | of, applicable law, Affirmer hereby overtly, fully, permanently,
65 | irrevocably and unconditionally waives, abandons, and surrenders all of
66 | Affirmer's Copyright and Related Rights and associated claims and causes
67 | of action, whether now known or unknown (including existing as well as
68 | future claims and causes of action), in the Work (i) in all territories
69 | worldwide, (ii) for the maximum duration provided by applicable law or
70 | treaty (including future time extensions), (iii) in any current or future
71 | medium and for any number of copies, and (iv) for any purpose whatsoever,
72 | including without limitation commercial, advertising or promotional
73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74 | member of the public at large and to the detriment of Affirmer's heirs and
75 | successors, fully intending that such Waiver shall not be subject to
76 | revocation, rescission, cancellation, termination, or any other legal or
77 | equitable action to disrupt the quiet enjoyment of the Work by the public
78 | as contemplated by Affirmer's express Statement of Purpose.
79 |
80 | 3. Public License Fallback. Should any part of the Waiver for any reason
81 | be judged legally invalid or ineffective under applicable law, then the
82 | Waiver shall be preserved to the maximum extent permitted taking into
83 | account Affirmer's express Statement of Purpose. In addition, to the
84 | extent the Waiver is so judged Affirmer hereby grants to each affected
85 | person a royalty-free, non transferable, non sublicensable, non exclusive,
86 | irrevocable and unconditional license to exercise Affirmer's Copyright and
87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the
88 | maximum duration provided by applicable law or treaty (including future
89 | time extensions), (iii) in any current or future medium and for any number
90 | of copies, and (iv) for any purpose whatsoever, including without
91 | limitation commercial, advertising or promotional purposes (the
92 | "License"). The License shall be deemed effective as of the date CC0 was
93 | applied by Affirmer to the Work. Should any part of the License for any
94 | reason be judged legally invalid or ineffective under applicable law, such
95 | partial invalidity or ineffectiveness shall not invalidate the remainder
96 | of the License, and in such case Affirmer hereby affirms that he or she
97 | will not (i) exercise any of his or her remaining Copyright and Related
98 | Rights in the Work or (ii) assert any associated claims and causes of
99 | action with respect to the Work, in either case contrary to Affirmer's
100 | express Statement of Purpose.
101 |
102 | 4. Limitations and Disclaimers.
103 |
104 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
105 | surrendered, licensed or otherwise affected by this document.
106 | b. Affirmer offers the Work as-is and makes no representations or
107 | warranties of any kind concerning the Work, express, implied,
108 | statutory or otherwise, including without limitation warranties of
109 | title, merchantability, fitness for a particular purpose, non
110 | infringement, or the absence of latent or other defects, accuracy, or
111 | the present or absence of errors, whether or not discoverable, all to
112 | the greatest extent permissible under applicable law.
113 | c. Affirmer disclaims responsibility for clearing rights of other persons
114 | that may apply to the Work or any use thereof, including without
115 | limitation any person's Copyright and Related Rights in the Work.
116 | Further, Affirmer disclaims responsibility for obtaining any necessary
117 | consents, permissions or other rights required for any use of the
118 | Work.
119 | d. Affirmer understands and acknowledges that Creative Commons is not a
120 | party to this document and has no duty or obligation with respect to
121 | this CC0 or use of the Work.
122 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DNS over HTTPS proxy on Google Cloud Function
2 | A DNS over HTTPS (DoH) resolver can be accessed entirely through a simple URL. If your ISP/organization blocks popular DoH provider, you don't trust random DoH proxy and can't be bothered to setup your own server, you can use this script to have your own DoH proxy on Google Cloud Function (GCF).
3 |
4 | If you find the following too complex when all you need is simple resolver to target one server or need a straightforward example to implement DoH, see the [simpleDo53](https://github.com/tina-hello/doh-gcf/tree/simpleDo53) and [simpleDoH](https://github.com/tina-hello/doh-gcf/tree/simpleDoH) branch, or their original inspiration [NotMikeDEV/DoH](https://github.com/NotMikeDEV/DoH)
5 |
6 | Don't have a card to activate Google Cloud account or just don't want to use Google? I have a very [simplistic port](https://github.com/tina-hello/doh-cf-workers) for Cloudflare, no card needed.
7 |
8 | ## Usage Steps
9 |
10 | * Get to https://console.cloud.google.com/functions and create a new function.
11 |
12 | If you don't have a project yet, the project name will be part of the function subdomain and visible to network logs, so don't use project name that implies it's a DoH proxy. The function name will be the path, that shouldn't be visible to network logs, feel free to use shortest function name as possible (even a single letter will do).
13 |
14 | * Pick the closest region to your location
15 | * Change the authentication options to allow unauthorized invocations
16 | * Take note of the function trigger URL, it will be in the pattern of `https://region-projectname.cloudfunctions.net/functionname`, click Save and Next
17 | * In the new page, change the Runtime to .NET
18 | * Replace the entire content of Function.cs with [my version](/Function.cs) then click deploy
19 | * Use your function trigger URL anywhere DoH URL is accepted (Chrome, Firefox, Intra, macOS and iOS profile generator, etc)
20 |
21 | Without extra parameter, your proxy will resolve using Google's own 8.8.8.8. You can use other servers just by adding their short name/domain after the function name, eg : `https://region-projectname.cloudfunctions.net/functionname/shortname`
22 |
23 | ### Short names
24 |
25 | Used on its own, the short names will forward your query unencrypted through Do53. You can add `doh-` prefix, eg, `doh-google` (except `google6`, since the DoH always use IPv6 when available) to forward with encryption through DoH instead.
26 |
27 | * `google` [Google](https://developers.google.com/speed/public-dns) public DNS. Fastest since the proxy already running inside Google's network
28 | * `google6` IPv6 variant of the Google DNS. I put it mostly to hint how to use your own IPv6 address by editing the source code.
29 | * `adguard` [Adguard](http://adguard.com/) blocks ads, trackers & phishing. Conservative filter means it just works without further maintainance.
30 | * `adguard-family` the regular variant plus adult sites filtering. Decent for work/public sites purposes.
31 | * `adguard-unrestricted` non filtering variant.
32 | * `cleanbrowsing-family` [CleanBrowsing](https://cleanbrowsing.org/)'s most restrictive filter, aside from blocking phising and malware sites, it also blocks adult sites, vpn, proxies, and mixed sites like Reddit. Great for religious or educational institute.
33 | * `cleanbrowsing-adult` only block adult, phishing and malware sites. Good for work purposes or personal use.
34 | * `cleanbrowsing-security` only block phishing and malware sites.
35 | * `cloudflare` [Cloudflare](https://blog.cloudflare.com/dns-resolver-1-1-1-1/)'s non-filtering variant.
36 | * `cloudflare-malware` [Cloudflare](https://blog.cloudflare.com/introducing-1-1-1-1-for-families/)'s malware filter variant.
37 | * `cloudflare-adult` Block adult sites in addition to malware filter.
38 | * `opendns` [OpenDNS](https://support.opendns.com/hc/en-us/articles/227986707-Understanding-Malware-and-how-OpenDNS-helps) default malware blocking variant
39 | * `opendns-family` blocks ["tasteless, proxy/anonymizer, sexuality and pornography"](https://support.opendns.com/hc/en-us/articles/228006487-FamilyShield-Router-Configuration-Instructions). They don't [consider Playboy](https://domain.opendns.com/playboy.com) as porn site, which may be a good or bad thing depends on your goal.
40 | * `quad9` [Quad9](https://www.quad9.net/) malware protection, frequently [topping malware blocking test](https://www.quad9.net/dns-blocking-effectiveness-recent-independent-tests/)
41 | * `quad9-ecs` with ECS support. Note however, since the DNS payload is sent as is through the cloud function, the detected IP will be Google Cloud's.
42 | * `quad9-unrestricted` non filtering variant.
43 |
44 | ### [NextDNS](http://nextdns.io/) Configuration
45 |
46 | Use `nextdns-` for Do53 mode or `nextdns/` for DoH mode, followed with your configuration ID, eg. if your configuration ID is abc123, use either `nextdns-abc123` or `nextdns/abc123` so the URL is going to be `https://region-projectname.cloudfunctions.net/functionname/nextdns-abc123` or `https://region-projectname.cloudfunctions.net/functionname/nextdns/abc123`. Do53 request will be sent to your NextDNS assigned IPv6 address, while DoH mode use your assigned DoH address. Device identifier is also supported in DoH mode, so if you use `nextdns/abc123/deviceid`, the request will be marked as coming from `deviceid` in the NextDNS log. If you activate ECS support, on Do53 mode the IP seen by the resolver is Google Cloud's, while the DoH mode will use your actual device IP. Use the Cache Boost and CNAME Flattening to reduce calls.
47 |
48 | ### Custom Do53 and DoH servers
49 |
50 | Any resolvers that [support Do53](https://kb.adguard.com/en/general/dns-providers) can be used by their IP, eg. to use Google's 8.8.8.8, use `https://region-projectname.cloudfunctions.net/functionname/8.8.8.8`, IPv6 is also supported (even if your own connection is IPv4 only, Google Cloud can use them), so for Google's IPv6 variant, use `https://region-projectname.cloudfunctions.net/functionname/2001:4860:4860::8888`
51 |
52 | Any resolvers that [support DoH](https://github.com/curl/curl/wiki/DNS-over-HTTPS) can be used by their complete domain and query path, eg to use Google's DoH variant, use `https://region-projectname.cloudfunctions.net/functionname/dns.google/dns-query`. The `/dns-query` part can be skipped, so just the domain is enough for resolvers that use the standard path.
53 |
54 | The X-Forwarded-For header is set with your device's IP on DoH request, so ECS *might* work with the device's IP, but so far it's only confirmed on NextDNS, while all other ECS-capable resolver doesn't seem to care, or in OpenDNS case, return an entirely different answer. You can disable the header from the source code from a marked comment inside `sendDoH()`.
55 |
56 | ### Random Mode
57 |
58 | There are three group of resolvers that you can pick to resolve queries. Each query would be resolved by different member, reducing the amount of data each resolver have of your activity. Use the group name as short code. Prepend with `doh-` to use the DoH variant.
59 |
60 | * `unrestricted` : The unrestricted, non-filtering variants of Adguard, Quad9, Cloudflare and Google.
61 |
62 | * `malware` : Anti malware variants of AdGuard, CleanBrowsing, Cloudflare and Quad9.
63 |
64 | * `family` : Family friendly variants of AdGuard, CleanBrowsing, Cloudflare, and OpenDNS.
65 |
66 | ## Pros :
67 |
68 | * Free for even heavy usages. With free 2 million calls and 5 GB egress traffic a month, this should be enough to serve even an entire household (for comparison, the free tier for NextDNS provides 300 thousand request a month).
69 |
70 | * Automatically adjust for heavy load by launching more instance.
71 |
72 | * Simply create another project if your URL is blocked.
73 |
74 | * No need to fiddle with command lines or setting up updates.
75 |
76 | * Create multiple functions on any region you want with no additional cost. Free quota is shared across all functions.
77 |
78 | * Proxy to any provider you want and utilize their filtering features, even your custom filter.
79 |
80 | * Relatively fast when proxying to Do53 resolver.
81 |
82 | * Can still use ECS when proxying to DoH resolver.
83 |
84 | * On DoH mode, your query is encrypted nearly all the way from your device to the resolver, except during the transit in Google Cloud.
85 |
86 | * You can use IPv6 and IPv4 resolvers even if your device connection doesn't support them. Useful for IPv4-only ISP or when running IPv6-only VM
87 |
88 | * If you're paranoid about DNS resolvers tracking your request, the Do53 mode will only send the datagram with no identifying information aside from the cloud instance IPv6 address (*might* be correlated through requests) without the resolver getting your client IP.
89 |
90 | ## Cons :
91 |
92 | * Not the fastest solution, might take between 10-200 ms for Do53 and 50-200 ms for DoH , compared to 5-20 ms for average global resolvers. Browsers and OSes cache DNS request, but first visit might feel sluggish. Spinning up a new instance (after extended idle or during heavy load) can take 2-5 seconds.
93 |
94 | * Can't do custom filtering on itself. The code don't even try to parse the DNS request and just pass them as is. Either use existing provider filters or host your own (probably useful if direct access to your server is blocked/need to be kept secret). Aside from NextDNS which have excellent adblocking filters, there's free tier for [Cloudlare Team](https://www.cloudflare.com/teams/) with unlimited queries for multiple configuration and 50 members.
95 |
96 | * Your network admin might just block the entire cloudfunctions.net domain. That would break sites that use GCF without whitelisting, viable for small organization level.
97 |
98 | * If you're really paranoid about privacy, this runs on Google Cloud, owned by the largest advertiser in the world.
99 |
--------------------------------------------------------------------------------
/Function.cs:
--------------------------------------------------------------------------------
1 | using Google.Cloud.Functions.Framework;
2 | using Microsoft.AspNetCore.Http;
3 | using Microsoft.AspNetCore.WebUtilities;
4 | using Microsoft.Extensions.Logging;
5 | using System.Collections.Generic;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Net.Http;
9 | using System.Net.Sockets;
10 | using System.Net;
11 | using System.Threading.Tasks;
12 | using System;
13 |
14 | namespace SimpleHttpFunction
15 | {
16 | public class Function : IHttpFunction
17 | {
18 | private readonly ILogger _logger;
19 |
20 | public Function(ILogger logger) =>
21 | _logger = logger;
22 | public async Task HandleAsync(HttpContext context)
23 | {
24 | try
25 | {
26 | var datagram = extractDatagram(context);
27 |
28 | var option = extractOption(context);
29 |
30 | context.Response.ContentType = "application/dns-message";
31 | var do53Address = pickDo53(option);
32 |
33 | if (datagram.Result == null)
34 | {
35 | context.Response.StatusCode = 400;
36 | return;
37 | }
38 |
39 | if (do53Address != null)
40 | {
41 | await sendDo53(context, datagram.Result, do53Address);
42 | return;
43 | }
44 |
45 | var (dnsHost,dnsPath) = extractUrlDoH(option);
46 |
47 | await sendDoH(context, datagram.Result, dnsHost, dnsPath);
48 |
49 | }
50 | catch (Exception ex)
51 | {
52 | _logger.LogError(ex, ex.Message + Environment.NewLine + ex.StackTrace);
53 | }
54 |
55 | }
56 |
57 | private static (string dnsHost,string dnsPath) extractUrlDoH(string option)
58 | {
59 |
60 | if (dohProviders.ContainsKey(option))
61 | {
62 | option = dohProviders[option];
63 | }
64 | else if (option.StartsWith("nextdns"))
65 | {
66 | option = option.Replace("nextdns", "dns.nextdns.io");
67 | }
68 | else switch (option)
69 | {
70 | case "doh-unrestricted":
71 | option = dohProviders["doh-"+unrestricted[rand.Next(unrestricted.Length)]];
72 | break;
73 | case "doh-malware":
74 | option = dohProviders["doh-"+antiMalware[rand.Next(antiMalware.Length)]];
75 | break;
76 | case "doh-family":
77 | option = dohProviders["doh-"+family[rand.Next(family.Length)]];
78 | break;
79 | }
80 | var slashIndex = option.IndexOf("/");
81 | string dnsHost, dnsPath;
82 | if (slashIndex > 0)
83 | {
84 | dnsHost = option.Substring(0, slashIndex);
85 | dnsPath = option[(slashIndex + 1)..];
86 | }
87 | else
88 | {
89 | dnsHost = option;
90 | dnsPath= "dns-query";
91 |
92 | }
93 |
94 | return (dnsHost, dnsPath);
95 | }
96 |
97 | private static async Task sendDoH(HttpContext context, byte[] datagram, string dnsHost, string dnsPath)
98 | {
99 | var request = new HttpRequestMessage();
100 | request.Content = new ByteArrayContent(datagram);
101 | request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/dns-message");
102 |
103 | request.Method = HttpMethod.Post;
104 | request.RequestUri = new Uri($"https://{dnsHost}/{dnsPath}");
105 | request.Headers.Host = dnsHost;
106 | //comment the line below to disable ECS using client's IP
107 | request.Headers.Add("x-forwarded-for",context.Request.Headers["x-forwarded-for"].ToString());
108 |
109 | using (var client = new HttpClient())
110 | {
111 | using (var responseMessage = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
112 | {
113 | context.Response.StatusCode = (int)responseMessage.StatusCode;
114 | await responseMessage.Content.CopyToAsync(context.Response.Body);
115 | }
116 | }
117 | }
118 |
119 | private async static Task sendDo53(HttpContext context, byte[] datagram, IPAddress do53Address)
120 | {
121 | var endpoint = new IPEndPoint(do53Address, 53);
122 | var udpClient = new UdpClient(endpoint.AddressFamily);
123 | udpClient.Connect(endpoint);
124 | udpClient.Send(datagram, datagram.Length);
125 |
126 | var result = udpClient.Receive(ref endpoint);
127 | await context.Response.Body.WriteAsync(result, 0, result.Length);
128 | }
129 |
130 | private static readonly Dictionary do53Providers = new Dictionary ()
131 | {
132 | ["google"] = IPAddress.Parse("8.8.8.8"),
133 | ["google6"] = IPAddress.Parse("2001:4860:4860::8888"),
134 | ["adguard"] = IPAddress.Parse("94.140.14.14"),
135 | ["adguard-family"] = IPAddress.Parse("94.140.14.15"),
136 | ["adguard-unrestricted"] = IPAddress.Parse("94.140.14.140"),
137 | ["cleanbrowsing-family"] = IPAddress.Parse("185.228.168.168"),
138 | ["cleanbrowsing-adult"] = IPAddress.Parse("185.228.168.10"),
139 | ["cleanbrowsing-security"] = IPAddress.Parse("185.228.168.9"),
140 | ["cloudflare"] = IPAddress.Parse("1.1.1.1"),
141 | ["cloudflare-malware"] = IPAddress.Parse("1.1.1.2"),
142 | ["cloudflare-adult"] = IPAddress.Parse("1.1.1.3"),
143 | ["opendns"] = IPAddress.Parse("208.67.222.222"),
144 | ["opendns-family"] = IPAddress.Parse("208.67.222.123"),
145 | ["quad9"] = IPAddress.Parse("9.9.9.9"),
146 | ["quad9-unrestricted"] = IPAddress.Parse("9.9.9.10"),
147 | ["quad9-ecs"] = IPAddress.Parse("9.9.9.11"),
148 | };
149 |
150 | private static readonly string[] unrestricted = new[] { "adguard-unrestricted", "cloudflare", "quad9-unrestricted", "google" };
151 | private static readonly string[] antiMalware = new[] { "adguard", "cleanbrowsing-security", "cloudflare-malware", "quad9" };
152 | private static readonly string[] family = new[] { "adguard-family", "cleanbrowsing-family", "cloudflare-adult", "opendns-family" };
153 |
154 | private static readonly Dictionary dohProviders = new Dictionary()
155 | {
156 | ["doh-google"] = "dns.google",
157 | ["doh-adguard"] = "dns.adguard.com",
158 | ["doh-adguard-family"] = "dns-family.adguard.com",
159 | ["doh-adguard-unrestricted"] = "dns-unfiltered.adguard.com",
160 | ["doh-cleanbrowsing-family"] = "doh.cleanbrowsing.org/doh/family-filter/",
161 | ["doh-cleanbrowsing-adult"] = "doh.cleanbrowsing.org/doh/adult-filter/",
162 | ["doh-cleanbrowsing-security"] = "doh.cleanbrowsing.org/doh/security-filter/",
163 | ["doh-cloudflare"] = "dns.cloudflare.com",
164 | ["doh-cloudflare-malware"] = "security.cloudflare-dns.com",
165 | ["doh-cloudflare-adult"] = "family.cloudflare-dns.com",
166 | ["doh-opendns"] = "doh.opendns.com",
167 | ["doh-opendns-family"] = "doh.familyshield.opendns.com",
168 | ["doh-quad9"] = "dns.quad9.net",
169 | ["doh-quad9-unrestricted"] = "dns10.quad9.net",
170 | ["doh-quad9-ecs"] = "dns11.quad9.net",
171 | };
172 |
173 | private static readonly Random rand = new Random();
174 | private static IPAddress pickDo53(string option)
175 | {
176 | if (!option.Any())
177 | {
178 | return do53Providers["google"];
179 | }
180 | IPAddress do53Address;
181 |
182 | if (IPAddress.TryParse(option,out do53Address))
183 | {
184 | return do53Address;
185 | }
186 |
187 | if (option.StartsWith("nextdns-"))
188 | {
189 | var configID = option.Replace("nextdns-", "");
190 | return IPAddress.Parse($"2a07:a8c0::{configID[..^4]}:{configID[^4..]}");
191 | }
192 |
193 | if (do53Providers.ContainsKey(option))
194 | {
195 | return do53Providers[option];
196 | }
197 |
198 | switch (option)
199 | {
200 | case "unrestricted":
201 | return do53Providers[unrestricted[rand.Next(unrestricted.Length)]];
202 | case "malware":
203 | return do53Providers[antiMalware[rand.Next(antiMalware.Length)]];
204 | case "family":
205 | return do53Providers[family[rand.Next(family.Length)]];
206 | default:
207 | return null;
208 | }
209 | }
210 |
211 | private static string extractOption(HttpContext context)
212 | {
213 | var originPath = context.Request.Path.ToString();
214 |
215 | var secondSlashIndex = originPath.IndexOf("/");
216 | var option = "";
217 | if (secondSlashIndex >= 0 && secondSlashIndex < originPath.Length - 1)
218 | {
219 | option = originPath[(secondSlashIndex + 1)..];
220 | }
221 |
222 | return option;
223 | }
224 |
225 | private static async Task extractDatagram(HttpContext context)
226 | {
227 | byte[] datagram;
228 |
229 | if (context.Request.Method == "POST" && context.Request.ContentType == "application/dns-message")
230 | {
231 | using (var bodyStream = new MemoryStream())
232 | {
233 | await context.Request.Body.CopyToAsync(bodyStream);
234 | datagram = bodyStream.ToArray();
235 | }
236 | }
237 | else if (context.Request.Query["dns"].Any())
238 | {
239 | var base64 = context.Request.Query["dns"].ToString();
240 | datagram = WebEncoders.Base64UrlDecode(base64);
241 | }
242 | else
243 | {
244 | datagram = null;
245 | }
246 |
247 | return datagram;
248 | }
249 | }
250 | }
251 |
--------------------------------------------------------------------------------