-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
1674 lines (1455 loc) · 50.1 KB
/
config.rs
File metadata and controls
1674 lines (1455 loc) · 50.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs;
use std::io::{BufReader, Read};
use std::net::IpAddr;
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;
use uuid::Uuid;
const DEFAULT_CONFIG: &str = include_str!("../../default-config.json");
const DEFAULT_FILTER_DHT: &str = include_str!("../../default-filters/windivert_part.dht.txt");
const DEFAULT_FILTER_DISCORD_MEDIA: &str =
include_str!("../../default-filters/windivert_part.discord_media.txt");
const DEFAULT_FILTER_QUIC_INITIAL_IETF: &str =
include_str!("../../default-filters/windivert_part.quic_initial_ietf.txt");
const DEFAULT_FILTER_STUN: &str = include_str!("../../default-filters/windivert_part.stun.txt");
const DEFAULT_FILTER_WIREGUARD: &str =
include_str!("../../default-filters/windivert_part.wireguard.txt");
const SOURCE_MANAGED_DIR_NAME: &str = "thirdparty";
const INSTALLED_RESOURCES_DIR_NAME: &str = "resources";
const MANAGED_PATH_ALIAS: &str = "@resources";
const LEGACY_MANAGED_PATH_ALIAS: &str = "@thirdparty";
const LEGACY_INSTALLED_RESOURCES_MARKER: &str = ".legacy-thirdparty-migrated";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalPorts {
pub tcp: String,
pub udp: String,
}
impl Default for GlobalPorts {
fn default() -> Self {
Self {
tcp: "1-65535".to_string(),
udp: "1-65535".to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Strategy {
pub id: String,
pub name: String,
pub content: String,
pub active: bool,
#[serde(default)]
pub system: bool,
#[serde(
default,
rename = "systemBaseName",
skip_serializing_if = "Option::is_none"
)]
pub system_base_name: Option<String>,
#[serde(
default,
rename = "systemBaseContent",
skip_serializing_if = "Option::is_none"
)]
pub system_base_content: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Category {
pub id: String,
pub name: String,
pub strategies: Vec<Strategy>,
#[serde(default)]
pub system: bool,
#[serde(
default,
rename = "systemBaseName",
skip_serializing_if = "Option::is_none"
)]
pub system_base_name: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Placeholder {
pub name: String,
pub path: String,
#[serde(default)]
pub system: bool,
#[serde(
default,
rename = "systemBaseName",
skip_serializing_if = "Option::is_none"
)]
pub system_base_name: Option<String>,
#[serde(
default,
rename = "systemBasePath",
skip_serializing_if = "Option::is_none"
)]
pub system_base_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Filter {
pub id: String,
pub name: String,
pub filename: String,
pub active: bool,
#[serde(default)]
pub content: String,
#[serde(default)]
pub system: bool,
#[serde(
default,
rename = "systemBaseName",
skip_serializing_if = "Option::is_none"
)]
pub system_base_name: Option<String>,
#[serde(
default,
rename = "systemBaseFilename",
skip_serializing_if = "Option::is_none"
)]
pub system_base_filename: Option<String>,
#[serde(
default,
rename = "systemBaseContent",
skip_serializing_if = "Option::is_none"
)]
pub system_base_content: Option<String>,
#[serde(
default,
rename = "systemBaseActive",
skip_serializing_if = "Option::is_none"
)]
pub system_base_active: Option<bool>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ListMode {
#[default]
Ipset,
Exclude,
}
impl std::fmt::Display for ListMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ListMode::Ipset => write!(f, "ipset"),
ListMode::Exclude => write!(f, "exclude"),
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum WindowMaterial {
None,
#[default]
Acrylic,
Mica,
Tabbed,
}
impl<'de> Deserialize<'de> for WindowMaterial {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum WindowMaterialRepr {
String(String),
Bool(bool),
}
match WindowMaterialRepr::deserialize(deserializer)? {
WindowMaterialRepr::String(value) => match value.as_str() {
"none" => Ok(Self::None),
"acrylic" => Ok(Self::Acrylic),
"mica" => Ok(Self::Mica),
"tabbed" => Ok(Self::Tabbed),
other => Err(serde::de::Error::unknown_variant(
other,
&["none", "acrylic", "mica", "tabbed"],
)),
},
WindowMaterialRepr::Bool(enabled) => {
Ok(if enabled { Self::Acrylic } else { Self::None })
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
pub global_ports: GlobalPorts,
pub categories: Vec<Category>,
pub placeholders: Vec<Placeholder>,
#[serde(default)]
pub filters: Vec<Filter>,
pub binaries_path: String,
#[serde(default = "default_dns_preset_id", rename = "dnsPresetId")]
pub dns_preset_id: String,
#[serde(
default = "default_dns_bootstrap_resolvers",
rename = "dnsBootstrapResolvers"
)]
pub dns_bootstrap_resolvers: Vec<String>,
#[serde(
default = "default_dns_accelerator_enabled",
rename = "dnsAcceleratorEnabled"
)]
pub dns_accelerator_enabled: bool,
#[serde(default = "default_dns_module_enabled", rename = "dnsModuleEnabled")]
pub dns_module_enabled: bool,
#[serde(default = "default_tg_ws_proxy_port", rename = "tgWsProxyPort")]
pub tg_ws_proxy_port: u16,
#[serde(default = "default_tg_ws_proxy_secret", rename = "tgWsProxySecret")]
pub tg_ws_proxy_secret: String,
#[serde(
default = "default_tg_ws_proxy_module_enabled",
rename = "tgWsProxyModuleEnabled"
)]
pub tg_ws_proxy_module_enabled: bool,
#[serde(
default = "default_discord_presence_enabled",
rename = "discordPresenceEnabled"
)]
pub discord_presence_enabled: bool,
#[serde(default = "default_minimize_to_tray", rename = "minimizeToTray")]
pub minimize_to_tray: bool,
#[serde(default = "default_launch_to_tray", rename = "launchToTray")]
pub launch_to_tray: bool,
#[serde(
default = "default_connect_on_autostart",
rename = "connectOnAutostart"
)]
pub connect_on_autostart: bool,
#[serde(default, rename = "listMode")]
pub list_mode: ListMode,
#[serde(
default = "default_core_file_update_prompts_enabled",
rename = "coreFileUpdatePromptsEnabled"
)]
pub core_file_update_prompts_enabled: bool,
#[serde(
default = "default_app_auto_updates_enabled",
rename = "appAutoUpdatesEnabled"
)]
pub app_auto_updates_enabled: bool,
#[serde(
default = "default_window_material",
rename = "windowMaterial",
alias = "windowAcrylicEnabled"
)]
pub window_material: WindowMaterial,
#[serde(default, rename = "systemRemovedCategoryIds")]
pub system_removed_category_ids: Vec<String>,
#[serde(default, rename = "systemRemovedStrategyKeys")]
pub system_removed_strategy_keys: Vec<String>,
#[serde(default, rename = "systemRemovedPlaceholderNames")]
pub system_removed_placeholder_names: Vec<String>,
#[serde(default, rename = "systemRemovedFilterIds")]
pub system_removed_filter_ids: Vec<String>,
#[serde(default, rename = "systemSyncInitialized")]
pub system_sync_initialized: bool,
}
pub struct ConfigEnsureResult {
pub config: AppConfig,
pub restored_default: bool,
pub normalized_and_persisted: bool,
pub unrecoverable_filters: Vec<String>,
}
struct NormalizedConfigResult {
config: AppConfig,
changed: bool,
unrecoverable_filters: Vec<String>,
}
pub(crate) fn validate_filter_filename(filename: &str) -> Result<String, String> {
if filename.is_empty() {
return Err("Filename cannot be empty".to_string());
}
if filename.contains('/') || filename.contains('\\') {
return Err("Path separators not allowed in filename".to_string());
}
let path = Path::new(filename);
let mut components = path.components();
let first_component = components
.next()
.ok_or_else(|| "Filename cannot be empty".to_string())?;
if components.next().is_some() {
return Err("Path separators not allowed in filename".to_string());
}
match first_component {
Component::Normal(name) => {
let name = name
.to_str()
.ok_or_else(|| "Invalid filename".to_string())?;
if name.is_empty() || name == "." || name == ".." {
return Err("Invalid filename".to_string());
}
Ok(name.to_string())
}
_ => Err("Invalid filename".to_string()),
}
}
fn default_minimize_to_tray() -> bool {
true
}
fn default_launch_to_tray() -> bool {
false
}
fn default_connect_on_autostart() -> bool {
false
}
fn default_core_file_update_prompts_enabled() -> bool {
true
}
fn default_app_auto_updates_enabled() -> bool {
true
}
fn default_dns_preset_id() -> String {
"comss-one".to_string()
}
fn normalize_dns_preset_id(preset_id: &str) -> String {
let normalized = preset_id.trim();
if normalized.eq_ignore_ascii_case("malw-link") {
return "malw-link-main".to_string();
}
match normalized {
"comss-one" | "xbox-dns-ru" | "malw-link-main" | "malw-link-cf" | "mafioznik"
| "astracat" => normalized.to_string(),
_ => default_dns_preset_id(),
}
}
fn default_dns_bootstrap_resolvers() -> Vec<String> {
vec![
"77.88.8.8".to_string(),
"1.1.1.1".to_string(),
"8.8.8.8".to_string(),
]
}
fn default_dns_accelerator_enabled() -> bool {
false
}
fn default_dns_module_enabled() -> bool {
false
}
fn default_tg_ws_proxy_port() -> u16 {
1443
}
fn default_tg_ws_proxy_secret() -> String {
String::new()
}
fn default_tg_ws_proxy_module_enabled() -> bool {
false
}
fn default_discord_presence_enabled() -> bool {
true
}
fn is_valid_tg_ws_proxy_secret(secret: &str) -> bool {
secret.len() == 32 && secret.chars().all(|char| char.is_ascii_hexdigit())
}
fn generate_tg_ws_proxy_secret() -> String {
Uuid::new_v4().simple().to_string()
}
fn default_window_material() -> WindowMaterial {
WindowMaterial::Acrylic
}
fn system_strategy_key(category_id: &str, strategy_id: &str) -> String {
format!("{category_id}::{strategy_id}")
}
fn annotate_builtin_category(category: &mut Category) {
category.system = true;
category.system_base_name = Some(category.name.clone());
for strategy in &mut category.strategies {
strategy.system = true;
strategy.system_base_name = Some(strategy.name.clone());
strategy.system_base_content = Some(strategy.content.clone());
}
}
fn annotate_builtin_placeholder(placeholder: &mut Placeholder) {
placeholder.system = true;
placeholder.system_base_name = Some(placeholder.name.clone());
placeholder.system_base_path = Some(placeholder.path.clone());
}
fn annotate_builtin_filter(filter: &mut Filter) {
filter.system = true;
filter.system_base_name = Some(filter.name.clone());
filter.system_base_filename = Some(filter.filename.clone());
filter.system_base_content = Some(filter.content.clone());
filter.system_base_active = Some(filter.active);
}
fn strategy_base_name(strategy: &Strategy) -> &str {
strategy
.system_base_name
.as_deref()
.unwrap_or(strategy.name.as_str())
}
fn strategy_base_content(strategy: &Strategy) -> &str {
strategy
.system_base_content
.as_deref()
.unwrap_or(strategy.content.as_str())
}
fn is_legacy_system_strategy_name(
current_name: &str,
category_name: &str,
strategy_id: &str,
builtin_name: &str,
) -> bool {
let mut candidates = vec![format!("{category_name} {builtin_name}")];
if let Some(version_without_prefix) = builtin_name.strip_prefix('v') {
candidates.push(format!("{category_name} {version_without_prefix}"));
}
if let Some(id_suffix) = strategy_id.rsplit('-').next() {
candidates.push(format!("{category_name} {id_suffix}"));
if let Some(version_without_prefix) = id_suffix.strip_prefix('v') {
candidates.push(format!("{category_name} {version_without_prefix}"));
}
}
candidates
.into_iter()
.any(|candidate| current_name == candidate)
}
fn is_system_strategy_modified(strategy: &Strategy) -> bool {
strategy.name != strategy_base_name(strategy)
|| strategy.content != strategy_base_content(strategy)
}
fn category_base_name(category: &Category) -> &str {
category
.system_base_name
.as_deref()
.unwrap_or(category.name.as_str())
}
fn is_system_category_name_modified(category: &Category) -> bool {
category.name != category_base_name(category)
}
fn is_system_category_modified(category: &Category) -> bool {
if is_system_category_name_modified(category) {
return true;
}
category
.strategies
.iter()
.any(|strategy| !strategy.system || is_system_strategy_modified(strategy))
}
fn placeholder_base_name(placeholder: &Placeholder) -> &str {
placeholder
.system_base_name
.as_deref()
.unwrap_or(placeholder.name.as_str())
}
fn placeholder_base_path(placeholder: &Placeholder) -> &str {
placeholder
.system_base_path
.as_deref()
.unwrap_or(placeholder.path.as_str())
}
fn is_system_placeholder_modified(placeholder: &Placeholder) -> bool {
placeholder.name != placeholder_base_name(placeholder)
|| placeholder.path != placeholder_base_path(placeholder)
}
fn filter_base_name(filter: &Filter) -> &str {
filter
.system_base_name
.as_deref()
.unwrap_or(filter.name.as_str())
}
fn filter_base_filename(filter: &Filter) -> &str {
filter
.system_base_filename
.as_deref()
.unwrap_or(filter.filename.as_str())
}
fn filter_base_content(filter: &Filter) -> &str {
filter
.system_base_content
.as_deref()
.unwrap_or(filter.content.as_str())
}
fn filter_base_active(filter: &Filter) -> bool {
filter.system_base_active.unwrap_or(filter.active)
}
fn is_system_filter_modified(filter: &Filter) -> bool {
filter.name != filter_base_name(filter)
|| filter.filename != filter_base_filename(filter)
|| filter.content != filter_base_content(filter)
|| filter.active != filter_base_active(filter)
}
fn built_in_filter_content(filename: &str) -> Option<&'static str> {
match filename.trim() {
"windivert_part.dht.txt" => Some(DEFAULT_FILTER_DHT),
"windivert_part.discord_media.txt" => Some(DEFAULT_FILTER_DISCORD_MEDIA),
"windivert_part.quic_initial_ietf.txt" => Some(DEFAULT_FILTER_QUIC_INITIAL_IETF),
"windivert_part.stun.txt" => Some(DEFAULT_FILTER_STUN),
"windivert_part.wireguard.txt" => Some(DEFAULT_FILTER_WIREGUARD),
_ => None,
}
}
fn default_filters_metadata() -> Vec<Filter> {
vec![
Filter {
id: "filter-discord".to_string(),
name: "Discord Media".to_string(),
filename: "windivert_part.discord_media.txt".to_string(),
active: true,
content: String::new(),
system: false,
system_base_name: None,
system_base_filename: None,
system_base_content: None,
system_base_active: None,
},
Filter {
id: "filter-stun".to_string(),
name: "STUN".to_string(),
filename: "windivert_part.stun.txt".to_string(),
active: true,
content: String::new(),
system: false,
system_base_name: None,
system_base_filename: None,
system_base_content: None,
system_base_active: None,
},
Filter {
id: "filter-wireguard".to_string(),
name: "WireGuard".to_string(),
filename: "windivert_part.wireguard.txt".to_string(),
active: false,
content: String::new(),
system: false,
system_base_name: None,
system_base_filename: None,
system_base_content: None,
system_base_active: None,
},
Filter {
id: "filter-quic".to_string(),
name: "QUIC Initial IETF".to_string(),
filename: "windivert_part.quic_initial_ietf.txt".to_string(),
active: false,
content: String::new(),
system: false,
system_base_name: None,
system_base_filename: None,
system_base_content: None,
system_base_active: None,
},
Filter {
id: "filter-dht".to_string(),
name: "DHT".to_string(),
filename: "windivert_part.dht.txt".to_string(),
active: false,
content: String::new(),
system: false,
system_base_name: None,
system_base_filename: None,
system_base_content: None,
system_base_active: None,
},
]
}
fn populate_builtin_filter_content(filters: &mut [Filter]) -> bool {
let mut changed = false;
for filter in filters.iter_mut() {
if filter.content.is_empty()
&& let Some(content) = built_in_filter_content(&filter.filename)
{
filter.content = content.to_string();
changed = true;
}
}
changed
}
fn is_dev_project_root(path: &Path) -> bool {
path.join("src-tauri").join("tauri.conf.json").is_file()
&& path.join(SOURCE_MANAGED_DIR_NAME).is_dir()
}
fn executable_dir() -> Option<PathBuf> {
std::env::current_exe()
.ok()
.and_then(|path| path.parent().map(Path::to_path_buf))
}
fn find_dev_project_root() -> Option<PathBuf> {
if !cfg!(debug_assertions) {
return None;
}
let mut candidates = Vec::new();
if let Ok(path) = std::env::current_exe() {
candidates.extend(path.ancestors().map(Path::to_path_buf));
}
if let Ok(path) = std::env::current_dir() {
candidates.extend(path.ancestors().map(Path::to_path_buf));
}
candidates
.into_iter()
.find(|candidate| is_dev_project_root(candidate))
}
fn install_resources_dir() -> PathBuf {
executable_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(INSTALLED_RESOURCES_DIR_NAME)
}
fn source_managed_resources_dir() -> Option<PathBuf> {
find_dev_project_root().map(|project_root| project_root.join(SOURCE_MANAGED_DIR_NAME))
}
pub(crate) fn uses_dev_managed_resources_source() -> bool {
source_managed_resources_dir()
.map(|source_dir| source_dir != get_managed_resources_dir())
.unwrap_or(false)
}
fn legacy_install_resources_dir() -> Option<PathBuf> {
executable_dir().map(|dir| dir.join(SOURCE_MANAGED_DIR_NAME))
}
pub(crate) fn get_runtime_data_dir() -> PathBuf {
executable_dir().unwrap_or_else(|| PathBuf::from("."))
}
fn managed_relative_path(path: &str) -> Option<String> {
let normalized = path.replace('\\', "/");
if normalized == MANAGED_PATH_ALIAS {
return Some(String::new());
}
normalized
.strip_prefix(&format!("{MANAGED_PATH_ALIAS}/"))
.map(str::to_string)
}
fn join_relative_path(base: &Path, relative: &str) -> PathBuf {
let mut path = base.to_path_buf();
for segment in relative.split('/') {
if !segment.is_empty() {
path.push(segment);
}
}
path
}
fn normalize_placeholder_path(path: &str) -> Option<String> {
let normalized = path.replace('\\', "/");
if normalized == MANAGED_PATH_ALIAS || normalized.starts_with(&format!("{MANAGED_PATH_ALIAS}/"))
{
return Some(normalized);
}
if normalized == LEGACY_MANAGED_PATH_ALIAS {
return Some(MANAGED_PATH_ALIAS.to_string());
}
if let Some(suffix) = normalized.strip_prefix(&format!("{LEGACY_MANAGED_PATH_ALIAS}/")) {
return Some(format!("{MANAGED_PATH_ALIAS}/{suffix}"));
}
None
}
fn normalize_placeholder_paths(placeholders: &mut [Placeholder]) -> bool {
let mut changed = false;
for placeholder in placeholders.iter_mut() {
if let Some(normalized) = normalize_placeholder_path(&placeholder.path)
&& placeholder.path != normalized
{
placeholder.path = normalized;
changed = true;
}
}
changed
}
fn resolve_managed_placeholder_path(path: &str) -> Option<String> {
let relative = managed_relative_path(path)?;
let base = get_managed_resources_dir();
Some(if relative.is_empty() {
base.to_string_lossy().to_string()
} else {
join_relative_path(&base, &relative)
.to_string_lossy()
.to_string()
})
}
impl Default for AppConfig {
fn default() -> Self {
let mut config: AppConfig =
serde_json::from_str(DEFAULT_CONFIG).expect("Failed to parse default config");
config.binaries_path = get_managed_resources_dir().to_string_lossy().to_string();
config.system_removed_category_ids.clear();
config.system_removed_strategy_keys.clear();
config.system_removed_placeholder_names.clear();
config.system_removed_filter_ids.clear();
config.system_sync_initialized = true;
if config.filters.is_empty() {
config.filters = default_filters_metadata();
}
populate_builtin_filter_content(&mut config.filters);
normalize_placeholder_paths(&mut config.placeholders);
for placeholder in &mut config.placeholders {
annotate_builtin_placeholder(placeholder);
}
for filter in &mut config.filters {
annotate_builtin_filter(filter);
}
for category in &mut config.categories {
annotate_builtin_category(category);
}
config
}
}
pub fn get_managed_resources_dir() -> PathBuf {
install_resources_dir()
}
fn copy_missing_tree(source: &Path, destination: &Path) -> Result<(), String> {
if !source.is_dir() {
return Ok(());
}
fs::create_dir_all(destination).map_err(|e| e.to_string())?;
for entry in fs::read_dir(source).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let source_path = entry.path();
let destination_path = destination.join(entry.file_name());
if entry.file_type().map_err(|e| e.to_string())?.is_dir() {
copy_missing_tree(&source_path, &destination_path)?;
continue;
}
if !destination_path.exists() {
fs::copy(&source_path, &destination_path).map_err(|e| e.to_string())?;
}
}
Ok(())
}
fn should_replace_file(source: &Path, destination: &Path) -> Result<bool, String> {
if !destination.exists() {
return Ok(true);
}
let source_metadata = fs::metadata(source).map_err(|e| e.to_string())?;
let destination_metadata = fs::metadata(destination).map_err(|e| e.to_string())?;
if source_metadata.len() != destination_metadata.len() {
return Ok(true);
}
if let (Ok(source_modified), Ok(destination_modified)) =
(source_metadata.modified(), destination_metadata.modified())
&& source_modified > destination_modified
{
return Ok(true);
}
let source_file = fs::File::open(source).map_err(|e| e.to_string())?;
let destination_file = fs::File::open(destination).map_err(|e| e.to_string())?;
let mut source_reader = BufReader::new(source_file);
let mut destination_reader = BufReader::new(destination_file);
let mut source_buffer = [0_u8; 64 * 1024];
let mut destination_buffer = [0_u8; 64 * 1024];
let mut remaining = source_metadata.len() as usize;
while remaining > 0 {
let chunk_size = remaining.min(source_buffer.len());
source_reader
.read_exact(&mut source_buffer[..chunk_size])
.map_err(|e| e.to_string())?;
destination_reader
.read_exact(&mut destination_buffer[..chunk_size])
.map_err(|e| e.to_string())?;
if source_buffer[..chunk_size] != destination_buffer[..chunk_size] {
return Ok(true);
}
remaining -= chunk_size;
}
Ok(false)
}
fn sync_tree_with_updates(source: &Path, destination: &Path) -> Result<(), String> {
if !source.is_dir() {
return Ok(());
}
fs::create_dir_all(destination).map_err(|e| e.to_string())?;
for entry in fs::read_dir(source).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let source_path = entry.path();
let destination_path = destination.join(entry.file_name());
if entry.file_type().map_err(|e| e.to_string())?.is_dir() {
sync_tree_with_updates(&source_path, &destination_path)?;
continue;
}
if should_replace_file(&source_path, &destination_path)? {
fs::copy(&source_path, &destination_path).map_err(|e| e.to_string())?;
}
}
Ok(())
}
fn migrate_legacy_installed_resources() -> Result<(), String> {
let managed_dir = get_managed_resources_dir();
fs::create_dir_all(&managed_dir).map_err(|e| e.to_string())?;
let marker_path = managed_dir.join(LEGACY_INSTALLED_RESOURCES_MARKER);
if marker_path.exists() {
return Ok(());
}
let Some(legacy_dir) = legacy_install_resources_dir() else {
return Ok(());
};
if legacy_dir == managed_dir || !legacy_dir.is_dir() {
return Ok(());
}
copy_missing_tree(&legacy_dir, &managed_dir)?;
fs::write(marker_path, []).map_err(|e| e.to_string())?;
Ok(())
}
pub fn ensure_managed_resources_dir_ready() -> Result<PathBuf, String> {
let dir = get_managed_resources_dir();
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
if let Some(source_dir) = source_managed_resources_dir()
&& source_dir != dir
{
sync_tree_with_updates(&source_dir, &dir)?;
}
migrate_legacy_installed_resources()?;
Ok(dir)
}
pub fn ensure_runtime_data_dir_ready() -> Result<PathBuf, String> {
let dir = get_runtime_data_dir();
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
Ok(dir)
}
pub(crate) fn get_config_path() -> PathBuf {
get_runtime_data_dir().join("config.json")
}
pub struct AppState {
pub config: Mutex<AppConfig>,
}
impl AppState {
pub fn new() -> Result<Self, String> {
let ensured = ensure_config_exists_and_normalized()?;
Ok(Self {
config: Mutex::new(ensured.config),
})
}
}
fn read_config_from_disk() -> Result<Option<AppConfig>, String> {
ensure_runtime_data_dir_ready()?;
let config_path = get_config_path();
if !config_path.try_exists().map_err(|e| e.to_string())? {
return Ok(None);
}
if !config_path.is_file() {
return Ok(None);
}
let content = fs::read_to_string(&config_path).map_err(|e| e.to_string())?;
let config: AppConfig = serde_json::from_str(&content).map_err(|e| e.to_string())?;
Ok(Some(config))
}
fn normalize_config(mut config: AppConfig) -> NormalizedConfigResult {
let mut changed = false;
let mut unrecoverable_filters = Vec::new();
let expected_binaries_path = get_managed_resources_dir().to_string_lossy().to_string();
let builtin_config = AppConfig::default();
if config.binaries_path != expected_binaries_path {
config.binaries_path = expected_binaries_path;
changed = true;
}
let normalized_dns_preset_id = normalize_dns_preset_id(&config.dns_preset_id);
if config.dns_preset_id != normalized_dns_preset_id {
config.dns_preset_id = normalized_dns_preset_id;
changed = true;
}
if config.tg_ws_proxy_port == 0 {
config.tg_ws_proxy_port = default_tg_ws_proxy_port();
changed = true;
}
let normalized_tg_ws_proxy_secret = config.tg_ws_proxy_secret.trim().to_ascii_lowercase();
if !is_valid_tg_ws_proxy_secret(&normalized_tg_ws_proxy_secret) {
config.tg_ws_proxy_secret = generate_tg_ws_proxy_secret();
changed = true;
} else if config.tg_ws_proxy_secret != normalized_tg_ws_proxy_secret {
config.tg_ws_proxy_secret = normalized_tg_ws_proxy_secret;
changed = true;
}
let mut seen_bootstrap_resolvers = HashSet::new();
let normalized_bootstrap_resolvers = config
.dns_bootstrap_resolvers
.iter()
.map(|resolver| resolver.trim())
.filter(|resolver| !resolver.is_empty())
.filter_map(|resolver| match resolver.parse::<IpAddr>() {
Ok(ip) => {
let value = ip.to_string();
if seen_bootstrap_resolvers.insert(value.clone()) {
Some(value)
} else {
None
}
}
Err(_) => {
changed = true;
None
}