Compare commits

...

15 Commits

Author SHA1 Message Date
Eugene Burkov
41e8db4221 Pull request: client: upd i18n
Merge in DNS/adguard-home from upd-i18n to master

Squashed commit of the following:

commit e3dfb6cd66813d45591f74c9cdddab8b61143db3
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Mon Jan 24 14:52:19 2022 +0300

    client: upd i18n
2022-01-24 15:02:47 +03:00
Eugene Burkov
3f5605c42e Pull request: 2846 cover aghnet vol.1
Merge in DNS/adguard-home from 2846-cover-aghnet-vol.1 to master

Updates #2846.

Squashed commit of the following:

commit 368e75b0bacb290f9929b8a5a682b06f2d75df6a
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Fri Jan 21 19:11:59 2022 +0300

    aghnet: imp tests

commit 8bb3e2a1680fd30294f7c82693891ffb19474c6a
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Fri Jan 21 18:27:06 2022 +0300

    aghnet: rm unused test

commit 28d8e64880f845810d0af629e5d1f06b9bde5b28
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Fri Jan 21 18:18:22 2022 +0300

    aghnet: cover with tests
2022-01-21 19:21:38 +03:00
Ildar Kamalov
f7ff02f3b1 Pull request: 3971 fix client id error message
Updates #3971

Squashed commit of the following:

commit f6b855a16daaec7bfca1e1653b4b9c4180c2d80e
Merge: 0cb31dbb 5ec4a4da
Author: Ildar Kamalov <ik@adguard.com>
Date:   Thu Jan 20 18:19:20 2022 +0300

    Merge branch 'master' into 3971-client-id

commit 0cb31dbbea785fb5ba11a8efe2b6653aece7cd97
Author: Natalia Sokolova <n.sokolova@adguard.com>
Date:   Thu Jan 20 11:41:06 2022 +0300

    client/src/__locales/en.json edited online with Bitbucket

commit 7999f260d83adcb2fc8d5d5e40cb1934e0333873
Author: Ildar Kamalov <ik@adguard.com>
Date:   Wed Jan 19 15:58:18 2022 +0300

    client: fix client id error message
2022-01-20 18:24:21 +03:00
Eugene Burkov
5ec4a4dab8 Pull request: 4142 stats panic
Merge in DNS/adguard-home from 4142-stats-panic to master

Updates #4142.

Squashed commit of the following:

commit bf168f50ac86bdfdab73bf7285705f09f87b6c72
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Jan 20 17:13:41 2022 +0300

    stats: imp more

commit bb638211da7d0c51959ded2dacb72faea00befb4
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Jan 20 17:09:31 2022 +0300

    stats: imp code quality

commit 27ac52f15e4e0f4112ce7a6b47b03f963463393e
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Jan 20 17:00:09 2022 +0300

    stats: recover panic on init

commit 1ffcebbb9062438170b010e1c7bad3c6cef4cfc1
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Jan 20 14:19:01 2022 +0300

    all: fix some typos
2022-01-20 17:19:09 +03:00
Ainar Garipov
13871977f9 Pull request: all: upd dnsproxy
Updates #4128.

Squashed commit of the following:

commit c177750f3f4d3ae29133154eca4dfe4051de1310
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu Jan 20 17:01:02 2022 +0300

    all: upd dnsproxy
2022-01-20 17:05:59 +03:00
Ildar Kamalov
2fdda8a22c Pull request: 4143 sort client ids
Merge in DNS/adguard-home from 4143-clients-sort to master

Updates #4143.

Squashed commit of the following:

commit a4b547eb46a54bdfdc7d342fab5f8ecfa54f5d06
Merge: d369c11c d82b2902
Author: Ildar Kamalov <ik@adguard.com>
Date:   Thu Jan 20 11:58:42 2022 +0300

    Merge branch 'master' into 4143-clients-sort

commit d369c11c69665510043f63e0283e1ca1b2974289
Author: Ildar Kamalov <ik@adguard.com>
Date:   Wed Jan 19 16:53:39 2022 +0300

    client: fix sort ip method

commit d767a1199c37ad9df7f3bc2d362d840b0226d836
Author: Ildar Kamalov <ik@adguard.com>
Date:   Wed Jan 19 16:23:23 2022 +0300

    client: sort client ids
2022-01-20 12:23:59 +03:00
Eugene Burkov
d82b290251 Pull request: 4095 fix duplicating port
Merge in DNS/adguard-home from 4095-port-3000 to master

Updates #4095.

Squashed commit of the following:

commit 968cc806264898523d29c4ec20b3ce6a69abb09c
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 19 20:26:33 2022 +0300

    home: fix typo

commit 03c6798db6a4ca726a7b5a683e475a8a74f79fe1
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 19 20:20:34 2022 +0300

    all: more naming imps

commit d3d417fcb24a1859f53a743b3533faa81b6bef19
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 19 20:10:14 2022 +0300

    aghalgo: rename into aghalg

commit 6e106006d07a747ff4ddf1271532106c3a3e2b20
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 19 20:05:43 2022 +0300

    all: imp names, docs

commit 12c8d9fde0d0cc5b953da30b042171ba7c53da5d
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 19 19:57:21 2022 +0300

    all: fix log of changes

commit 49c7a705b9b1ad8f2ef68fa807f9b6b8c447b421
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 19 19:51:00 2022 +0300

    home: fix duplicating port 3000
2022-01-19 20:45:50 +03:00
Ainar Garipov
eb15304ff4 scripts: imp sh lint 2022-01-19 15:06:23 +03:00
Eugene Burkov
1a3bf5ebda Pull request: 4133 empty rewrite
Merge in DNS/adguard-home from 4133-empty-rewrite to master

Closes #4133.

Squashed commit of the following:

commit 4d2313c211c3955922d340c006b323c65e5e5ba4
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Tue Jan 18 21:36:21 2022 +0300

    all: log changes

commit 5b8e392a2225c215fc117223d3f6553f8bdf21cd
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Tue Jan 18 21:32:57 2022 +0300

    all: upd urlfilter
2022-01-19 14:19:12 +03:00
Ainar Garipov
813a06d09a Pull request: home: show version in install api
Closes #4026.

Squashed commit of the following:

commit bcd1315a10e819daee3aee323427d90a27860b4a
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Jan 18 14:57:49 2022 +0300

    openapi: fix example

commit b56e27c5ac1fc7c3f595057d77607479d72ec50a
Author: Ildar Kamalov <ik@adguard.com>
Date:   Tue Jan 18 14:55:51 2022 +0300

    client: show version on install page

commit 95dfbfaa1235deef7b55e51457d11c677f6ef6b5
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Jan 18 14:29:08 2022 +0300

    home: show version in install api
2022-01-18 15:05:34 +03:00
Eugene Burkov
061136508e Pull request: 4120 service domain validation
Merge in DNS/adguard-home from 4120-fix-services to master

Closes #4120.

Squashed commit of the following:

commit ca2e5faf64f567cc6647a300181712236158e69d
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Tue Jan 18 14:14:54 2022 +0300

    dnsforward: imp docs

commit 9ed5f536e691dcdee5b7c94e161c738d31ff8588
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Tue Jan 18 13:50:33 2022 +0300

    dnsforward: fix reverse domain validation
2022-01-18 14:20:25 +03:00
Ainar Garipov
008f58c863 Pull request: all: upd dnsproxy
Updates #4065.

Squashed commit of the following:

commit d65d2e3a783910b9cb95c5bcfbcf1af11da666d5
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Mon Jan 17 18:47:17 2022 +0300

    all: upd dnsproxy
2022-01-17 18:54:00 +03:00
Eugene Burkov
0e4ffd339f Pull request: 4074 fix upstream test
Merge in DNS/adguard-home from 4074-upstream-test to master

Updates #4074.

Squashed commit of the following:

commit 0de155b1e175a892b259791ff6d6e6f351bcfcf2
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 12 19:20:01 2022 +0500

    dnsforward: fix upstream test
2022-01-13 15:05:44 +03:00
Eugene Burkov
1458600c37 Pull request: 4079 fix hosts container aliases
Merge in DNS/adguard-home from 4079-hosts-again to master

Updates #4079.

Squashed commit of the following:

commit 6aa8cbf32e8e47ba46bf5fba7681a10b68b4bc01
Merge: 19dba371 34c95f99
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 12 14:05:30 2022 +0500

    Merge branch 'master' into 4079-hosts-again

commit 19dba371cc30ab8b75b0116833f4ecf0ef0f182f
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 12 14:05:20 2022 +0500

    aghnet: imp docs

commit 9f341eb8ee4ba8468240bc3eeeb4951a3f7f5e6d
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Mon Jan 10 18:44:17 2022 +0500

    aghnet: fix races

commit fd66191c7637c8584711e5bb8186494327ce0f87
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Jan 6 17:21:14 2022 +0500

    aghnet: fix hosts container aliases
2022-01-12 12:14:59 +03:00
Eugene Burkov
34c95f99f8 Pull request: 4046 darwin service message
Merge in DNS/adguard-home from 4046-log-dir to master

Closes #4046.

Squashed commit of the following:

commit 05140550b14f477f52487c575f56428ce9e6fa10
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Jan 5 17:54:11 2022 +0500

    all: add macOS service msg
2022-01-11 21:33:14 +03:00
56 changed files with 1091 additions and 750 deletions

View File

@@ -17,6 +17,8 @@ and this project adheres to
### Added
- Support for a `$dnsrewrite` modifier with an empty `NOERROR` response
([#4133]).
- `windows/arm64` support ([#3057]).
### Deprecated
@@ -27,16 +29,29 @@ TODO(a.garipov): Remove this deprecation, if v0.108.0 is released before the Go
-->
- Go 1.17 support. v0.109.0 will require at least Go 1.18 to build.
### Fixed
- Wrong set of ports checked for duplicates during the initial setup ([#4095]).
- Incorrectly invalidated service domains ([#4120]).
- Poor testing of domain-specific upstream servers ([#4074]).
- Omitted aliases of hosts specified by another line within the OS's hosts file
([#4079]).
### Removed
- Go 1.16 support.
[#3057]: https://github.com/AdguardTeam/AdGuardHome/issues/3057
[#4074]: https://github.com/AdguardTeam/AdGuardHome/issues/4074
[#4079]: https://github.com/AdguardTeam/AdGuardHome/issues/4079
[#4095]: https://github.com/AdguardTeam/AdGuardHome/issues/4095
[#4120]: https://github.com/AdguardTeam/AdGuardHome/issues/4120
[#4133]: https://github.com/AdguardTeam/AdGuardHome/issues/4133
<!--
## [v0.107.3] - 2022-01-19 (APPROX.)
## [v0.107.3] - 2022-02-08 (APPROX.)
-->

View File

@@ -163,8 +163,8 @@
"apply_btn": "Ужыць",
"disabled_filtering_toast": "Фільтрацыя выкл.",
"enabled_filtering_toast": "Фільтрацыя ўкл.",
"disabled_safe_browsing_toast": "Бяспечная навігацыя выкл.",
"enabled_safe_browsing_toast": "Бяспечная навігацыя ўкл.",
"disabled_safe_browsing_toast": "Бяспечная навігацыя выключана",
"enabled_safe_browsing_toast": "Бяспечная навігацыя ўключана",
"disabled_parental_toast": "Бацькоўскі кантроль выкл.",
"enabled_parental_toast": "Бацькоўскі кантроль укл.",
"disabled_safe_search_toast": "Бяспечны пошук выкл.",
@@ -200,6 +200,7 @@
"form_error_url_or_path_format": "Няслушны URL ці абсалютны шлях да спіса",
"custom_filter_rules": "Карыстацкае рэдагавала фільтрацыі",
"custom_filter_rules_hint": "Уводзьце па адным правіле на радок. Вы можаце выкарыстоўваць правілы блакавання ці сінтаксіс файлаў hosts.",
"system_host_files": "Сістэмныя hosts-файлы",
"examples_title": "Прыклады",
"example_meaning_filter_block": "заблакаваць доступ да дамена example.org і ўсім яго паддаменам",
"example_meaning_filter_whitelist": "адблакаваць доступ да дамена example.org і ўсім яго паддаменам",
@@ -586,8 +587,8 @@
"show_blocked_responses": "Заблакавана",
"show_whitelisted_responses": "Белы спіс",
"show_processed_responses": "Апрацавана",
"blocked_safebrowsing": "Заблакавана згодна базе дадзеных Safebrowsing",
"blocked_adult_websites": "Заблакаваныя \"дарослыя\" сайты",
"blocked_safebrowsing": "Заблакавана згодна базе дадзеных Safe Browsing",
"blocked_adult_websites": "Заблакавана Бацькоўскім кантролем",
"blocked_threats": "Заблакавана пагроз",
"allowed": "Дазволены",
"filtered": "Адфільтраваныя",
@@ -624,5 +625,7 @@
"last_rule_in_allowlist": "Няможна заблакаваць гэтага кліента, бо вынятак правіла «{{disallowed_rule}}» АДКЛЮЧЫЦЬ рэжым белага спіса.",
"experimental": "Эксперыментальны",
"use_saved_key": "Скарыстаць захаваны раней ключ",
"parental_control": "Бацькоўскі кантроль"
"parental_control": "Бацькоўскі кантроль",
"safe_browsing": "Бяспечны інтэрнэт",
"served_from_cache": "{{value}} <i>(атрымана з кэша)</i>"
}

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Neplatná adresa IPv6",
"form_error_ip_format": "Neplatná adresa IP",
"form_error_mac_format": "Neplatná adresa MAC",
"form_error_client_id_format": "Neplatné ID klienta",
"form_error_client_id_format": "ID klienta musí obsahovat pouze čísla, malá písmena a spojovníky",
"form_error_server_name": "Neplatný název serveru",
"form_error_subnet": "Podsíť \"{{cidr}}\" neobsahuje IP adresu \"{{ip}}\"",
"form_error_positive": "Musí být větší než 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Ugyldig IPv6-adresse",
"form_error_ip_format": "Ugyldig IP-adresse",
"form_error_mac_format": "Ugyldig MAC-adresse",
"form_error_client_id_format": "Ugyldigt klient-ID",
"form_error_client_id_format": "Klient-ID må kun indeholde cifre, minuskler og bindestreger",
"form_error_server_name": "Ugyldigt servernavn",
"form_error_subnet": "Subnet \"{{cidr}}\" indeholder ikke IP-adressen \"{{ip}}\"",
"form_error_positive": "Skal være større end 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Invalid IPv6 address",
"form_error_ip_format": "Invalid IP address",
"form_error_mac_format": "Invalid MAC address",
"form_error_client_id_format": "Invalid client ID",
"form_error_client_id_format": "Client ID must contain only numbers, lowercase letters, and hyphens",
"form_error_server_name": "Invalid server name",
"form_error_subnet": "Subnet \"{{cidr}}\" does not contain the IP address \"{{ip}}\"",
"form_error_positive": "Must be greater than 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Dirección IPv6 no válida",
"form_error_ip_format": "Dirección IP no válida",
"form_error_mac_format": "Dirección MAC no válida",
"form_error_client_id_format": "ID de cliente no válido",
"form_error_client_id_format": "El ID de cliente debe contener solo números, letras minúsculas y guiones",
"form_error_server_name": "Nombre de servidor no válido",
"form_error_subnet": "La subred \"{{cidr}}\" no contiene la dirección IP \"{{ip}}\"",
"form_error_positive": "Debe ser mayor que 0",

View File

@@ -17,7 +17,7 @@
"form_error_required": "فیلد مورد نیاز",
"form_error_ip4_format": "فرمت نامعتبر IPv4",
"form_error_ip6_format": "فرمت نامعتبر IPv6",
"form_error_ip_format": "فرمت IPv4 نامعتبر است",
"form_error_ip_format": "آدرس آی پی نامعتبر است",
"form_error_mac_format": "فرمت مَک نامعتبر است",
"form_error_client_id_format": "فرمت شناسه کلاینت نامعتبر است",
"form_error_positive": "باید بزرگتر از 0 باشد",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Virheellinen IPv6-osoite",
"form_error_ip_format": "Virheellinen IP-osoite",
"form_error_mac_format": "Virheellinen MAC-osoite",
"form_error_client_id_format": "Virheellinen päätelaitteen ID",
"form_error_client_id_format": "Päätelaitteen tunniste voi sisältää ainoastaan numeroita, pieniä kirjaimia sekä yhdysviivoja",
"form_error_server_name": "Virheellinen palvelimen nimi",
"form_error_subnet": "Aliverkko \"{{cidr}}\" ei sisällä IP-osoitetta \"{{ip}}\"",
"form_error_positive": "Oltava suurempi kuin 0",
@@ -603,9 +603,9 @@
"enter_cache_size": "Syötä välimuistin koko (tavuina)",
"enter_cache_ttl_min_override": "Syötä vähimmäis-TTL (sekunteina)",
"enter_cache_ttl_max_override": "Syötä enimmäis-TTL (sekunteina)",
"cache_ttl_min_override_desc": "Pidennä ylävirran palvelimelta vastaanotettuja, lyhyitä time-to-live -arvoja (sekunteina) tallennettaessa DNS-vastauksia välimuistiin.",
"cache_ttl_max_override_desc": "Määritä DNS-välimuistin kohteiden suurin time-to-live -arvo (sekunteina)",
"ttl_cache_validation": "Välimuistin TTL-vähimmäisarvon tulee olla pienempi tai sama kuin enimmäisarvon",
"cache_ttl_min_override_desc": "Pidennä ylävirran palvelimelta vastaanotettuja, lyhyitä elinaika-arvoja (sekunteina) tallennettaessa DNS-vastauksia välimuistiin.",
"cache_ttl_max_override_desc": "Määritä DNS-välimuistin kohteiden suurin elinaika-arvo (sekunteina)",
"ttl_cache_validation": "Välimuistin elinajan vähimmäisarvon tulee olla pienempi tai sama kuin enimmäisarvon",
"cache_optimistic": "Optimistinen välimuisti",
"cache_optimistic_desc": "Pakota AdGuard Home vastaamaan välimuistista vaikka sen tiedot olisivat vanhentuneet. Pyri samalla myös päivittämään tiedot.",
"filter_category_general": "Yleiset",

View File

@@ -163,7 +163,7 @@
"apply_btn": "Primijeni",
"disabled_filtering_toast": "Onemogućeno filtriranje",
"enabled_filtering_toast": "Omogućeno filtriranje",
"disabled_safe_browsing_toast": "Onemogućena sigurna pretraga",
"disabled_safe_browsing_toast": "Onemogućena Sigurna pretraga",
"enabled_safe_browsing_toast": "Omogućena sigurna pretraga",
"disabled_parental_toast": "Onemogućen roditeljski nadzor",
"enabled_parental_toast": "Omogućen roditeljski nadzor",

View File

@@ -36,7 +36,7 @@
"dhcp_ipv4_settings": "DHCP IPv4 Beállítások",
"dhcp_ipv6_settings": "DHCP IPv6 Beállítások",
"form_error_required": "Kötelező mező",
"form_error_ip4_format": "Érvénytelen IPv4 formátum",
"form_error_ip4_format": "Érvénytelen IPv4 m",
"form_error_ip6_format": "Érvénytelen IPv6 formátum",
"form_error_ip_format": "Érvénytelen IP-cím",
"form_error_mac_format": "Érvénytelen MAC formátum",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Indirizzo IPv6 non valido",
"form_error_ip_format": "Indirizzo IP non valido",
"form_error_mac_format": "Indirizzo MAC non valido",
"form_error_client_id_format": "ID cliente non valido",
"form_error_client_id_format": "Il client ID deve contenere solo numeri, lettere minuscole e trattini",
"form_error_server_name": "Nome server non valido",
"form_error_subnet": "La subnet \"{{cidr}}\" non contiene l'indirizzo IP \"{{ip}}\"",
"form_error_positive": "Deve essere maggiore di 0",
@@ -295,16 +295,16 @@
"blocking_mode_null_ip": "IP nullo: Rispondi con indirizzo IP zero (0.0.0.0 per A; :: per AAAA)",
"blocking_mode_custom_ip": "IP personalizzato: Rispondi con un indirizzo IP impostato manualmente",
"upstream_dns_client_desc": "Se lasci questo spazio vuoto, AdGuard Home utilizzerà i server configurati nelle <0>impostazioni DNS</0>.",
"tracker_source": "Origine tracciante",
"tracker_source": "Origine del tracciatore",
"source_label": "Fonte",
"found_in_known_domain_db": "Trovato nel database dei domini conosciuti.",
"found_in_known_domain_db": "Trovato nel database dei domini noti.",
"category_label": "Categoria",
"rule_label": "Regola(e)",
"list_label": "Elenco",
"unknown_filter": "Filtro sconosciuto {{filterId}}",
"known_tracker": "Tracciante noto",
"known_tracker": "Tracciatore noto",
"install_welcome_title": "Benvenuto nella Home di AdGuard!",
"install_welcome_desc": "AdGuard Home è un server DNS che blocca annunci e traccianti in tutta la rete. Il suo scopo è quello di consentire di controllare l'intera rete e tutti i dispositivi, e non richiede l'utilizzo di un programma sul lato client.",
"install_welcome_desc": "AdGuard Home è un server DNS che blocca annunci e tracciatori a livello di rete. Il suo scopo è quello di permetterti il controllo dell'intera rete e di tutti i dispositivi, e non richiede l'utilizzo di un programma lato client.",
"install_settings_title": "Interfaccia Web dell'Admin",
"install_settings_listen": "Interfaccia d'ascolto",
"install_settings_port": "Porta",
@@ -400,7 +400,7 @@
"dns_status_error": "Errore nel recupero dello stato del server DNS",
"down": "Spenta",
"fix": "Risolvi",
"dns_providers": "Qui c'è un <0>elenco di fornitori DNS conosciuti</0> da cui scegliere.",
"dns_providers": "Qui c'è un <0>elenco di fornitori DNS noti</0> da cui scegliere.",
"update_now": "Aggiorna ora",
"update_failed": "Aggiornamento automatico non riuscito. Ti suggeriamo di <a>seguire questi passaggi</a> per aggiornare manualmente.",
"processing_update": "Perfavore aspetta, AdGuard Home si sta aggiornando",
@@ -612,9 +612,9 @@
"filter_category_security": "Sicurezza",
"filter_category_regional": "Regionale",
"filter_category_other": "Altro",
"filter_category_general_desc": "Elenchi per il blocco dei traccianti e degli annunci sulla maggioranza dei dispositivi",
"filter_category_general_desc": "Elenchi per il blocco dei tracciatori e degli annunci sulla maggioranza dei dispositivi",
"filter_category_security_desc": "Elenchi progettati specificamente per bloccare domini malevoli, di phishing o truffa",
"filter_category_regional_desc": "Elenchi focalizzati su annunci regionali e server traccianti",
"filter_category_regional_desc": "Elenchi focalizzati su annunci regionali e server tracciatori",
"filter_category_other_desc": "Altre liste nere",
"setup_config_to_enable_dhcp_server": "Configurazione dell'installazione per l'attivazione del server DHCP",
"original_response": "Responso originale",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Ongeldig IPv6-adres",
"form_error_ip_format": "Ongeldig IP-adres",
"form_error_mac_format": "Ongeldig MAC-adres",
"form_error_client_id_format": "Ongeldige cliënt-ID",
"form_error_client_id_format": "Client-ID mag alleen cijfers, kleine letters en koppeltekens bevatten",
"form_error_server_name": "Ongeldige servernaam",
"form_error_subnet": "Subnet “{{cidr}}” bevat niet het IP-adres “{{ip}}”",
"form_error_positive": "Moet groter zijn dan 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Nieprawidłowy adres IPv6",
"form_error_ip_format": "Nieprawidłowy adres IP",
"form_error_mac_format": "Nieprawidłowy adres MAC",
"form_error_client_id_format": "Nieprawidłowy ID klienta",
"form_error_client_id_format": "ID klienta musi zawierać tylko cyfry, małe litery i myślniki",
"form_error_server_name": "Nieprawidłowa nazwa serwera",
"form_error_subnet": "Podsieć \"{{cidr}}\" nie zawiera adresu IP \"{{ip}}\"",
"form_error_positive": "Musi być większa niż 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Endereço de IPv6 inválido",
"form_error_ip_format": "Endereço de IP inválido",
"form_error_mac_format": "Endereço de MAC inválido",
"form_error_client_id_format": "ID de cliente inválido",
"form_error_client_id_format": "O ID do cliente deve conter apenas números, letras minúsculas e hifens",
"form_error_server_name": "Nome de servidor inválido",
"form_error_subnet": "A sub-rede \"{{cidr}}\" não contém o endereço IP \"{{ip}}\"",
"form_error_positive": "Deve ser maior que 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Endereço de IPv6 inválido",
"form_error_ip_format": "Endereço de IP inválido",
"form_error_mac_format": "Endereço de MAC inválido",
"form_error_client_id_format": "ID de cliente inválido",
"form_error_client_id_format": "O ID do cliente deve conter apenas números, letras minúsculas e hifens",
"form_error_server_name": "Nome de servidor inválido",
"form_error_subnet": "A sub-rede \"{{cidr}}\" não contém o endereço IP \"{{ip}}\"",
"form_error_positive": "Deve ser maior que 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Adresa IPv6 nevalidă",
"form_error_ip_format": "Adresă IP nevalidă",
"form_error_mac_format": "Adresă MAC nevalidă",
"form_error_client_id_format": "ID client nevalid",
"form_error_client_id_format": "ID-ul clientului trebuie să conțină numai numere, litere minuscule și liniuțe.",
"form_error_server_name": "Nume de server nevalid",
"form_error_subnet": "Subrețeaua „{{cidr}}” nu conține adresa IP „{{ip}}”",
"form_error_positive": "Trebuie să fie mai mare de 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Некорректный IPv6-адрес",
"form_error_ip_format": "Некорректный IP-адрес",
"form_error_mac_format": "Некорректный MAC-адрес",
"form_error_client_id_format": "Некорректный ID клиента",
"form_error_client_id_format": "ID клиента может содержать только цифры, строчные латинские буквы и дефисы",
"form_error_server_name": "Некорректное имя сервера",
"form_error_subnet": "Подсеть «{{cidr}}» не содержит IP-адрес «{{ip}}»",
"form_error_positive": "Должно быть больше 0",
@@ -587,7 +587,7 @@
"show_blocked_responses": "Заблокировано",
"show_whitelisted_responses": "В белом списке",
"show_processed_responses": "Обработан",
"blocked_safebrowsing": "Заблокировано согласно базе данных Safebrowsing",
"blocked_safebrowsing": "Заблокировано согласно базе данных Safe Browsing",
"blocked_adult_websites": "Заблокировано Родительским контролем",
"blocked_threats": "Заблокировано угроз",
"allowed": "Разрешённые",

View File

@@ -163,8 +163,8 @@
"apply_btn": "Použiť",
"disabled_filtering_toast": "Vypnutá filtrácia",
"enabled_filtering_toast": "Zapnutá filtrácia",
"disabled_safe_browsing_toast": "Vypnuté Bezpečné prehliadanie",
"enabled_safe_browsing_toast": "Zapnuté Bezpečné prehliadanie",
"disabled_safe_browsing_toast": "Bezpečné prehliadanie vypnuté",
"enabled_safe_browsing_toast": "Bezpečné prehliadanie zapnuté",
"disabled_parental_toast": "Vypnutá Rodičovská kontrola",
"enabled_parental_toast": "Zapnutá Rodičovská kontrola",
"disabled_safe_search_toast": "Vypnuté bezpečné vyhľadávanie",
@@ -588,7 +588,7 @@
"show_whitelisted_responses": "Obsiahnuté v bielej listine",
"show_processed_responses": "Spracované",
"blocked_safebrowsing": "Zablokované modulom Bezpečné prehliadanie",
"blocked_adult_websites": "Blokované Rodičovskou kontrolou",
"blocked_adult_websites": "Zablokovaná stránka pre dospelých",
"blocked_threats": "Zablokované hrozby",
"allowed": "Povolené",
"filtered": "Filtrované",

View File

@@ -16,6 +16,8 @@
"dhcp_static_leases": "Statiska DHCP-leases",
"dhcp_leases_not_found": "Ingen DHCP-lease hittad",
"form_error_required": "Obligatoriskt fält",
"form_error_ip4_format": "Ogiltig IPv4-adress",
"form_error_ip6_format": "Ogiltig IPv6-adress",
"form_error_ip_format": "Ogiltig IP-adress",
"form_error_mac_format": "Ogiltig MAC-adress",
"form_error_positive": "Måste vara större än noll",
@@ -351,7 +353,7 @@
"show_blocked_responses": "Blockerade",
"show_whitelisted_responses": "Vitlistade",
"show_processed_responses": "Utförda",
"blocked_adult_websites": "Blockerad av Föräldrakontrollen",
"blocked_adult_websites": "Blockerad av Föräldrakontroll",
"blocked_threats": "Blockerade hot",
"allowed": "Vitlistade",
"safe_search": "Säker surf",
@@ -359,5 +361,5 @@
"filter_category_security": "säkerhet",
"filter_category_other": "Övrigt",
"use_saved_key": "Använd den tidigare sparade nyckeln",
"parental_control": "Föräldrarkontroll"
"parental_control": "Föräldrakontroll"
}

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "IPv6 adresi geçersiz",
"form_error_ip_format": "IP adresi geçersiz",
"form_error_mac_format": "MAC adresi geçersiz",
"form_error_client_id_format": "İstemci kimliği geçersiz",
"form_error_client_id_format": "İstemci kimliği yalnızca sayılar, küçük harfler ve kısa çizgiler içermelidir",
"form_error_server_name": "Sunucu adı geçersiz",
"form_error_subnet": "\"{{cidr}}\" alt ağı, \"{{ip}}\" IP adresini içermiyor",
"form_error_positive": "0'dan büyük olmalıdır",
@@ -53,7 +53,7 @@
"greater_range_end_error": "Bitiş aralığından daha büyük olmalıdır",
"subnet_error": "Adresler bir alt ağda olmalıdır",
"gateway_or_subnet_invalid": "Alt ağ maskesi geçersiz",
"dhcp_form_gateway_input": "Ağ Geçidi IP'si",
"dhcp_form_gateway_input": "Ağ geçidi IP",
"dhcp_form_subnet_input": "Alt ağ maskesi",
"dhcp_form_range_title": "IP adresi aralığı",
"dhcp_form_range_start": "Başlangıç aralığı",
@@ -138,7 +138,7 @@
"average_processing_time": "Ortalama işlem süresi",
"average_processing_time_hint": "Bir DNS isteğinin milisaniye cinsinden ortalama işlem süresi",
"block_domain_use_filters_and_hosts": "Filtre ve ana bilgisayar listelerini kullanarak alan adlarını engelle",
"filters_block_toggle_hint": "<a>Filtreler</a> sayfasından engelleme kurallarını ayarlayabilirsiniz.",
"filters_block_toggle_hint": "<a>Filtreler</a> ayarlarında engelleme kuralları oluşturabilirsiniz.",
"use_adguard_browsing_sec": "AdGuard gezinti koruması web hizmetini kullan",
"use_adguard_browsing_sec_hint": "AdGuard Home, alan adının gezinti koruması web hizmeti tarafından engellenip engellenmediğini kontrol eder. Kontrolü gerçekleştirmek için gizlilik dostu arama API'sini kullanır: sunucuya yalnızca SHA256 karma alan adının kısa bir ön eki gönderilir.",
"use_adguard_parental": "AdGuard ebeveyn denetimi web hizmetini kullan",
@@ -165,10 +165,10 @@
"enabled_filtering_toast": "Filtreleme etkin",
"disabled_safe_browsing_toast": "Güvenli Gezinti devre dışı bırakıldı",
"enabled_safe_browsing_toast": "Güvenli Gezinti etkinleştirildi",
"disabled_parental_toast": "Ebeveyn denetimi devre dışı",
"enabled_parental_toast": "Ebeveyn denetimi etkin",
"disabled_safe_search_toast": "Güvenli arama devre dışı",
"enabled_save_search_toast": "Güvenli arama etkin",
"disabled_parental_toast": "Ebeveyn denetimi devre dışı bırakıldı",
"enabled_parental_toast": "Ebeveyn denetimi etkinleştirildi",
"disabled_safe_search_toast": "Güvenli arama devre dışı bırakıldı",
"enabled_save_search_toast": "Güvenli arama etkinleştirildi",
"enabled_table_header": "Etkin",
"name_table_header": "İsim",
"list_url_table_header": "Liste URL'si",
@@ -178,7 +178,7 @@
"request_table_header": "İstek",
"edit_table_action": "Düzenle",
"delete_table_action": "Sil",
"elapsed": "Geçen zaman",
"elapsed": "Geçen süre",
"filters_and_hosts_hint": "AdGuard Home, temel reklam engelleme kurallarını ve ana bilgisayar engelleme dosyalarının söz dizimini anlar.",
"no_blocklist_added": "Engel listesi eklenmedi",
"no_whitelist_added": "İzin listesi eklenmedi",
@@ -327,10 +327,10 @@
"install_submit_desc": "Yükleme işlemi tamamlandı ve artık AdGuard Home'u kullanmaya hazırsınız.",
"install_devices_router": "Yönlendirici",
"install_devices_router_desc": "Bu kurulum, ev yönlendiricinize bağlı tüm cihazları otomatik olarak kapsar ve her birini elle yapılandırmanıza gerek yoktur.",
"install_devices_address": "AdGuard Home DNS sunucusu şu adresi dinleyecektir",
"install_devices_address": "AdGuard Home DNS sunucusu aşağıdaki adresleri dinliyor",
"install_devices_router_list_1": "Yönlendiricinizin ayarlarına gidin. Genellikle tarayıcınızdan http://192.168.0.1/ veya http://192.168.1.1/ gibi bir URL aracılığıyla erişebilirsiniz. Bir parola girmeniz istenebilir. Hatırlamıyorsanız, genellikle yönlendiricinin üzerindeki bir düğmeye basarak parolayı sıfırlayabilirsiniz, ancak bu işlemin seçilmesi durumunda yüksek ihtimalle tüm yönlendirici yapılandırmasını kaybedeceğinizi unutmayın. Yönlendiricinizin kurulumu için bir uygulama gerekiyorsa, lütfen uygulamayı telefonunuza veya PC'nize yükleyin ve yönlendiricinin ayarlarına erişmek için kullanın.",
"install_devices_router_list_2": "DHCP/DNS ayarlarını bulun. DNS satırlarını arayın, genelde iki veya üç tanedir, üç rakam girilebilen dört ayrı grup içeren satırdır.",
"install_devices_router_list_3": "AdGuard Home sunucusunun adresini o kısma yazın.",
"install_devices_router_list_3": "AdGuard Home sunucu adreslerinizi oraya girin.",
"install_devices_router_list_4": "Bazı yönlendirici türlerinde özel bir DNS sunucusu ayarlanamaz. Bu durumda, AdGuard Home'u <0>DHCP sunucusu</0> olarak ayarlamak yardımcı olabilir. Aksi takdirde, yönlendirici modeliniz için DNS sunucularını nasıl ayarlayacağınız konusunda yönlendirici kılavuzuna bakmalısınız.",
"install_devices_windows_list_1": "Başlat menüsünden veya Windows araması aracılığıyla Denetim Masası'nıın.",
"install_devices_windows_list_2": "Ağ ve İnternet kategorisine girin ve ardından Ağ ve Paylaşım Merkezi'ne girin.",
@@ -339,15 +339,15 @@
"install_devices_windows_list_5": "Listede \"İnternet Protokolü Sürüm 4 (TCP/IPv4)\" (veya IPv6 için \"İnternet Protokolü Sürüm 6 (TCP/IPv6)\") öğesini bulun, seçin ve ardından tekrar Özellikler'e tıklayın.",
"install_devices_windows_list_6": "\"Aşağıdaki DNS sunucu adreslerini kullan\"ı seçin ve AdGuard Home sunucu adreslerinizi girin.",
"install_devices_macos_list_1": "Apple simgesinde bulunan Sistem Tercihleri'ne tıklayın.",
"install_devices_macos_list_2": "Ağ seçeneğine tıklayın.",
"install_devices_macos_list_2": "Ağ'a tıklayın.",
"install_devices_macos_list_3": "Listedeki ilk bağlantıyı seçin ve Gelişmiş öğesine tıklayın.",
"install_devices_macos_list_4": "DNS sekmesini seçin ve AdGuard Home sunucunuzun adreslerini girin.",
"install_devices_android_list_1": "Android cihazınızda Ayarlar simgesine dokunun.",
"install_devices_android_list_1": "Android Menüsü ana ekranından Ayarlar'a dokunun.",
"install_devices_android_list_2": "Menüde bulunan Wi-Fi seçeneğine dokunun. Mevcut tüm ağlar listelenecektir (mobil ağlar için özel DNS sunucusu ayarlanamaz).",
"install_devices_android_list_3": "Bağlı olduğunuz ağın üzerine basılı tutun ve Ağı Değiştir'e dokunun.",
"install_devices_android_list_4": "Bazı cihazlarda, diğer ayarları görmek için \"Gelişmiş\" seçeneğini seçmeniz gerekebilir. Android DNS ayarlarınızı yapmak için IP ayarlarını DHCP modundan Statik moda almanız gerekecektir.",
"install_devices_android_list_5": "DNS 1 ve DNS 2 değerlerini AdGuard Home sunucunuzun adresleriyle değiştirin.",
"install_devices_ios_list_1": "Ana ekrandaki Ayarlar simgesine dokunun.",
"install_devices_ios_list_1": "Ana ekrandan Ayarlar'a dokunun.",
"install_devices_ios_list_2": "Sol menüde bulunan Wi-Fi bölümüne girin (mobil ağlar için özel DNS sunucusu ayarlanamaz).",
"install_devices_ios_list_3": "Bağlı olduğunuz ağın ismine dokunun.",
"install_devices_ios_list_4": "DNS alanına AdGuard Home sunucunuzun adreslerini girin.",
@@ -386,8 +386,8 @@
"encryption_issuer": "Sağlayan",
"encryption_hostnames": "Ana bilgisayar adları",
"encryption_reset": "Şifreleme ayarlarını sıfırlamak istediğinizden emin misiniz?",
"topline_expiring_certificate": "SSL sertifikanızın süresi dolmak üzere. <0>Şifreleme ayarlarını</0> güncelleyin.",
"topline_expired_certificate": "SSL sertifikanızın süresi doldu. <0>Şifreleme ayarlarını</0> güncelleyin.",
"topline_expiring_certificate": "SSL sertifikanızın süresi sona erdi. <0>Şifreleme ayarlarını</0> güncelleyin.",
"topline_expired_certificate": "SSL sertifikanızın süresi sona erdi. <0>Şifreleme ayarlarını</0> güncelleyin.",
"form_error_port_range": "80-65535 aralığında geçerli bir bağlantı noktası değeri girin",
"form_error_port_unsafe": "Bu bağlantı noktası güvenli değil",
"form_error_equal": "Aynı olmamalı",
@@ -417,7 +417,7 @@
"client_identifier": "Tanımlayıcı",
"ip_address": "IP adresi",
"client_identifier_desc": "İstemciler IP adresi, CIDR, MAC adresi veya özel bir istemci kimliği ile tanımlanabilir (DoT/DoH/DoQ için kullanılabilir). İstemcileri nasıl tanımlayacağınız hakkında daha fazla bilgiyi <0>burada</0> bulabilirsiniz.",
"form_enter_ip": "IP adresi girin",
"form_enter_ip": "IP girin",
"form_enter_subnet_ip": "\"{{cidr}}\" alt ağına bir IP adresi girin",
"form_enter_mac": "MAC adresi girin",
"form_enter_id": "Tanımlayıcı girin",
@@ -439,7 +439,7 @@
"access_allowed_desc": "CIDR'lerin, IP adreslerinin veya istemci kimliklerinin listesi. Yapılandırılırsa, AdGuard Home yalnızca bu istemcilerden gelen istekleri kabul eder.",
"access_disallowed_title": "İzin verilmeyen istemciler",
"access_disallowed_desc": "CIDR'lerin, IP adreslerinin veya istemci kimliklerinin listesi. Yapılandırılırsa, AdGuard Home bu istemcilerden gelen istekleri keser. İzin verilen istemciler yapılandırılırsa, bu alan yok sayılır.",
"access_blocked_title": "Engellenen alan adları",
"access_blocked_title": "İzin verilmeyen alan adları",
"access_blocked_desc": "Bu işlem filtrelerle ilgili değildir. AdGuard Home, bu alan adlarından gelen DNS sorgularını yanıtsız bırakır ve bu sorgular sorgu günlüğünde görünmez. Tam alan adlarını, joker karakterleri veya URL filtre kurallarını belirtebilirsiniz, ör. \"example.org\", \"*.example.org\" veya \"||example.org^\".",
"access_settings_saved": "Erişim ayarları başarıyla kaydedildi!",
"updates_checked": "Güncelleme kontrolü başarılı",
@@ -601,8 +601,8 @@
"cache_ttl_min_override": "Minimum TTL'i değiştir",
"cache_ttl_max_override": "Maksimum TTL'i değiştir",
"enter_cache_size": "Önbellek boyutunu girin (bayt)",
"enter_cache_ttl_min_override": "Minimum TTL değerini girin (saniye)",
"enter_cache_ttl_max_override": "Maksimum TTL değerini girin (saniye)",
"enter_cache_ttl_min_override": "Minimum TTL değerini girin (saniye olarak)",
"enter_cache_ttl_max_override": "Maksimum TTL değerini girin (saniye olarak)",
"cache_ttl_min_override_desc": "DNS yanıtlarını önbelleğe alırken üst sunucudan alınan kullanım süresi değerini uzatın (saniye olarak)",
"cache_ttl_max_override_desc": "DNS önbelleğindeki girişler için maksimum kullanım süresi değerini ayarlayın (saniye olarak)",
"ttl_cache_validation": "Minimum önbellek TTL değeri, maksimum değerden küçük veya bu değere eşit olmalıdır",
@@ -626,5 +626,6 @@
"experimental": "Deneysel",
"use_saved_key": "Önceden kaydedilmiş anahtarı kullan",
"parental_control": "Ebeveyn Denetimi",
"safe_browsing": "Güvenli Gezinti"
"safe_browsing": "Güvenli Gezinti",
"served_from_cache": "{{value}} <i>(önbellekten kullanıldı)</i>"
}

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "Неправильна IPv6-адреса",
"form_error_ip_format": "Неправильна IP-адреса",
"form_error_mac_format": "Неправильна MAC-адреса",
"form_error_client_id_format": "Неправильний ID клієнта",
"form_error_client_id_format": "ID клієнта має містити лише цифри, малі букви та дефіси",
"form_error_server_name": "Неправильна назва сервера",
"form_error_subnet": "Підмережа «{{cidr}}» не містить IP-адресу «{{ip}}»",
"form_error_positive": "Повинно бути більше 0",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "无效的 IPv6 地址",
"form_error_ip_format": "无效的 IP 地址",
"form_error_mac_format": "无效的 MAC 地址",
"form_error_client_id_format": "无效的客户端 ID",
"form_error_client_id_format": "无效的客户端 ID 格式客户 ID 必须只包含数字、小写字母和连字符",
"form_error_server_name": "无效的服务器名",
"form_error_subnet": "子网 \"{{cidr}}\" 不包含 IP 地址 \"{{ip}}\"",
"form_error_positive": "必须大于 0",
@@ -588,7 +588,7 @@
"show_whitelisted_responses": "已列入白名单",
"show_processed_responses": "已处理",
"blocked_safebrowsing": "被安全浏览阻止",
"blocked_adult_websites": "已由家长控制拦截",
"blocked_adult_websites": "家长控制阻止",
"blocked_threats": "拦截的威胁",
"allowed": "允许项",
"filtered": "已过滤",

View File

@@ -43,7 +43,7 @@
"form_error_ip6_format": "無效的 IPv6 位址",
"form_error_ip_format": "無效的 IP 位址",
"form_error_mac_format": "無效的媒體存取控制MAC位址",
"form_error_client_id_format": "無效的用戶端 ID",
"form_error_client_id_format": "用戶端 ID 必須只包含數值、小寫字母和連字號",
"form_error_server_name": "無效的伺服器名稱",
"form_error_subnet": "子網路 \"{{cidr}}\" 不包含該 IP 位址 \"{{ip}}\"",
"form_error_positive": "必須大於 0",
@@ -146,7 +146,7 @@
"enforce_safe_search": "使用安全搜尋",
"enforce_save_search_hint": "AdGuard Home 將在下列的搜尋引擎Google、YouTube、Bing、DuckDuckGo、Yandex 和 Pixabay 中強制執行安全搜尋。",
"no_servers_specified": "無已明確指定的伺服器",
"general_settings": "一般設定",
"general_settings": "一般設定",
"dns_settings": "DNS 設定",
"dns_blocklists": "DNS 封鎖清單",
"dns_allowlists": "DNS 允許清單",

View File

@@ -4,7 +4,7 @@ import { Trans, withTranslation } from 'react-i18next';
import ReactTable from 'react-table';
import { MODAL_TYPE } from '../../../helpers/constants';
import { splitByNewLine, countClientsStatistics } from '../../../helpers/helpers';
import { splitByNewLine, countClientsStatistics, sortIp } from '../../../helpers/helpers';
import Card from '../../ui/Card';
import Modal from './Modal';
import CellWrap from '../../ui/CellWrap';
@@ -106,6 +106,7 @@ class ClientsTable extends Component {
</div>
);
},
sortMethod: sortIp,
},
{
Header: this.props.t('table_name'),

View File

@@ -13,6 +13,12 @@ const Version = () => {
checkUpdateFlag,
} = useSelector((state) => state?.dashboard ?? {}, shallowEqual);
const {
dnsVersion: installDnsVersion,
} = useSelector((state) => state?.install ?? {}, shallowEqual);
const version = dnsVersion || installDnsVersion;
const onClick = () => {
dispatch(getVersion(true));
};
@@ -20,11 +26,12 @@ const Version = () => {
return (
<div className="version">
<div className="version__text">
{dnsVersion
&& <>
<Trans>version</Trans>:&nbsp;
<span className="version__value" title={dnsVersion}>{dnsVersion}</span>
</>}
{version && (
<>
<Trans>version</Trans>:&nbsp;
<span className="version__value" title={version}>{version}</span>
</>
)}
{checkUpdateFlag && <button
type="button"
className="btn btn-icon btn-icon-sm btn-outline-primary btn-sm ml-2"

View File

@@ -754,8 +754,10 @@ const getAddressesComparisonBytes = (item) => {
*/
export const sortIp = (a, b) => {
try {
const comparisonBytesA = getAddressesComparisonBytes(a);
const comparisonBytesB = getAddressesComparisonBytes(b);
const comparisonBytesA = Array.isArray(a)
? getAddressesComparisonBytes(a[0]) : getAddressesComparisonBytes(a);
const comparisonBytesB = Array.isArray(b)
? getAddressesComparisonBytes(b[0]) : getAddressesComparisonBytes(b);
for (let i = 0; i < comparisonBytesA.length; i += 1) {
const byteA = comparisonBytesA[i];

View File

@@ -12,13 +12,19 @@ const install = handleActions({
[actions.getDefaultAddressesRequest]: (state) => ({ ...state, processingDefault: true }),
[actions.getDefaultAddressesFailure]: (state) => ({ ...state, processingDefault: false }),
[actions.getDefaultAddressesSuccess]: (state, { payload }) => {
const { interfaces } = payload;
const { interfaces, version } = payload;
const web = { ...state.web, port: payload.web_port };
const dns = { ...state.dns, port: payload.dns_port };
const newState = {
...state, web, dns, interfaces, processingDefault: false,
...state,
web,
dns,
interfaces,
processingDefault: false,
dnsVersion: version,
};
return newState;
},
@@ -64,6 +70,7 @@ const install = handleActions({
error: '',
},
interfaces: {},
dnsVersion: '',
});
export default combineReducers({

6
go.mod
View File

@@ -3,9 +3,9 @@ module github.com/AdguardTeam/AdGuardHome
go 1.17
require (
github.com/AdguardTeam/dnsproxy v0.40.3
github.com/AdguardTeam/golibs v0.10.3
github.com/AdguardTeam/urlfilter v0.15.1
github.com/AdguardTeam/dnsproxy v0.40.5
github.com/AdguardTeam/golibs v0.10.4
github.com/AdguardTeam/urlfilter v0.15.2
github.com/NYTimes/gziphandler v1.1.1
github.com/ameshkov/dnscrypt/v2 v2.2.3
github.com/digineo/go-ipset/v2 v2.2.1

13
go.sum
View File

@@ -7,16 +7,16 @@ dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBr
dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4=
dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU=
git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg=
github.com/AdguardTeam/dnsproxy v0.40.3 h1:rdQBp3LMmOdD4EpRtnutfP4zwqNA/Q5TyYNNDyjSeQY=
github.com/AdguardTeam/dnsproxy v0.40.3/go.mod h1:PZ9l22h3Er+5mxFQB7oHZMTvx+aa9R6LbzA/ikXQlS0=
github.com/AdguardTeam/dnsproxy v0.40.5 h1:727KSGRmzq2DB5dMm093g0Guhc3dzzzMbfB0C9hK0s8=
github.com/AdguardTeam/dnsproxy v0.40.5/go.mod h1:PZ9l22h3Er+5mxFQB7oHZMTvx+aa9R6LbzA/ikXQlS0=
github.com/AdguardTeam/golibs v0.4.0/go.mod h1:skKsDKIBB7kkFflLJBpfGX+G8QFTx0WKUzB6TIgtUj4=
github.com/AdguardTeam/golibs v0.4.2/go.mod h1:skKsDKIBB7kkFflLJBpfGX+G8QFTx0WKUzB6TIgtUj4=
github.com/AdguardTeam/golibs v0.9.2/go.mod h1:fCAMwPBJ8S7YMYbTWvYS+eeTLblP5E04IDtNAo7y7IY=
github.com/AdguardTeam/golibs v0.10.3 h1:FBgk17zf35ESVWQKIqEUiqqB2bDaCBC8X5vMU760yB4=
github.com/AdguardTeam/golibs v0.10.3/go.mod h1:rSfQRGHIdgfxriDDNgNJ7HmE5zRoURq8R+VdR81Zuzw=
github.com/AdguardTeam/golibs v0.10.4 h1:TMBkablZC0IZOpRgg9fzAKlxxNhSN2YJq7qbgtuZ7PQ=
github.com/AdguardTeam/golibs v0.10.4/go.mod h1:rSfQRGHIdgfxriDDNgNJ7HmE5zRoURq8R+VdR81Zuzw=
github.com/AdguardTeam/gomitmproxy v0.2.0/go.mod h1:Qdv0Mktnzer5zpdpi5rAwixNJzW2FN91LjKJCkVbYGU=
github.com/AdguardTeam/urlfilter v0.15.1 h1:dP6S7J6eFAk8MN4IDpUq2fZoBo8K8fmc6pXpxNIv84M=
github.com/AdguardTeam/urlfilter v0.15.1/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU=
github.com/AdguardTeam/urlfilter v0.15.2 h1:LZGgrm4l4Ys9eAqB+UUmZfiC6vHlDlYFhx0WXqo6LtQ=
github.com/AdguardTeam/urlfilter v0.15.2/go.mod h1:46YZDOV1+qtdRDuhZKVPSSp7JWWes0KayqHrKAFBdEI=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw=
github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
@@ -343,7 +343,6 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210908191846-a5e095526f91/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210929193557-e81a3d93ecf6/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=

View File

@@ -1,7 +1,7 @@
// Package aghalgo contains common generic algorithms and data structures.
// Package aghalg contains common generic algorithms and data structures.
//
// TODO(a.garipov): Update to use type parameters in Go 1.18.
package aghalgo
package aghalg
import (
"fmt"
@@ -14,20 +14,20 @@ import (
// TODO(a.garipov): Remove in Go 1.18.
type comparable = interface{}
// UniquenessValidator allows validating uniqueness of comparable items.
type UniquenessValidator map[comparable]int64
// UniqChecker allows validating uniqueness of comparable items.
type UniqChecker map[comparable]int64
// Add adds a value to the validator. v must not be nil.
func (v UniquenessValidator) Add(elems ...comparable) {
func (uc UniqChecker) Add(elems ...comparable) {
for _, e := range elems {
v[e]++
uc[e]++
}
}
// Merge returns a validator containing data from both v and other.
func (v UniquenessValidator) Merge(other UniquenessValidator) (merged UniquenessValidator) {
merged = make(UniquenessValidator, len(v)+len(other))
for elem, num := range v {
// Merge returns a checker containing data from both uc and other.
func (uc UniqChecker) Merge(other UniqChecker) (merged UniqChecker) {
merged = make(UniqChecker, len(uc)+len(other))
for elem, num := range uc {
merged[elem] += num
}
@@ -41,9 +41,9 @@ func (v UniquenessValidator) Merge(other UniquenessValidator) (merged Uniqueness
// Validate returns an error enumerating all elements that aren't unique.
// isBefore is an optional sorting function to make the error message
// deterministic.
func (v UniquenessValidator) Validate(isBefore func(a, b comparable) (less bool)) (err error) {
func (uc UniqChecker) Validate(isBefore func(a, b comparable) (less bool)) (err error) {
var dup []comparable
for elem, num := range v {
for elem, num := range uc {
if num > 1 {
dup = append(dup, elem)
}
@@ -62,13 +62,13 @@ func (v UniquenessValidator) Validate(isBefore func(a, b comparable) (less bool)
return fmt.Errorf("duplicated values: %v", dup)
}
// IntIsBefore is a helper sort function for UniquenessValidator.Validate.
// IntIsBefore is a helper sort function for UniqChecker.Validate.
// a and b must be of type int.
func IntIsBefore(a, b comparable) (less bool) {
return a.(int) < b.(int)
}
// StringIsBefore is a helper sort function for UniquenessValidator.Validate.
// StringIsBefore is a helper sort function for UniqChecker.Validate.
// a and b must be of type string.
func StringIsBefore(a, b comparable) (less bool) {
return a.(string) < b.(string)

View File

@@ -19,7 +19,8 @@ import (
"github.com/insomniacslk/dhcp/iana"
)
// defaultDiscoverTime is the
// defaultDiscoverTime is the default timeout of checking another DHCP server
// response.
const defaultDiscoverTime = 3 * time.Second
func checkOtherDHCP(ifaceName string) (ok4, ok6 bool, err4, err6 error) {

View File

@@ -72,7 +72,11 @@ func (rm *requestMatcher) MatchRequest(
}
// Translate returns the source hosts-syntax rule for the generated dnsrewrite
// rule or an empty string if the last doesn't exist.
// rule or an empty string if the last doesn't exist. The returned rules are in
// a processed format like:
//
// ip host1 host2 ...
//
func (rm *requestMatcher) Translate(rule string) (hostRule string) {
rm.stateLock.RLock()
defer rm.stateLock.RUnlock()
@@ -179,7 +183,7 @@ func NewHostsContainer(
return nil, fmt.Errorf("adding path: %w", err)
}
log.Debug("%s: file %q expected to exist but doesn't", hostsContainerPref, p)
log.Debug("%s: %s is expected to exist but doesn't", hostsContainerPref, p)
}
}
@@ -199,7 +203,7 @@ func (hc *HostsContainer) Close() (err error) {
}
// Upd returns the channel into which the updates are sent. The receivable
// map's values are guaranteed to be of type of *stringutil.Set.
// map's values are guaranteed to be of type of *aghnet.Hosts.
func (hc *HostsContainer) Upd() (updates <-chan *netutil.IPMap) {
return hc.updates
}
@@ -228,8 +232,9 @@ func pathsToPatterns(fsys fs.FS, paths []string) (patterns []string, err error)
return patterns, nil
}
// handleEvents concurrently handles the events. It closes the update channel
// of HostsContainer when finishes. Used to be called within a goroutine.
// handleEvents concurrently handles the file system events. It closes the
// update channel of HostsContainer when finishes. It's used to be called
// within a separate goroutine.
func (hc *HostsContainer) handleEvents() {
defer log.OnPanic(fmt.Sprintf("%s: handling events", hostsContainerPref))
@@ -254,17 +259,27 @@ func (hc *HostsContainer) handleEvents() {
}
}
// ipRules is the pair of generated A/AAAA and PTR rules with related IP.
type ipRules struct {
// rule is the A/AAAA $dnsrewrite rule.
rule string
// rulePtr is the PTR $dnsrewrite rule.
rulePtr string
// ip is the IP address related to the rules.
ip net.IP
}
// hostsParser is a helper type to parse rules from the operating system's hosts
// file. It exists for only a single refreshing session.
type hostsParser struct {
// rulesBuilder builds the resulting rulesBuilder list content.
// rulesBuilder builds the resulting rules list content.
rulesBuilder *strings.Builder
// translations maps generated $dnsrewrite rules to the hosts-translations
// rules.
translations map[string]string
// rules stores the rules for main hosts to generate translations.
rules []ipRules
// cnameSet prevents duplicating cname rules.
// cnameSet prevents duplicating cname rules, e.g. same hostname for
// different IP versions.
cnameSet *stringutil.Set
// table stores only the unique IP-hostname pairs. It's also sent to the
@@ -272,13 +287,16 @@ type hostsParser struct {
table *netutil.IPMap
}
// newHostsParser creates a new *hostsParser with buffers of size taken from the
// previous parse.
func (hc *HostsContainer) newHostsParser() (hp *hostsParser) {
lastLen := hc.last.Len()
return &hostsParser{
rulesBuilder: &strings.Builder{},
// For A/AAAA and PTRs.
translations: make(map[string]string, hc.last.Len()*2),
rules: make([]ipRules, 0, lastLen),
cnameSet: stringutil.NewSet(),
table: netutil.NewIPMap(hc.last.Len()),
table: netutil.NewIPMap(lastLen),
}
}
@@ -286,9 +304,7 @@ func (hc *HostsContainer) newHostsParser() (hp *hostsParser) {
// never signs to stop walking and never returns any additional patterns.
//
// See man hosts(5).
func (hp *hostsParser) parseFile(
r io.Reader,
) (patterns []string, cont bool, err error) {
func (hp *hostsParser) parseFile(r io.Reader) (patterns []string, cont bool, err error) {
s := bufio.NewScanner(r)
for s.Scan() {
ip, hosts := hp.parseLine(s.Text())
@@ -339,62 +355,79 @@ func (hp *hostsParser) parseLine(line string) (ip net.IP, hosts []string) {
return ip, hosts
}
// Simple types of hosts in hosts database. Zero value isn't used to be able
// quizzaciously emulate nil with 0.
const (
_ = iota
hostAlias
hostMain
)
// Hosts is used to contain the main host and all it's aliases.
type Hosts struct {
// Aliases contains all the aliases for Main.
Aliases *stringutil.Set
// Main is the host itself.
Main string
}
// Equal returns true if h equals hh.
func (h *Hosts) Equal(hh *Hosts) (ok bool) {
if h == nil || hh == nil {
return h == hh
}
return h.Main == hh.Main && h.Aliases.Equal(hh.Aliases)
}
// add tries to add the ip-host pair. It returns:
//
// hostAlias if the host is not the first one added for the ip.
// hostMain if the host is the first one added for the ip.
// 0 if the ip-host pair has already been added.
// main host if the host is not the first one added for the ip.
// host itself if the host is the first one added for the ip.
// "" if the ip-host pair has already been added.
//
func (hp *hostsParser) add(ip net.IP, host string) (hostType int) {
func (hp *hostsParser) add(ip net.IP, host string) (mainHost string) {
v, ok := hp.table.Get(ip)
switch hosts, _ := v.(*stringutil.Set); {
case ok && hosts.Has(host):
return 0
case hosts == nil:
hosts = stringutil.NewSet(host)
hp.table.Set(ip, hosts)
switch h, _ := v.(*Hosts); {
case !ok:
// This is the first host for the ip.
hp.table.Set(ip, &Hosts{Main: host})
return hostMain
return host
case h.Main == host:
// This is a duplicate. Go on.
case h.Aliases == nil:
// This is the first alias.
h.Aliases = stringutil.NewSet(host)
return h.Main
case !h.Aliases.Has(host):
// This is a new alias.
h.Aliases.Add(host)
return h.Main
default:
hosts.Add(host)
return hostAlias
// This is a duplicate. Go on.
}
return ""
}
// addPair puts the pair of ip and host to the rules builder if needed. For
// each ip the first member of hosts will become the main one.
func (hp *hostsParser) addPairs(ip net.IP, hosts []string) {
// Put the rule in a processed format like:
//
// ip host1 host2 ...
//
hostsLine := strings.Join(append([]string{ip.String()}, hosts...), " ")
var mainHost string
for _, host := range hosts {
switch hp.add(ip, host) {
case 0:
switch mainHost := hp.add(ip, host); mainHost {
case "":
// This host is a duplicate.
continue
case hostMain:
mainHost = host
added, addedPtr := hp.writeMainHostRule(host, ip)
hp.translations[added], hp.translations[addedPtr] = hostsLine, hostsLine
case hostAlias:
case host:
// This host is main.
added, addedPtr := hp.writeMainRule(host, ip)
hp.rules = append(hp.rules, ipRules{
rule: added,
rulePtr: addedPtr,
ip: ip,
})
default:
// This host is an alias.
pair := fmt.Sprint(host, " ", mainHost)
if hp.cnameSet.Has(pair) {
continue
}
// Since the hostAlias couldn't be returned from add before the
// hostMain the mainHost shouldn't appear empty.
hp.writeAliasHostRule(host, mainHost)
hp.writeAliasRule(host, mainHost)
hp.cnameSet.Add(pair)
}
@@ -402,9 +435,9 @@ func (hp *hostsParser) addPairs(ip net.IP, hosts []string) {
}
}
// writeAliasHostRule writes the CNAME rule for the alias-host pair into
// internal builders.
func (hp *hostsParser) writeAliasHostRule(alias, host string) {
// writeAliasRule writes the CNAME rule for the alias-host pair into internal
// builders.
func (hp *hostsParser) writeAliasRule(alias, host string) {
const (
nl = "\n"
sc = ";"
@@ -417,9 +450,9 @@ func (hp *hostsParser) writeAliasHostRule(alias, host string) {
stringutil.WriteToBuilder(hp.rulesBuilder, rules.MaskPipe, alias, rwSuccess, host, nl)
}
// writeMainHostRule writes the actual rule for the qtype and the PTR for the
// writeMainRule writes the actual rule for the qtype and the PTR for the
// host-ip pair into internal builders.
func (hp *hostsParser) writeMainHostRule(host string, ip net.IP) (added, addedPtr string) {
func (hp *hostsParser) writeMainRule(host string, ip net.IP) (added, addedPtr string) {
arpa, err := netutil.IPToReversedAddr(ip)
if err != nil {
return
@@ -484,12 +517,15 @@ func (hp *hostsParser) equalSet(target *netutil.IPMap) (ok bool) {
return false
}
hp.table.Range(func(ip net.IP, val interface{}) (cont bool) {
v, hasIP := target.Get(ip)
hp.table.Range(func(ip net.IP, b interface{}) (cont bool) {
// ok is set to true if the target doesn't contain ip or if the
// appropriate hosts set isn't equal to the checked one, i.e. the maps
// have at least one discrepancy.
ok = !hasIP || !v.(*stringutil.Set).Equal(val.(*stringutil.Set))
// appropriate hosts set isn't equal to the checked one, i.e. the main
// hosts differ or the maps have at least one discrepancy.
if a, hasIP := target.Get(ip); !hasIP {
ok = true
} else if hosts, aok := a.(*Hosts); aok {
ok = !hosts.Equal(b.(*Hosts))
}
// Continue only if maps has no discrepancies.
return !ok
@@ -527,6 +563,35 @@ func (hp *hostsParser) newStrg(id int) (s *filterlist.RuleStorage, err error) {
}})
}
// translations generates the map to translate $dnsrewrite rules to
// hosts-syntax ones.
func (hp *hostsParser) translations() (trans map[string]string) {
l := len(hp.rules)
if l == 0 {
return nil
}
trans = make(map[string]string, l*2)
for _, r := range hp.rules {
v, ok := hp.table.Get(r.ip)
if !ok {
continue
}
var hosts *Hosts
hosts, ok = v.(*Hosts)
if !ok {
continue
}
strs := append([]string{r.ip.String(), hosts.Main}, hosts.Aliases.Values()...)
hostsLine := strings.Join(strs, " ")
trans[r.rule], trans[r.rulePtr] = hostsLine, hostsLine
}
return trans
}
// refresh gets the data from specified files and propagates the updates if
// needed.
//
@@ -540,7 +605,7 @@ func (hc *HostsContainer) refresh() (err error) {
}
if hp.equalSet(hc.last) {
log.Debug("%s: no updates detected", hostsContainerPref)
log.Debug("%s: no changes detected", hostsContainerPref)
return nil
}
@@ -553,7 +618,7 @@ func (hc *HostsContainer) refresh() (err error) {
return fmt.Errorf("initializing rules storage: %w", err)
}
hc.resetEng(rulesStrg, hp.translations)
hc.resetEng(rulesStrg, hp.translations())
return nil
}

View File

@@ -9,6 +9,7 @@ import (
"sync/atomic"
"testing"
"testing/fstest"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghtest"
"github.com/AdguardTeam/golibs/errors"
@@ -129,24 +130,13 @@ func TestNewHostsContainer(t *testing.T) {
})
}
func TestHostsContainer_Refresh(t *testing.T) {
knownIP := net.IP{127, 0, 0, 1}
func TestHostsContainer_refresh(t *testing.T) {
// TODO(e.burkov): Test the case with no actual updates.
const knownHost = "localhost"
const knownAlias = "hocallost"
ip := net.IP{127, 0, 0, 1}
ipStr := ip.String()
const dirname = "dir"
const filename1 = "file1"
const filename2 = "file2"
p1 := path.Join(dirname, filename1)
p2 := path.Join(dirname, filename2)
testFS := fstest.MapFS{
p1: &fstest.MapFile{
Data: []byte(strings.Join([]string{knownIP.String(), knownHost}, sp) + nl),
},
}
testFS := fstest.MapFS{"dir/file1": &fstest.MapFile{Data: []byte(ipStr + ` hostname` + nl)}}
// event is a convenient alias for an empty struct{} to emit test events.
type event = struct{}
@@ -157,119 +147,117 @@ func TestHostsContainer_Refresh(t *testing.T) {
w := &aghtest.FSWatcher{
OnEvents: func() (e <-chan event) { return eventsCh },
OnAdd: func(name string) (err error) {
assert.Equal(t, dirname, name)
assert.Equal(t, "dir", name)
return nil
},
OnClose: func() (err error) { panic("not implemented") },
}
hc, err := NewHostsContainer(0, testFS, w, dirname)
hc, err := NewHostsContainer(0, testFS, w, "dir")
require.NoError(t, err)
checkRefresh := func(t *testing.T, wantHosts *stringutil.Set) {
checkRefresh := func(t *testing.T, wantHosts Hosts) {
upd, ok := <-hc.Upd()
require.True(t, ok)
require.NotNil(t, upd)
assert.Equal(t, 1, upd.Len())
v, ok := upd.Get(knownIP)
v, ok := upd.Get(ip)
require.True(t, ok)
var hosts *stringutil.Set
hosts, ok = v.(*stringutil.Set)
var hosts *Hosts
hosts, ok = v.(*Hosts)
require.True(t, ok)
assert.True(t, hosts.Equal(wantHosts))
assert.Equal(t, wantHosts.Main, hosts.Main)
assert.True(t, hosts.Aliases.Equal(wantHosts.Aliases))
}
t.Run("initial_refresh", func(t *testing.T) {
checkRefresh(t, stringutil.NewSet(knownHost))
checkRefresh(t, Hosts{Main: "hostname"})
})
testFS[p2] = &fstest.MapFile{
Data: []byte(strings.Join([]string{knownIP.String(), knownAlias}, sp) + nl),
}
eventsCh <- event{}
t.Run("second_refresh", func(t *testing.T) {
checkRefresh(t, stringutil.NewSet(knownHost, knownAlias))
testFS["dir/file2"] = &fstest.MapFile{Data: []byte(ipStr + ` alias` + nl)}
eventsCh <- event{}
checkRefresh(t, Hosts{Main: "hostname", Aliases: stringutil.NewSet("alias")})
})
eventsCh <- event{}
t.Run("double_refresh", func(t *testing.T) {
// Make a change once.
testFS["dir/file1"] = &fstest.MapFile{Data: []byte(ipStr + ` alias` + nl)}
eventsCh <- event{}
t.Run("no_changes_refresh", func(t *testing.T) {
assert.Empty(t, hc.Upd())
// Require the changes are written.
require.Eventually(t, func() bool {
res, ok := hc.MatchRequest(urlfilter.DNSRequest{
Hostname: "hostname",
DNSType: dns.TypeA,
})
return !ok && res.DNSRewrites() == nil
}, 5*time.Second, time.Second/2)
// Make a change again.
testFS["dir/file2"] = &fstest.MapFile{Data: []byte(ipStr + ` hostname` + nl)}
eventsCh <- event{}
// Require the changes are written.
require.Eventually(t, func() bool {
res, ok := hc.MatchRequest(urlfilter.DNSRequest{
Hostname: "hostname",
DNSType: dns.TypeA,
})
return !ok && res.DNSRewrites() != nil
}, 5*time.Second, time.Second/2)
assert.Len(t, hc.Upd(), 1)
})
}
func TestHostsContainer_PathsToPatterns(t *testing.T) {
const (
dir0 = "dir"
dir1 = "dir_1"
fn1 = "file_1"
fn2 = "file_2"
fn3 = "file_3"
fn4 = "file_4"
)
fp1 := path.Join(dir0, fn1)
fp2 := path.Join(dir0, fn2)
fp3 := path.Join(dir0, dir1, fn3)
gsfs := fstest.MapFS{
fp1: &fstest.MapFile{Data: []byte{1}},
fp2: &fstest.MapFile{Data: []byte{2}},
fp3: &fstest.MapFile{Data: []byte{3}},
"dir_0/file_1": &fstest.MapFile{Data: []byte{1}},
"dir_0/file_2": &fstest.MapFile{Data: []byte{2}},
"dir_0/dir_1/file_3": &fstest.MapFile{Data: []byte{3}},
}
testCases := []struct {
name string
wantErr error
want []string
paths []string
name string
paths []string
want []string
}{{
name: "no_paths",
wantErr: nil,
want: nil,
paths: nil,
name: "no_paths",
paths: nil,
want: nil,
}, {
name: "single_file",
wantErr: nil,
want: []string{fp1},
paths: []string{fp1},
name: "single_file",
paths: []string{"dir_0/file_1"},
want: []string{"dir_0/file_1"},
}, {
name: "several_files",
wantErr: nil,
want: []string{fp1, fp2},
paths: []string{fp1, fp2},
name: "several_files",
paths: []string{"dir_0/file_1", "dir_0/file_2"},
want: []string{"dir_0/file_1", "dir_0/file_2"},
}, {
name: "whole_dir",
wantErr: nil,
want: []string{path.Join(dir0, "*")},
paths: []string{dir0},
name: "whole_dir",
paths: []string{"dir_0"},
want: []string{"dir_0/*"},
}, {
name: "file_and_dir",
wantErr: nil,
want: []string{fp1, path.Join(dir0, dir1, "*")},
paths: []string{fp1, path.Join(dir0, dir1)},
name: "file_and_dir",
paths: []string{"dir_0/file_1", "dir_0/dir_1"},
want: []string{"dir_0/file_1", "dir_0/dir_1/*"},
}, {
name: "non-existing",
wantErr: nil,
want: nil,
paths: []string{path.Join(dir0, "file_3")},
name: "non-existing",
paths: []string{path.Join("dir_0", "file_3")},
want: nil,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
patterns, err := pathsToPatterns(gsfs, tc.paths)
if tc.wantErr != nil {
assert.ErrorIs(t, err, tc.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tc.want, patterns)
@@ -290,111 +278,158 @@ func TestHostsContainer_PathsToPatterns(t *testing.T) {
})
}
func TestHostsContainer_Translate(t *testing.T) {
testdata := os.DirFS("./testdata")
stubWatcher := aghtest.FSWatcher{
OnEvents: func() (e <-chan struct{}) { return nil },
OnAdd: func(name string) (err error) { return nil },
OnClose: func() (err error) { panic("not implemented") },
}
hc, err := NewHostsContainer(0, testdata, &stubWatcher, "etc_hosts")
require.NoError(t, err)
testCases := []struct {
name string
rule string
wantTrans []string
}{{
name: "simplehost",
rule: "|simplehost^$dnsrewrite=NOERROR;A;1.0.0.1",
wantTrans: []string{"1.0.0.1", "simplehost"},
}, {
name: "hello",
rule: "|hello^$dnsrewrite=NOERROR;A;1.0.0.0",
wantTrans: []string{"1.0.0.0", "hello", "hello.world", "hello.world.again"},
}, {
name: "simplehost_v6",
rule: "|simplehost^$dnsrewrite=NOERROR;AAAA;::1",
wantTrans: []string{"::1", "simplehost"},
}, {
name: "hello_v6",
rule: "|hello^$dnsrewrite=NOERROR;AAAA;::",
wantTrans: []string{"::", "hello", "hello.world", "hello.world.again"},
}, {
name: "simplehost_ptr",
rule: "|1.0.0.1.in-addr.arpa^$dnsrewrite=NOERROR;PTR;simplehost.",
wantTrans: []string{"1.0.0.1", "simplehost"},
}, {
name: "hello_ptr",
rule: "|0.0.0.1.in-addr.arpa^$dnsrewrite=NOERROR;PTR;hello.",
wantTrans: []string{"1.0.0.0", "hello", "hello.world", "hello.world.again"},
}, {
name: "simplehost_ptr_v6",
rule: "|1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" +
"^$dnsrewrite=NOERROR;PTR;simplehost.",
wantTrans: []string{"::1", "simplehost"},
}, {
name: "hello_ptr_v6",
rule: "|0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" +
"^$dnsrewrite=NOERROR;PTR;hello.",
wantTrans: []string{"::", "hello", "hello.world", "hello.world.again"},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
want := stringutil.NewSet(tc.wantTrans...)
got := stringutil.NewSet(strings.Fields(hc.Translate(tc.rule))...)
assert.True(t, want.Equal(got))
})
}
}
func TestHostsContainer(t *testing.T) {
const listID = 1234
testdata := os.DirFS("./testdata")
nRewrites := func(t *testing.T, res *urlfilter.DNSResult, n int) (rws []*rules.DNSRewrite) {
t.Helper()
rewrites := res.DNSRewrites()
assert.Len(t, rewrites, n)
for _, rewrite := range rewrites {
require.Equal(t, listID, rewrite.FilterListID)
rw := rewrite.DNSRewrite
require.NotNil(t, rw)
rws = append(rws, rw)
}
return rws
}
testCases := []struct {
testTail func(t *testing.T, res *urlfilter.DNSResult)
name string
req urlfilter.DNSRequest
want []*rules.DNSRewrite
name string
req urlfilter.DNSRequest
}{{
want: []*rules.DNSRewrite{{
RCode: dns.RcodeSuccess,
Value: net.IPv4(1, 0, 0, 1),
RRType: dns.TypeA,
}, {
RCode: dns.RcodeSuccess,
Value: net.IP(append((&[15]byte{})[:], byte(1))),
RRType: dns.TypeAAAA,
}},
name: "simple",
req: urlfilter.DNSRequest{
Hostname: "simplehost",
DNSType: dns.TypeA,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
rws := nRewrites(t, res, 2)
v, ok := rws[0].Value.(net.IP)
require.True(t, ok)
assert.True(t, net.IP{1, 0, 0, 1}.Equal(v))
v, ok = rws[1].Value.(net.IP)
require.True(t, ok)
// It's ::1.
assert.True(t, net.IP(append((&[15]byte{})[:], byte(1))).Equal(v))
},
}, {
want: []*rules.DNSRewrite{{
RCode: dns.RcodeSuccess,
NewCNAME: "hello",
}},
name: "hello_alias",
req: urlfilter.DNSRequest{
Hostname: "hello.world",
DNSType: dns.TypeA,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
assert.Equal(t, "hello", nRewrites(t, res, 1)[0].NewCNAME)
}, {
want: []*rules.DNSRewrite{{
RCode: dns.RcodeSuccess,
NewCNAME: "hello",
}},
name: "other_line_alias",
req: urlfilter.DNSRequest{
Hostname: "hello.world.again",
DNSType: dns.TypeA,
},
}, {
want: []*rules.DNSRewrite{},
name: "hello_subdomain",
req: urlfilter.DNSRequest{
Hostname: "say.hello",
DNSType: dns.TypeA,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
assert.Empty(t, res.DNSRewrites())
},
}, {
want: []*rules.DNSRewrite{},
name: "hello_alias_subdomain",
req: urlfilter.DNSRequest{
Hostname: "say.hello.world",
DNSType: dns.TypeA,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
assert.Empty(t, res.DNSRewrites())
},
}, {
want: []*rules.DNSRewrite{{
RCode: dns.RcodeSuccess,
NewCNAME: "a.whole",
}},
name: "lots_of_aliases",
req: urlfilter.DNSRequest{
Hostname: "for.testing",
DNSType: dns.TypeA,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
assert.Equal(t, "a.whole", nRewrites(t, res, 1)[0].NewCNAME)
},
}, {
want: []*rules.DNSRewrite{{
RCode: dns.RcodeSuccess,
RRType: dns.TypePTR,
Value: "simplehost.",
}},
name: "reverse",
req: urlfilter.DNSRequest{
Hostname: "1.0.0.1.in-addr.arpa",
DNSType: dns.TypePTR,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
rws := nRewrites(t, res, 1)
assert.Equal(t, dns.TypePTR, rws[0].RRType)
assert.Equal(t, "simplehost.", rws[0].Value)
},
}, {
want: []*rules.DNSRewrite{},
name: "non-existing",
req: urlfilter.DNSRequest{
Hostname: "nonexisting",
DNSType: dns.TypeA,
},
testTail: func(t *testing.T, res *urlfilter.DNSResult) {
require.NotNil(t, res)
assert.Nil(t, res.DNSRewrites())
}, {
want: nil,
name: "bad_type",
req: urlfilter.DNSRequest{
Hostname: "1.0.0.1.in-addr.arpa",
DNSType: dns.TypeSRV,
},
}}
@@ -411,20 +446,33 @@ func TestHostsContainer(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
res, ok := hc.MatchRequest(tc.req)
require.False(t, ok)
if tc.want == nil {
assert.Nil(t, res)
return
}
require.NotNil(t, res)
tc.testTail(t, res)
rewrites := res.DNSRewrites()
require.Len(t, rewrites, len(tc.want))
for i, rewrite := range rewrites {
require.Equal(t, listID, rewrite.FilterListID)
rw := rewrite.DNSRewrite
require.NotNil(t, rw)
assert.Equal(t, tc.want[i], rw)
}
})
}
}
func TestUniqueRules_ParseLine(t *testing.T) {
const (
hostname = "localhost"
alias = "hocallost"
)
knownIP := net.IP{127, 0, 0, 1}
ip := net.IP{127, 0, 0, 1}
ipStr := ip.String()
testCases := []struct {
name string
@@ -433,39 +481,39 @@ func TestUniqueRules_ParseLine(t *testing.T) {
wantHosts []string
}{{
name: "simple",
line: strings.Join([]string{knownIP.String(), hostname}, sp),
wantIP: knownIP,
wantHosts: []string{"localhost"},
line: ipStr + ` hostname`,
wantIP: ip,
wantHosts: []string{"hostname"},
}, {
name: "aliases",
line: strings.Join([]string{knownIP.String(), hostname, alias}, sp),
wantIP: knownIP,
wantHosts: []string{"localhost", "hocallost"},
line: ipStr + ` hostname alias`,
wantIP: ip,
wantHosts: []string{"hostname", "alias"},
}, {
name: "invalid_line",
line: knownIP.String(),
line: ipStr,
wantIP: nil,
wantHosts: nil,
}, {
name: "invalid_line_hostname",
line: strings.Join([]string{knownIP.String(), "#" + hostname}, sp),
wantIP: knownIP,
line: ipStr + ` # hostname`,
wantIP: ip,
wantHosts: nil,
}, {
name: "commented_aliases",
line: strings.Join([]string{knownIP.String(), hostname, "#" + alias}, sp),
wantIP: knownIP,
wantHosts: []string{"localhost"},
line: ipStr + ` hostname # alias`,
wantIP: ip,
wantHosts: []string{"hostname"},
}, {
name: "whole_comment",
line: strings.Join([]string{"#", knownIP.String(), hostname}, sp),
line: `# ` + ipStr + ` hostname`,
wantIP: nil,
wantHosts: nil,
}, {
name: "partial_comment",
line: strings.Join([]string{knownIP.String(), hostname[:4] + "#" + hostname[4:]}, sp),
wantIP: knownIP,
wantHosts: []string{hostname[:4]},
line: ipStr + ` host#name`,
wantIP: ip,
wantHosts: []string{"host"},
}, {
name: "empty",
line: ``,
@@ -476,8 +524,8 @@ func TestUniqueRules_ParseLine(t *testing.T) {
for _, tc := range testCases {
hp := hostsParser{}
t.Run(tc.name, func(t *testing.T) {
ip, hosts := hp.parseLine(tc.line)
assert.True(t, tc.wantIP.Equal(ip))
got, hosts := hp.parseLine(tc.line)
assert.True(t, tc.wantIP.Equal(got))
assert.Equal(t, tc.wantHosts, hosts)
})
}

View File

@@ -25,6 +25,13 @@ type NetIface interface {
// IfaceIPAddrs returns the interface's IP addresses.
func IfaceIPAddrs(iface NetIface, ipv IPVersion) (ips []net.IP, err error) {
switch ipv {
case IPVersion4, IPVersion6:
// Go on.
default:
return nil, fmt.Errorf("invalid ip version %d", ipv)
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
@@ -41,20 +48,16 @@ func IfaceIPAddrs(iface NetIface, ipv IPVersion) (ips []net.IP, err error) {
continue
}
// Assume that net.(*Interface).Addrs can only return valid IPv4
// and IPv6 addresses. Thus, if it isn't an IPv4 address, it
// must be an IPv6 one.
switch ipv {
case IPVersion4:
if ip4 := ip.To4(); ip4 != nil {
// Assume that net.(*Interface).Addrs can only return valid IPv4 and
// IPv6 addresses. Thus, if it isn't an IPv4 address, it must be an
// IPv6 one.
ip4 := ip.To4()
if ipv == IPVersion4 {
if ip4 != nil {
ips = append(ips, ip4)
}
case IPVersion6:
if ip6 := ip.To4(); ip6 == nil {
ips = append(ips, ip)
}
default:
return nil, fmt.Errorf("invalid ip version %d", ipv)
} else if ip4 == nil {
ips = append(ips, ip)
}
}
@@ -96,16 +99,16 @@ func IfaceDNSIPAddrs(
switch len(addrs) {
case 0:
// Don't return errors in case the users want to try and enable
// the DHCP server later.
// Don't return errors in case the users want to try and enable the DHCP
// server later.
t := time.Duration(n) * backoff
log.Error("dhcpv%d: no ip for iface after %d attempts and %s", ipv, n, t)
return nil, nil
case 1:
// Some Android devices use 8.8.8.8 if there is not a secondary
// DNS server. Fix that by setting the secondary DNS address to
// the same address.
// Some Android devices use 8.8.8.8 if there is not a secondary DNS
// server. Fix that by setting the secondary DNS address to the same
// address.
//
// See https://github.com/AdguardTeam/AdGuardHome/issues/1708.
log.Debug("dhcpv%d: setting secondary dns ip to itself", ipv)

View File

@@ -5,13 +5,15 @@ import (
"testing"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeIface is a stub implementation of aghnet.NetIface to simplify testing.
type fakeIface struct {
addrs []net.Addr
err error
addrs []net.Addr
}
// Addrs implements the NetIface interface for *fakeIface.
@@ -33,61 +35,86 @@ func TestIfaceIPAddrs(t *testing.T) {
addr6 := &net.IPNet{IP: ip6}
testCases := []struct {
name string
iface NetIface
ipv IPVersion
want []net.IP
wantErr error
iface NetIface
name string
wantErrMsg string
want []net.IP
ipv IPVersion
}{{
name: "ipv4_success",
iface: &fakeIface{addrs: []net.Addr{addr4}, err: nil},
ipv: IPVersion4,
want: []net.IP{ip4},
wantErr: nil,
iface: &fakeIface{addrs: []net.Addr{addr4}, err: nil},
name: "ipv4_success",
wantErrMsg: "",
want: []net.IP{ip4},
ipv: IPVersion4,
}, {
name: "ipv4_success_with_ipv6",
iface: &fakeIface{addrs: []net.Addr{addr6, addr4}, err: nil},
ipv: IPVersion4,
want: []net.IP{ip4},
wantErr: nil,
iface: &fakeIface{addrs: []net.Addr{addr6, addr4}, err: nil},
name: "ipv4_success_with_ipv6",
wantErrMsg: "",
want: []net.IP{ip4},
ipv: IPVersion4,
}, {
name: "ipv4_error",
iface: &fakeIface{addrs: []net.Addr{addr4}, err: errTest},
ipv: IPVersion4,
want: nil,
wantErr: errTest,
iface: &fakeIface{addrs: []net.Addr{addr4}, err: errTest},
name: "ipv4_error",
wantErrMsg: errTest.Error(),
want: nil,
ipv: IPVersion4,
}, {
name: "ipv6_success",
iface: &fakeIface{addrs: []net.Addr{addr6}, err: nil},
ipv: IPVersion6,
want: []net.IP{ip6},
wantErr: nil,
iface: &fakeIface{addrs: []net.Addr{addr6}, err: nil},
name: "ipv6_success",
wantErrMsg: "",
want: []net.IP{ip6},
ipv: IPVersion6,
}, {
name: "ipv6_success_with_ipv4",
iface: &fakeIface{addrs: []net.Addr{addr6, addr4}, err: nil},
ipv: IPVersion6,
want: []net.IP{ip6},
wantErr: nil,
iface: &fakeIface{addrs: []net.Addr{addr6, addr4}, err: nil},
name: "ipv6_success_with_ipv4",
wantErrMsg: "",
want: []net.IP{ip6},
ipv: IPVersion6,
}, {
name: "ipv6_error",
iface: &fakeIface{addrs: []net.Addr{addr6}, err: errTest},
ipv: IPVersion6,
want: nil,
wantErr: errTest,
iface: &fakeIface{addrs: []net.Addr{addr6}, err: errTest},
name: "ipv6_error",
wantErrMsg: errTest.Error(),
want: nil,
ipv: IPVersion6,
}, {
iface: &fakeIface{addrs: nil, err: nil},
name: "bad_proto",
wantErrMsg: "invalid ip version 10",
want: nil,
ipv: IPVersion6 + IPVersion4,
}, {
iface: &fakeIface{addrs: []net.Addr{&net.IPAddr{IP: ip4}}, err: nil},
name: "ipaddr_v4",
wantErrMsg: "",
want: []net.IP{ip4},
ipv: IPVersion4,
}, {
iface: &fakeIface{addrs: []net.Addr{&net.IPAddr{IP: ip6, Zone: ""}}, err: nil},
name: "ipaddr_v6",
wantErrMsg: "",
want: []net.IP{ip6},
ipv: IPVersion6,
}, {
iface: &fakeIface{addrs: []net.Addr{&net.UnixAddr{}}, err: nil},
name: "non-ipv4",
wantErrMsg: "",
want: nil,
ipv: IPVersion4,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got, gotErr := IfaceIPAddrs(tc.iface, tc.ipv)
require.True(t, errors.Is(gotErr, tc.wantErr))
got, err := IfaceIPAddrs(tc.iface, tc.ipv)
testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
assert.Equal(t, tc.want, got)
})
}
}
type waitingFakeIface struct {
addrs []net.Addr
err error
addrs []net.Addr
n int
}
@@ -116,11 +143,11 @@ func TestIfaceDNSIPAddrs(t *testing.T) {
addr6 := &net.IPNet{IP: ip6}
testCases := []struct {
name string
iface NetIface
ipv IPVersion
want []net.IP
wantErr error
name string
want []net.IP
ipv IPVersion
}{{
name: "ipv4_success",
iface: &fakeIface{addrs: []net.Addr{addr4}, err: nil},
@@ -169,12 +196,25 @@ func TestIfaceDNSIPAddrs(t *testing.T) {
ipv: IPVersion6,
want: []net.IP{ip6, ip6},
wantErr: nil,
}, {
name: "empty",
iface: &fakeIface{addrs: nil, err: nil},
ipv: IPVersion4,
want: nil,
wantErr: nil,
}, {
name: "many",
iface: &fakeIface{addrs: []net.Addr{addr4, addr4}},
ipv: IPVersion4,
want: []net.IP{ip4, ip4},
wantErr: nil,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got, gotErr := IfaceDNSIPAddrs(tc.iface, tc.ipv, 2, 0)
require.True(t, errors.Is(gotErr, tc.wantErr))
got, err := IfaceDNSIPAddrs(tc.iface, tc.ipv, 2, 0)
require.ErrorIs(t, err, tc.wantErr)
assert.Equal(t, tc.want, got)
})
}

View File

@@ -0,0 +1,44 @@
package aghnet
import (
"net"
"testing"
"github.com/AdguardTeam/golibs/netutil"
"github.com/stretchr/testify/assert"
)
func TestIPMut(t *testing.T) {
testIPs := []net.IP{{
127, 0, 0, 1,
}, {
192, 168, 0, 1,
}, {
8, 8, 8, 8,
}}
t.Run("nil_no_mut", func(t *testing.T) {
ipmut := NewIPMut(nil)
ips := netutil.CloneIPs(testIPs)
for i := range ips {
ipmut.Load()(ips[i])
assert.True(t, ips[i].Equal(testIPs[i]))
}
})
t.Run("not_nil_mut", func(t *testing.T) {
ipmut := NewIPMut(func(ip net.IP) {
for i := range ip {
ip[i] = 0
}
})
want := netutil.IPv4Zero()
ips := netutil.CloneIPs(testIPs)
for i := range ips {
ipmut.Load()(ips[i])
assert.True(t, ips[i].Equal(want))
}
})
}

View File

@@ -42,8 +42,7 @@ func GatewayIP(ifaceName string) net.IP {
fields := strings.Fields(string(d))
// The meaningful "ip route" command output should contain the word
// "default" at first field and default gateway IP address at third
// field.
// "default" at first field and default gateway IP address at third field.
if len(fields) < 3 || fields[0] != "default" {
return nil
}
@@ -218,28 +217,6 @@ func IsAddrInUse(err error) (ok bool) {
return isAddrInUse(sysErr)
}
// SplitHost is a wrapper for net.SplitHostPort for the cases when the hostport
// does not necessarily contain a port.
func SplitHost(hostport string) (host string, err error) {
host, _, err = net.SplitHostPort(hostport)
if err != nil {
// Check for the missing port error. If it is that error, just
// use the host as is.
//
// See the source code for net.SplitHostPort.
const missingPort = "missing port in address"
addrErr := &net.AddrError{}
if !errors.As(err, &addrErr) || addrErr.Err != missingPort {
return "", err
}
host = hostport
}
return host, nil
}
// CollectAllIfacesAddrs returns the slice of all network interfaces IP
// addresses without port number.
func CollectAllIfacesAddrs() (addrs []string, err error) {

View File

@@ -15,12 +15,20 @@ func TestMain(m *testing.M) {
aghtest.DiscardLogOutput(m)
}
func TestGetValidNetInterfacesForWeb(t *testing.T) {
func TestGetInterfaceByIP(t *testing.T) {
ifaces, err := GetValidNetInterfacesForWeb()
require.NoErrorf(t, err, "cannot get net interfaces: %s", err)
require.NotEmpty(t, ifaces, "no net interfaces found")
require.NoError(t, err)
require.NotEmpty(t, ifaces)
for _, iface := range ifaces {
require.NotEmptyf(t, iface.Addresses, "no addresses found for %s", iface.Name)
t.Run(iface.Name, func(t *testing.T) {
require.NotEmpty(t, iface.Addresses)
for _, ip := range iface.Addresses {
ifaceName := GetInterfaceByIP(ip)
require.Equal(t, iface.Name, ifaceName)
}
})
}
}
@@ -73,18 +81,47 @@ func TestBroadcastFromIPNet(t *testing.T) {
}
func TestCheckPort(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:")
require.NoError(t, err)
testutil.CleanupAndRequireSuccess(t, l.Close)
t.Run("tcp_bound", func(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:")
require.NoError(t, err)
testutil.CleanupAndRequireSuccess(t, l.Close)
ipp := netutil.IPPortFromAddr(l.Addr())
require.NotNil(t, ipp)
require.NotNil(t, ipp.IP)
require.NotZero(t, ipp.Port)
ipp := netutil.IPPortFromAddr(l.Addr())
require.NotNil(t, ipp)
require.NotNil(t, ipp.IP)
require.NotZero(t, ipp.Port)
err = CheckPort("tcp", ipp.IP, ipp.Port)
target := &net.OpError{}
require.ErrorAs(t, err, &target)
err = CheckPort("tcp", ipp.IP, ipp.Port)
target := &net.OpError{}
require.ErrorAs(t, err, &target)
assert.Equal(t, "listen", target.Op)
assert.Equal(t, "listen", target.Op)
})
t.Run("udp_bound", func(t *testing.T) {
conn, err := net.ListenPacket("udp", "127.0.0.1:")
require.NoError(t, err)
testutil.CleanupAndRequireSuccess(t, conn.Close)
ipp := netutil.IPPortFromAddr(conn.LocalAddr())
require.NotNil(t, ipp)
require.NotNil(t, ipp.IP)
require.NotZero(t, ipp.Port)
err = CheckPort("udp", ipp.IP, ipp.Port)
target := &net.OpError{}
require.ErrorAs(t, err, &target)
assert.Equal(t, "listen", target.Op)
})
t.Run("bad_network", func(t *testing.T) {
err := CheckPort("bad_network", nil, 0)
assert.NoError(t, err)
})
t.Run("can_bind", func(t *testing.T) {
err := CheckPort("udp", net.IP{0, 0, 0, 0}, 0)
assert.NoError(t, err)
})
}

View File

@@ -12,9 +12,19 @@
1.0.0.3 *
1.0.0.4 *.com
# See https://github.com/AdguardTeam/AdGuardHome/issues/4079.
1.0.0.0 hello.world.again
# Duplicates of a main host and an alias.
1.0.0.1 simplehost
1.0.0.0 hello.world
# Same for IPv6.
::1 simplehost
:: hello hello.world
::2 a.whole lot.of aliases for.testing
::3 *
::4 *.com
:: hello.world.again
::1 simplehost
:: hello.world

View File

@@ -7,7 +7,7 @@ import (
"net/http"
"strings"
"github.com/AdguardTeam/AdGuardHome/internal/aghalgo"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
@@ -214,7 +214,7 @@ func validateAccessSet(list *accessListJSON) (err error) {
}
merged := allowed.Merge(disallowed)
err = merged.Validate(aghalgo.StringIsBefore)
err = merged.Validate(aghalg.StringIsBefore)
if err != nil {
return fmt.Errorf("items in allowed and disallowed clients intersect: %w", err)
}
@@ -223,13 +223,13 @@ func validateAccessSet(list *accessListJSON) (err error) {
}
// validateStrUniq returns an informative error if clients are not unique.
func validateStrUniq(clients []string) (uv aghalgo.UniquenessValidator, err error) {
uv = make(aghalgo.UniquenessValidator, len(clients))
func validateStrUniq(clients []string) (uc aghalg.UniqChecker, err error) {
uc = make(aghalg.UniqChecker, len(clients))
for _, c := range clients {
uv.Add(c)
uc.Add(c)
}
return uv, uv.Validate(aghalgo.StringIsBefore)
return uc, uc.Validate(aghalg.StringIsBefore)
}
func (s *Server) handleAccessSet(w http.ResponseWriter, r *http.Request) {

View File

@@ -352,9 +352,22 @@ func (s *Server) processRestrictLocal(ctx *dnsContext) (rc resultCode) {
ip, err := netutil.IPFromReversedAddr(q.Name)
if err != nil {
log.Debug("dns: reversed addr: %s", err)
log.Debug("dns: parsing reversed addr: %s", err)
return resultCodeError
// DNS-Based Service Discovery uses PTR records having not an ARPA
// format of the domain name in question. Those shouldn't be
// invalidated. See http://www.dns-sd.org/ServerStaticSetup.html and
// RFC 2782.
name := strings.TrimSuffix(q.Name, ".")
if err = netutil.ValidateSRVDomainName(name); err != nil {
log.Debug("dns: validating service domain: %s", err)
return resultCodeError
}
log.Debug("dns: request is for a service domain")
return resultCodeSuccess
}
// Restrict an access to local addresses for external clients. We also

View File

@@ -5,7 +5,6 @@ import (
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
@@ -192,22 +191,23 @@ func (req *dnsConfig) checkCacheTTL() bool {
func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) {
req := dnsConfig{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&req); err != nil {
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json Encode: %s", err)
return
}
if req.Upstreams != nil {
if err := ValidateUpstreams(*req.Upstreams); err != nil {
if err = ValidateUpstreams(*req.Upstreams); err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "wrong upstreams specification: %s", err)
return
}
}
if errBoot, err := req.checkBootstrap(); err != nil {
var errBoot string
if errBoot, err = req.checkBootstrap(); err != nil {
aghhttp.Error(
r,
w,
@@ -220,19 +220,16 @@ func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) {
return
}
if !req.checkBlockingMode() {
switch {
case !req.checkBlockingMode():
aghhttp.Error(r, w, http.StatusBadRequest, "blocking_mode: incorrect value")
return
}
if !req.checkUpstreamsMode() {
case !req.checkUpstreamsMode():
aghhttp.Error(r, w, http.StatusBadRequest, "upstream_mode: incorrect value")
return
}
if !req.checkCacheTTL() {
case !req.checkCacheTTL():
aghhttp.Error(
r,
w,
@@ -241,13 +238,15 @@ func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) {
)
return
default:
// Go on.
}
restart := s.setConfig(req)
s.conf.ConfigModified()
if restart {
if err := s.Reconfigure(nil); err != nil {
if err = s.Reconfigure(nil); err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "%s", err)
}
}
@@ -387,14 +386,14 @@ func ValidateUpstreams(upstreams []string) (err error) {
var defaultUpstreamFound bool
for _, u := range upstreams {
var ok bool
ok, err = validateUpstream(u)
var useDefault bool
useDefault, err = validateUpstream(u)
if err != nil {
return err
}
if !defaultUpstreamFound {
defaultUpstreamFound = ok
defaultUpstreamFound = useDefault
}
}
@@ -407,50 +406,62 @@ func ValidateUpstreams(upstreams []string) (err error) {
var protocols = []string{"tls://", "https://", "tcp://", "sdns://", "quic://"}
func validateUpstream(u string) (bool, error) {
func validateUpstream(u string) (useDefault bool, err error) {
// Check if the user tries to specify upstream for domain.
u, useDefault, err := separateUpstream(u)
var isDomainSpec bool
u, isDomainSpec, err = separateUpstream(u)
if err != nil {
return useDefault, err
return !isDomainSpec, err
}
// The special server address '#' means "use the default servers"
if u == "#" && !useDefault {
// The special server address '#' means that default server must be used.
if useDefault = !isDomainSpec; u == "#" && isDomainSpec {
return useDefault, nil
}
// Check if the upstream has a valid protocol prefix
// Check if the upstream has a valid protocol prefix.
//
// TODO(e.burkov): Validate the domain name.
for _, proto := range protocols {
if strings.HasPrefix(u, proto) {
return useDefault, nil
}
}
// Return error if the upstream contains '://' without any valid protocol
if strings.Contains(u, "://") {
return useDefault, fmt.Errorf("wrong protocol")
return useDefault, errors.Error("wrong protocol")
}
// Check if upstream is valid plain DNS
return useDefault, checkPlainDNS(u)
// Check if upstream is either an IP or IP with port.
if net.ParseIP(u) != nil {
return useDefault, nil
} else if _, err = netutil.ParseIPPort(u); err != nil {
return useDefault, err
}
return useDefault, nil
}
// separateUpstream returns the upstream without the specified domains.
// useDefault is true when a default upstream must be used.
func separateUpstream(upstreamStr string) (upstream string, useDefault bool, err error) {
defer func() { err = errors.Annotate(err, "bad upstream for domain spec %q: %w", upstreamStr) }()
// isDomainSpec is true when the upstream is domains-specific.
func separateUpstream(upstreamStr string) (upstream string, isDomainSpec bool, err error) {
if !strings.HasPrefix(upstreamStr, "[/") {
return upstreamStr, true, nil
return upstreamStr, false, nil
}
defer func() { err = errors.Annotate(err, "bad upstream for domain %q: %w", upstreamStr) }()
parts := strings.Split(upstreamStr[2:], "/]")
if len(parts) != 2 {
return "", false, errors.Error("duplicated separator")
switch len(parts) {
case 2:
// Go on.
case 1:
return "", false, errors.Error("missing separator")
default:
return "", true, errors.Error("duplicated separator")
}
domains := parts[0]
upstream = parts[1]
var domains string
domains, upstream = parts[0], parts[1]
for i, host := range strings.Split(domains, "/") {
if host == "" {
continue
@@ -458,36 +469,11 @@ func separateUpstream(upstreamStr string) (upstream string, useDefault bool, err
err = netutil.ValidateDomainName(host)
if err != nil {
return "", false, fmt.Errorf("domain at index %d: %w", i, err)
return "", true, fmt.Errorf("domain at index %d: %w", i, err)
}
}
return upstream, false, nil
}
// checkPlainDNS checks if host is plain DNS
func checkPlainDNS(upstream string) error {
// Check if host is ip without port
if net.ParseIP(upstream) != nil {
return nil
}
// Check if host is ip with port
ip, port, err := net.SplitHostPort(upstream)
if err != nil {
return err
}
if net.ParseIP(ip) == nil {
return fmt.Errorf("%s is not a valid IP", ip)
}
_, err = strconv.ParseInt(port, 0, 64)
if err != nil {
return fmt.Errorf("%s is not a valid port: %w", port, err)
}
return nil
return upstream, true, nil
}
// excFunc is a signature of function to check if upstream exchanges correctly.
@@ -515,12 +501,8 @@ func checkDNSUpstreamExc(u upstream.Upstream) (err error) {
if len(reply.Answer) != 1 {
return fmt.Errorf("wrong response")
}
if t, ok := reply.Answer[0].(*dns.A); ok {
if !net.IPv4(8, 8, 8, 8).Equal(t.A) {
return fmt.Errorf("wrong response")
}
} else if a, ok := reply.Answer[0].(*dns.A); !ok || !a.A.Equal(net.IP{8, 8, 8, 8}) {
return fmt.Errorf("wrong response")
}
return nil
@@ -555,7 +537,7 @@ func checkDNS(input string, bootstrap []string, timeout time.Duration, ef excFun
// Separate upstream from domains list.
var useDefault bool
if input, useDefault, err = separateUpstream(input); err != nil {
if useDefault, err = validateUpstream(input); err != nil {
return fmt.Errorf("wrong upstream format: %w", err)
}
@@ -564,7 +546,7 @@ func checkDNS(input string, bootstrap []string, timeout time.Duration, ef excFun
return nil
}
if _, err = validateUpstream(input); err != nil {
if input, _, err = separateUpstream(input); err != nil {
return fmt.Errorf("wrong upstream format: %w", err)
}
@@ -572,7 +554,8 @@ func checkDNS(input string, bootstrap []string, timeout time.Duration, ef excFun
bootstrap = defaultBootstrap
}
log.Debug("checking if dns server %q works...", input)
log.Debug("checking if upstream %s works", input)
var u upstream.Upstream
u, err = upstream.AddressToUpstream(input, &upstream.Options{
Bootstrap: bootstrap,
@@ -586,7 +569,7 @@ func checkDNS(input string, bootstrap []string, timeout time.Duration, ef excFun
return fmt.Errorf("upstream %q fails to exchange: %w", input, err)
}
log.Debug("dns %s works OK", input)
log.Debug("upstream %s is ok", input)
return nil
}
@@ -620,9 +603,9 @@ func (s *Server) handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
err = checkDNS(host, bootstraps, timeout, checkPrivateUpstreamExc)
if err != nil {
log.Info("%v", err)
// TODO(e.burkov): If passed upstream have already
// written an error above, we rewriting the error for
// it. These cases should be handled properly instead.
// TODO(e.burkov): If passed upstream have already written an error
// above, we rewriting the error for it. These cases should be
// handled properly instead.
result[host] = err.Error()
continue

View File

@@ -184,7 +184,7 @@ func TestDNSForwardHTTP_handleSetConfig(t *testing.T) {
wantSet: "",
}, {
name: "upstream_dns_bad",
wantSet: `wrong upstreams specification: address !!!: ` +
wantSet: `wrong upstreams specification: bad ipport address "!!!": address !!!: ` +
`missing port in address`,
}, {
name: "bootstraps_bad",
@@ -235,107 +235,117 @@ func TestDNSForwardHTTP_handleSetConfig(t *testing.T) {
}
func TestIsCommentOrEmpty(t *testing.T) {
assert.True(t, IsCommentOrEmpty(""))
assert.True(t, IsCommentOrEmpty("# comment"))
assert.False(t, IsCommentOrEmpty("1.2.3.4"))
for _, tc := range []struct {
want assert.BoolAssertionFunc
str string
}{{
want: assert.True,
str: "",
}, {
want: assert.True,
str: "# comment",
}, {
want: assert.False,
str: "1.2.3.4",
}} {
tc.want(t, IsCommentOrEmpty(tc.str))
}
}
// TODO(a.garipov): Rewrite to check the actual error messages.
func TestValidateUpstream(t *testing.T) {
testCases := []struct {
wantDef assert.BoolAssertionFunc
name string
upstream string
valid bool
wantDef bool
wantErr string
}{{
wantDef: assert.True,
name: "invalid",
upstream: "1.2.3.4.5",
valid: false,
wantDef: false,
wantErr: `bad ipport address "1.2.3.4.5": address 1.2.3.4.5: missing port in address`,
}, {
wantDef: assert.True,
name: "invalid",
upstream: "123.3.7m",
valid: false,
wantDef: false,
wantErr: `bad ipport address "123.3.7m": address 123.3.7m: missing port in address`,
}, {
wantDef: assert.True,
name: "invalid",
upstream: "htttps://google.com/dns-query",
valid: false,
wantDef: false,
wantErr: `wrong protocol`,
}, {
wantDef: assert.True,
name: "invalid",
upstream: "[/host.com]tls://dns.adguard.com",
valid: false,
wantDef: false,
wantErr: `bad upstream for domain "[/host.com]tls://dns.adguard.com": missing separator`,
}, {
wantDef: assert.True,
name: "invalid",
upstream: "[host.ru]#",
valid: false,
wantDef: false,
wantErr: `bad ipport address "[host.ru]#": address [host.ru]#: missing port in address`,
}, {
wantDef: assert.True,
name: "valid_default",
upstream: "1.1.1.1",
valid: true,
wantDef: true,
wantErr: ``,
}, {
wantDef: assert.True,
name: "valid_default",
upstream: "tls://1.1.1.1",
valid: true,
wantDef: true,
wantErr: ``,
}, {
wantDef: assert.True,
name: "valid_default",
upstream: "https://dns.adguard.com/dns-query",
valid: true,
wantDef: true,
wantErr: ``,
}, {
wantDef: assert.True,
name: "valid_default",
upstream: "sdns://AQMAAAAAAAAAFDE3Ni4xMDMuMTMwLjEzMDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20",
valid: true,
wantDef: true,
wantErr: ``,
}, {
wantDef: assert.False,
name: "valid",
upstream: "[/host.com/]1.1.1.1",
valid: true,
wantDef: false,
wantErr: ``,
}, {
wantDef: assert.False,
name: "valid",
upstream: "[//]tls://1.1.1.1",
valid: true,
wantDef: false,
wantErr: ``,
}, {
wantDef: assert.False,
name: "valid",
upstream: "[/www.host.com/]#",
valid: true,
wantDef: false,
wantErr: ``,
}, {
wantDef: assert.False,
name: "valid",
upstream: "[/host.com/google.com/]8.8.8.8",
valid: true,
wantDef: false,
wantErr: ``,
}, {
wantDef: assert.False,
name: "valid",
upstream: "[/host/]sdns://AQMAAAAAAAAAFDE3Ni4xMDMuMTMwLjEzMDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20",
valid: true,
wantDef: false,
wantErr: ``,
}, {
wantDef: assert.False,
name: "idna",
upstream: "[/пример.рф/]8.8.8.8",
valid: true,
wantDef: false,
wantErr: ``,
}, {
wantDef: assert.False,
name: "bad_domain",
upstream: "[/!/]8.8.8.8",
valid: false,
wantDef: false,
wantErr: `bad upstream for domain "[/!/]8.8.8.8": domain at index 0: ` +
`bad domain name "!": bad domain name label "!": bad domain name label rune '!'`,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
defaultUpstream, err := validateUpstream(tc.upstream)
require.Equal(t, tc.valid, err == nil)
if tc.valid {
assert.Equal(t, tc.wantDef, defaultUpstream)
}
testutil.AssertErrorMsg(t, tc.wantErr, err)
tc.wantDef(t, defaultUpstream)
})
}
}
@@ -343,22 +353,19 @@ func TestValidateUpstream(t *testing.T) {
func TestValidateUpstreamsSet(t *testing.T) {
testCases := []struct {
name string
msg string
wantErr string
set []string
wantNil bool
}{{
name: "empty",
msg: "empty upstreams array should be valid",
wantErr: ``,
set: nil,
wantNil: true,
}, {
name: "comment",
msg: "comments should not be validated",
wantErr: ``,
set: []string{"# comment"},
wantNil: true,
}, {
name: "valid_no_default",
msg: "there is no default upstream",
name: "valid_no_default",
wantErr: `no default upstreams specified`,
set: []string{
"[/host.com/]1.1.1.1",
"[//]tls://1.1.1.1",
@@ -366,10 +373,9 @@ func TestValidateUpstreamsSet(t *testing.T) {
"[/host.com/google.com/]8.8.8.8",
"[/host/]sdns://AQMAAAAAAAAAFDE3Ni4xMDMuMTMwLjEzMDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20",
},
wantNil: false,
}, {
name: "valid_with_default",
msg: "upstreams set is valid, but doesn't pass through validation cause: %s",
name: "valid_with_default",
wantErr: ``,
set: []string{
"[/host.com/]1.1.1.1",
"[//]tls://1.1.1.1",
@@ -378,19 +384,16 @@ func TestValidateUpstreamsSet(t *testing.T) {
"[/host/]sdns://AQMAAAAAAAAAFDE3Ni4xMDMuMTMwLjEzMDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20",
"8.8.8.8",
},
wantNil: true,
}, {
name: "invalid",
msg: "there is an invalid upstream in set, but it pass through validation",
wantErr: `cannot prepare the upstream dhcp://fake.dns ([]): unsupported URL scheme: dhcp`,
set: []string{"dhcp://fake.dns"},
wantNil: false,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := ValidateUpstreams(tc.set)
assert.Equalf(t, tc.wantNil, err == nil, tc.msg, err)
testutil.AssertErrorMsg(t, tc.wantErr, err)
})
}
}

View File

@@ -783,12 +783,17 @@ func (clients *clientsContainer) addFromHostsFile(hosts *netutil.IPMap) {
n := 0
hosts.Range(func(ip net.IP, v interface{}) (cont bool) {
names, ok := v.(*stringutil.Set)
hosts, ok := v.(*aghnet.Hosts)
if !ok {
log.Error("dns: bad type %T in ipToRC for %s", v, ip)
return true
}
names.Range(func(name string) (cont bool) {
if clients.addHostLocked(ip, hosts.Main, ClientSourceHostsFile) {
n++
}
hosts.Aliases.Range(func(name string) (cont bool) {
if clients.addHostLocked(ip, name, ClientSourceHostsFile) {
n++
}

View File

@@ -7,7 +7,7 @@ import (
"path/filepath"
"sync"
"github.com/AdguardTeam/AdGuardHome/internal/aghalgo"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/dhcpd"
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
@@ -288,9 +288,9 @@ func parseConfig() (err error) {
return err
}
uv := aghalgo.UniquenessValidator{}
uc := aghalg.UniqChecker{}
addPorts(
uv,
uc,
config.BindPort,
config.BetaBindPort,
config.DNS.Port,
@@ -298,14 +298,14 @@ func parseConfig() (err error) {
if config.TLS.Enabled {
addPorts(
uv,
uc,
config.TLS.PortHTTPS,
config.TLS.PortDNSOverTLS,
config.TLS.PortDNSOverQUIC,
config.TLS.PortDNSCrypt,
)
}
if err = uv.Validate(aghalgo.IntIsBefore); err != nil {
if err = uc.Validate(aghalg.IntIsBefore); err != nil {
return fmt.Errorf("validating ports: %w", err)
}
@@ -321,10 +321,10 @@ func parseConfig() (err error) {
}
// addPorts is a helper for ports validation. It skips zero ports.
func addPorts(uv aghalgo.UniquenessValidator, ports ...int) {
func addPorts(uc aghalg.UniqChecker, ports ...int) {
for _, p := range ports {
if p != 0 {
uv.Add(p)
uc.Add(p)
}
}
}

View File

@@ -14,9 +14,10 @@ import (
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalgo"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/version"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
)
@@ -24,13 +25,23 @@ import (
// getAddrsResponse is the response for /install/get_addresses endpoint.
type getAddrsResponse struct {
Interfaces map[string]*aghnet.NetInterface `json:"interfaces"`
WebPort int `json:"web_port"`
DNSPort int `json:"dns_port"`
// Version is the version of AdGuard Home.
//
// TODO(a.garipov): In the new API, rename this endpoint to something more
// general, since there will be more information here than just network
// interfaces.
Version string `json:"version"`
WebPort int `json:"web_port"`
DNSPort int `json:"dns_port"`
}
// handleInstallGetAddresses is the handler for /install/get_addresses endpoint.
func (web *Web) handleInstallGetAddresses(w http.ResponseWriter, r *http.Request) {
data := getAddrsResponse{
Version: version.Version(),
WebPort: defaultPortHTTP,
DNSPort: defaultPortDNS,
}
@@ -62,19 +73,19 @@ func (web *Web) handleInstallGetAddresses(w http.ResponseWriter, r *http.Request
}
}
type checkConfigReqEnt struct {
type checkConfReqEnt struct {
IP net.IP `json:"ip"`
Port int `json:"port"`
Autofix bool `json:"autofix"`
}
type checkConfigReq struct {
Web checkConfigReqEnt `json:"web"`
DNS checkConfigReqEnt `json:"dns"`
SetStaticIP bool `json:"set_static_ip"`
type checkConfReq struct {
Web checkConfReqEnt `json:"web"`
DNS checkConfReqEnt `json:"dns"`
SetStaticIP bool `json:"set_static_ip"`
}
type checkConfigRespEnt struct {
type checkConfRespEnt struct {
Status string `json:"status"`
CanAutofix bool `json:"can_autofix"`
}
@@ -85,79 +96,110 @@ type staticIPJSON struct {
Error string `json:"error"`
}
type checkConfigResp struct {
StaticIP staticIPJSON `json:"static_ip"`
Web checkConfigRespEnt `json:"web"`
DNS checkConfigRespEnt `json:"dns"`
type checkConfResp struct {
StaticIP staticIPJSON `json:"static_ip"`
Web checkConfRespEnt `json:"web"`
DNS checkConfRespEnt `json:"dns"`
}
// Check if ports are available, respond with results
func (web *Web) handleInstallCheckConfig(w http.ResponseWriter, r *http.Request) {
reqData := checkConfigReq{}
respData := checkConfigResp{}
// validateWeb returns error is the web part if the initial configuration can't
// be set.
func (req *checkConfReq) validateWeb(uc aghalg.UniqChecker) (err error) {
defer func() { err = errors.Annotate(err, "validating ports: %w") }()
err := json.NewDecoder(r.Body).Decode(&reqData)
port := req.Web.Port
addPorts(uc, config.BetaBindPort, port)
if err = uc.Validate(aghalg.IntIsBefore); err != nil {
// Avoid duplicating the error into the status of DNS.
uc[port] = 1
return err
}
switch port {
case 0, config.BindPort:
return nil
default:
// Go on and check the port binding only if it's not zero or won't be
// unbound after install.
}
return aghnet.CheckPort("tcp", req.Web.IP, port)
}
// validateDNS returns error if the DNS part of the initial configuration can't
// be set. canAutofix is true if the port can be unbound by AdGuard Home
// automatically.
func (req *checkConfReq) validateDNS(uc aghalg.UniqChecker) (canAutofix bool, err error) {
defer func() { err = errors.Annotate(err, "validating ports: %w") }()
port := req.DNS.Port
addPorts(uc, port)
if err = uc.Validate(aghalg.IntIsBefore); err != nil {
return false, err
}
switch port {
case 0:
return false, nil
case config.BindPort:
// Go on and only check the UDP port since the TCP one is already bound
// by AdGuard Home for web interface.
default:
// Check TCP as well.
err = aghnet.CheckPort("tcp", req.DNS.IP, port)
if err != nil {
return false, err
}
}
err = aghnet.CheckPort("udp", req.DNS.IP, port)
if !aghnet.IsAddrInUse(err) {
return false, err
}
// Try to fix automatically.
canAutofix = checkDNSStubListener()
if canAutofix && req.DNS.Autofix {
if derr := disableDNSStubListener(); derr != nil {
log.Error("disabling DNSStubListener: %s", err)
}
err = aghnet.CheckPort("udp", req.DNS.IP, port)
canAutofix = false
}
return canAutofix, err
}
// handleInstallCheckConfig handles the /check_config endpoint.
func (web *Web) handleInstallCheckConfig(w http.ResponseWriter, r *http.Request) {
req := &checkConfReq{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "Failed to parse 'check_config' JSON data: %s", err)
aghhttp.Error(r, w, http.StatusBadRequest, "decoding the request: %s", err)
return
}
uv := aghalgo.UniquenessValidator{}
addPorts(
uv,
config.BindPort,
config.BetaBindPort,
reqData.Web.Port,
)
if err = uv.Validate(aghalgo.IntIsBefore); err != nil {
err = fmt.Errorf("validating ports: %w", err)
respData.Web.Status = err.Error()
} else if reqData.Web.Port != 0 {
err = aghnet.CheckPort("tcp", reqData.Web.IP, reqData.Web.Port)
if err != nil {
respData.Web.Status = err.Error()
}
resp := &checkConfResp{}
uc := aghalg.UniqChecker{}
if err = req.validateWeb(uc); err != nil {
resp.Web.Status = err.Error()
}
addPorts(uv, reqData.DNS.Port)
if err = uv.Validate(aghalgo.IntIsBefore); err != nil {
err = fmt.Errorf("validating ports: %w", err)
respData.DNS.Status = err.Error()
} else if reqData.DNS.Port != 0 {
err = aghnet.CheckPort("udp", reqData.DNS.IP, reqData.DNS.Port)
if aghnet.IsAddrInUse(err) {
canAutofix := checkDNSStubListener()
if canAutofix && reqData.DNS.Autofix {
err = disableDNSStubListener()
if err != nil {
log.Error("Couldn't disable DNSStubListener: %s", err)
}
err = aghnet.CheckPort("udp", reqData.DNS.IP, reqData.DNS.Port)
canAutofix = false
}
respData.DNS.CanAutofix = canAutofix
}
if err == nil {
err = aghnet.CheckPort("tcp", reqData.DNS.IP, reqData.DNS.Port)
}
if err != nil {
respData.DNS.Status = err.Error()
} else if !reqData.DNS.IP.IsUnspecified() {
respData.StaticIP = handleStaticIP(reqData.DNS.IP, reqData.SetStaticIP)
}
if resp.DNS.CanAutofix, err = req.validateDNS(uc); err != nil {
resp.DNS.Status = err.Error()
} else if !req.DNS.IP.IsUnspecified() {
resp.StaticIP = handleStaticIP(req.DNS.IP, req.SetStaticIP)
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(respData)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to marshal JSON: %s", err)
aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err)
return
}
@@ -279,10 +321,11 @@ type applyConfigReqEnt struct {
}
type applyConfigReq struct {
Web applyConfigReqEnt `json:"web"`
DNS applyConfigReqEnt `json:"dns"`
Username string `json:"username"`
Password string `json:"password"`
Username string `json:"username"`
Password string `json:"password"`
Web applyConfigReqEnt `json:"web"`
DNS applyConfigReqEnt `json:"dns"`
}
// copyInstallSettings copies the installation parameters between two
@@ -482,13 +525,13 @@ func (web *Web) handleInstallCheckConfigBeta(w http.ResponseWriter, r *http.Requ
return
}
nonBetaReqData := checkConfigReq{
Web: checkConfigReqEnt{
nonBetaReqData := checkConfReq{
Web: checkConfReqEnt{
IP: reqData.Web.IP[0],
Port: reqData.Web.Port,
Autofix: reqData.Web.Autofix,
},
DNS: checkConfigReqEnt{
DNS: checkConfReqEnt{
IP: reqData.DNS.IP[0],
Port: reqData.DNS.Port,
Autofix: reqData.DNS.Autofix,
@@ -533,10 +576,11 @@ type applyConfigReqEntBeta struct {
// TODO(e.burkov): This should removed with the API v1 when the appropriate
// functionality will appear in default applyConfigReq.
type applyConfigReqBeta struct {
Web applyConfigReqEntBeta `json:"web"`
DNS applyConfigReqEntBeta `json:"dns"`
Username string `json:"username"`
Password string `json:"password"`
Username string `json:"username"`
Password string `json:"password"`
Web applyConfigReqEntBeta `json:"web"`
DNS applyConfigReqEntBeta `json:"dns"`
}
// handleInstallConfigureBeta is a substitution of /install/configure handler

View File

@@ -54,7 +54,7 @@ func initDNSServer() (err error) {
}
Context.stats, err = stats.New(statsConf)
if err != nil {
return fmt.Errorf("couldn't initialize statistics module")
return fmt.Errorf("init stats: %w", err)
}
conf := querylog.Config{

View File

@@ -19,7 +19,7 @@ import (
"syscall"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalgo"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/AdGuardHome/internal/dhcpd"
@@ -296,23 +296,23 @@ func setupConfig(args options) (err error) {
Context.clients.Init(config.Clients, Context.dhcpServer, Context.etcHosts)
if args.bindPort != 0 {
uv := aghalgo.UniquenessValidator{}
uc := aghalg.UniqChecker{}
addPorts(
uv,
uc,
args.bindPort,
config.BetaBindPort,
config.DNS.Port,
)
if config.TLS.Enabled {
addPorts(
uv,
uc,
config.TLS.PortHTTPS,
config.TLS.PortDNSOverTLS,
config.TLS.PortDNSOverQUIC,
config.TLS.PortDNSCrypt,
)
}
if err = uv.Validate(aghalgo.IntIsBefore); err != nil {
if err = uc.Validate(aghalg.IntIsBefore); err != nil {
return fmt.Errorf("validating ports: %w", err)
}
@@ -393,9 +393,9 @@ func run(args options, clientBuildFS fs.FS) {
// Go memory hacks
memoryUsage(args)
// print the first message after logger is configured
// Print the first message after logger is configured.
log.Println(version.Full())
log.Debug("Current working directory is %s", Context.workDir)
log.Debug("current working directory is %s", Context.workDir)
if args.runningAsService {
log.Info("AdGuard Home is running as a service")
}
@@ -631,13 +631,13 @@ func configureLogger(args options) {
log.SetLevel(log.DEBUG)
}
// Make sure that we see the microseconds in logs, as networking stuff
// can happen pretty quickly.
// Make sure that we see the microseconds in logs, as networking stuff can
// happen pretty quickly.
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
// When running as a Windows service, use eventlog by default if nothing else is configured
// Otherwise, we'll simply loose the log output
// When running as a Windows service, use eventlog by default if nothing
// else is configured. Otherwise, we'll simply lose the log output.
ls.LogFile = configSyslog
}

View File

@@ -82,6 +82,12 @@ func svcStatus(s service.Service) (status service.Status, err error) {
// On OpenWrt, the service utility may not exist. We use our service script
// directly in this case.
func svcAction(s service.Service, action string) (err error) {
if runtime.GOOS == "darwin" &&
action == "start" &&
!strings.HasPrefix(Context.workDir, "/Applications/") {
log.Info("warning: service must be started from within the /Applications directory")
}
err = service.Control(s, action)
if err != nil && service.Platform() == "unix-systemv" &&
(action == "start" || action == "stop" || action == "restart") {

View File

@@ -20,7 +20,7 @@ import (
"sync"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalgo"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
"github.com/AdguardTeam/golibs/errors"
@@ -251,9 +251,9 @@ func (t *TLSMod) handleTLSValidate(w http.ResponseWriter, r *http.Request) {
}
if setts.Enabled {
uv := aghalgo.UniquenessValidator{}
uc := aghalg.UniqChecker{}
addPorts(
uv,
uc,
config.BindPort,
config.BetaBindPort,
config.DNS.Port,
@@ -263,7 +263,7 @@ func (t *TLSMod) handleTLSValidate(w http.ResponseWriter, r *http.Request) {
setts.PortDNSCrypt,
)
err = uv.Validate(aghalgo.IntIsBefore)
err = uc.Validate(aghalg.IntIsBefore)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "validating ports: %s", err)
@@ -344,9 +344,9 @@ func (t *TLSMod) handleTLSConfigure(w http.ResponseWriter, r *http.Request) {
}
if data.Enabled {
uv := aghalgo.UniquenessValidator{}
uc := aghalg.UniqChecker{}
addPorts(
uv,
uc,
config.BindPort,
config.BetaBindPort,
config.DNS.Port,
@@ -356,7 +356,7 @@ func (t *TLSMod) handleTLSConfigure(w http.ResponseWriter, r *http.Request) {
data.PortDNSCrypt,
)
err = uv.Validate(aghalgo.IntIsBefore)
err = uc.Validate(aghalg.IntIsBefore)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)

View File

@@ -67,7 +67,29 @@ type unitDB struct {
TimeAvg uint32 // usec
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// createObject creates s from conf and properly initializes it.
func createObject(conf Config) (s *statsCtx, err error) {
defer withRecovered(&err)
s = &statsCtx{
mu: &sync.Mutex{},
}

View File

@@ -62,18 +62,10 @@ func Version() (v string) {
return version
}
// Common formatting constants.
const (
sp = " "
nl = "\n"
tb = "\t"
nltb = nl + tb
)
// Constants defining the format of module information string.
const (
modInfoAtSep = "@"
modInfoDevSep = sp
modInfoDevSep = " "
modInfoSumLeft = " (sum: "
modInfoSumRight = ")"
)
@@ -142,6 +134,7 @@ const (
func Verbose() (v string) {
b := &strings.Builder{}
const nl = "\n"
stringutil.WriteToBuilder(
b,
vFmtAGHHdr,
@@ -178,7 +171,7 @@ func Verbose() (v string) {
stringutil.WriteToBuilder(b, nl, vFmtDepsHdr)
for _, dep := range info.Deps {
if depStr := fmtModule(dep); depStr != "" {
stringutil.WriteToBuilder(b, nltb, depStr)
stringutil.WriteToBuilder(b, "\n\t", depStr)
}
}

View File

@@ -2,9 +2,16 @@
<!-- TODO(a.garipov): Reformat in accordance with the KeepAChangelog spec. -->
## v0.107: API changes
## v0.107.3: API changes
## The new field `"cached"` in `QueryLogItem`
### The new field `"version"` in `AddressesInfo`
* The new field `"version"` in `GET /install/get_addresses` is the version of
the AdGuard Home instance.
## v0.107.0: API changes
### The new field `"cached"` in `QueryLogItem`
* The new field `"cached"` in `GET /control/querylog` is true if the response is
served from cache instead of being resolved by an upstream server.

View File

@@ -123,7 +123,9 @@
'8.8.8.8': 'OK'
'8.8.4.4': 'OK'
'192.168.1.104:53535': >
Couldn't communicate with DNS server
upstream "192.168.1.104:1234" fails to exchange: couldn't
communicate with upstream: read udp
192.168.1.100:60675->8.8.8.8:1234: i/o timeout
'/version.json':
'post':
'tags':
@@ -1262,7 +1264,7 @@
'type': 'boolean'
'version':
'type': 'string'
'example': '0.1'
'example': 'v0.123.4'
'language':
'type': 'string'
'example': 'en'
@@ -2219,19 +2221,23 @@
'description': 'AdGuard Home addresses configuration'
'required':
- 'dns_port'
- 'web_port'
- 'interfaces'
- 'version'
- 'web_port'
'properties':
'dns_port':
'type': 'integer'
'format': 'uint16'
'example': 53
'interfaces':
'$ref': '#/components/schemas/NetInterfaces'
'version':
'type': 'string'
'example': 'v0.123.4'
'web_port':
'type': 'integer'
'format': 'uint16'
'example': 80
'interfaces':
'$ref': '#/components/schemas/NetInterfaces'
'AddressesInfoBeta':
'type': 'object'
'description': 'AdGuard Home addresses configuration'

View File

@@ -272,32 +272,12 @@ fix_darwin() {
return 0
fi
if [ "$cpu" = 'arm64' ]
then
case "$channel"
in
('beta'|'development'|'edge')
# Everything is fine, we have Apple Silicon support on
# these channels.
;;
('release')
cpu='amd64'
log "use $cpu build on Mac M1 until the native ARM support is added."
;;
(*)
# Generally shouldn't happen, since the release channel
# has already been validated.
error_exit "invalid channel '$channel'"
;;
esac
fi
# Set the package extension.
pkg_ext='zip'
# It is important to install AdGuard Home into the /Applications
# directory on macOS. Otherwise, it may not grant enough privileges to
# the AdGuard Home.
# It is important to install AdGuard Home into the /Applications directory
# on macOS. Otherwise, it may grant not enough privileges to the AdGuard
# Home.
out_dir='/Applications'
}

View File

@@ -49,7 +49,7 @@ trap not_found EXIT
# Warnings
go_version="$( "$GO" version )"
go_version="$( "${GO:-go}" version )"
readonly go_version
go_min_version='go1.17'
@@ -62,7 +62,6 @@ for example:
"
readonly go_min_version go_version_msg
case "$go_version"
in
('go version'*"$go_min_version"*)
@@ -80,11 +79,11 @@ esac
# blocklist_imports is a simple check against unwanted packages. The following
# packages are banned:
#
# * Package io/ioutil is soft-deprecated.
#
# * Packages errors and log are replaced by our own packages in the
# github.com/AdguardTeam/golibs module.
#
# * Package io/ioutil is soft-deprecated.
#
# * Package reflect is often an overkill, and for deep comparisons there are
# much better functions in module github.com/google/go-cmp. Which is
# already our indirect dependency and which may or may not enter the stdlib
@@ -94,6 +93,8 @@ esac
#
# * Package unsafe is… unsafe.
#
# * Package golang.org/x/net/context has been moved into stdlib.
#
blocklist_imports() {
git grep\
-e '[[:space:]]"errors"$'\
@@ -101,33 +102,55 @@ blocklist_imports() {
-e '[[:space:]]"log"$'\
-e '[[:space:]]"reflect"$'\
-e '[[:space:]]"unsafe"$'\
-- '*.go' || exit 0;
-e '[[:space:]]"golang.org/x/net/context"$'\
-n\
-- '*.go'\
| sed -e 's/^\([^[:space:]]\+\)\(.*\)$/\1 blocked import:\2/'\
|| exit 0
}
# method_const is a simple check against the usage of some raw strings and
# numbers where one should use named constants.
method_const() {
git grep -F -e '"GET"' -e '"POST"' -- '*.go' || exit 0;
git grep -F\
-e '"DELETE"'\
-e '"GET"'\
-e '"POST"'\
-e '"PUT"'\
-n\
-- '*.go'\
| sed -e 's/^\([^[:space:]]\+\)\(.*\)$/\1 http method literal:\2/'\
|| exit 0
}
# underscores is a simple check against Go filenames with underscores.
# underscores is a simple check against Go filenames with underscores. Add new
# build tags and OS as you go. The main goal of this check is to discourage the
# use of filenames like client_manager.go.
underscores() {
git ls-files '*_*.go' | {
grep -F\
-e '_big.go'\
-e '_bsd.go'\
-e '_darwin.go'\
-e '_freebsd.go'\
-e '_openbsd.go'\
-e '_linux.go'\
-e '_little.go'\
-e '_others.go'\
-e '_test.go'\
-e '_unix.go'\
-e '_windows.go' \
-v\
|| exit 0
}
underscore_files="$(
git ls-files '*_*.go'\
| grep -F\
-e '_big.go'\
-e '_bsd.go'\
-e '_darwin.go'\
-e '_freebsd.go'\
-e '_openbsd.go'\
-e '_linux.go'\
-e '_little.go'\
-e '_others.go'\
-e '_test.go'\
-e '_unix.go'\
-e '_windows.go' \
-v\
| sed -e 's/./\t\0/'
)"
readonly underscore_files
if [ "$underscore_files" != '' ]
then
echo 'found file names with underscores:'
echo "$underscore_files"
fi
}
# TODO(a.garipov): Add an analyser to look for `fallthrough`, `goto`, and `new`?
@@ -151,7 +174,7 @@ exit_on_output() (
output="$( "$cmd" "$@" 2>&1 )"
exitcode="$?"
if [ "$exitcode" != '0' ]
if [ "$exitcode" -ne '0' ]
then
echo "'$cmd' failed with code $exitcode"
fi
@@ -160,9 +183,9 @@ exit_on_output() (
then
if [ "$*" != '' ]
then
echo "combined output of '$cmd $*':"
echo "combined output of linter '$cmd $*':"
else
echo "combined output of '$cmd':"
echo "combined output of linter '$cmd':"
fi
echo "$output"
@@ -178,13 +201,6 @@ exit_on_output() (
# Constants
go_files='./main.go ./internal/'
readonly go_files
# Checks
exit_on_output blocklist_imports
@@ -208,8 +224,6 @@ gocyclo --over 10 ./internal/aghio/ ./internal/aghnet/ ./internal/aghos/\
./internal/aghtest/ ./internal/stats/ ./internal/tools/\
./internal/updater/ ./internal/version/ ./main.go
gosec --quiet $go_files
ineffassign ./...
unparam ./...
@@ -222,6 +236,9 @@ nilness ./...
exit_on_output shadow --strict ./...
# TODO(a.garipov): Enable in v0.108.0.
# gosec --quiet ./...
# TODO(a.garipov): Enable --blank?
errcheck --asserts ./...