-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathconfig.rs
More file actions
3087 lines (2853 loc) · 104 KB
/
Copy pathconfig.rs
File metadata and controls
3087 lines (2853 loc) · 104 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 std::{
collections::{HashMap, HashSet},
fs,
io::{Read, Write},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
ops::{Deref, DerefMut},
path::{Path, PathBuf},
sync::{Mutex, RwLock},
time::{Duration, Instant, SystemTime},
};
use anyhow::Result;
use bytes::Bytes;
use rand::Rng;
use regex::Regex;
use serde as de;
use serde_derive::{Deserialize, Serialize};
use serde_json;
use sodiumoxide::base64;
use sodiumoxide::crypto::sign;
use crate::{
compress::{compress, decompress},
log,
password_security::{
decrypt_str_or_original, decrypt_vec_or_original, encrypt_str_or_original,
encrypt_vec_or_original, symmetric_crypt,
},
};
pub const RENDEZVOUS_TIMEOUT: u64 = 12_000;
pub const CONNECT_TIMEOUT: u64 = 18_000;
pub const READ_TIMEOUT: u64 = 18_000;
// https://github.com/quic-go/quic-go/issues/525#issuecomment-294531351
// https://datatracker.ietf.org/doc/html/draft-hamilton-early-deployment-quic-00#section-6.10
// 15 seconds is recommended by quic, though oneSIP recommend 25 seconds,
// https://www.onsip.com/voip-resources/voip-fundamentals/what-is-nat-keepalive
pub const REG_INTERVAL: i64 = 15_000;
pub const COMPRESS_LEVEL: i32 = 3;
const SERIAL: i32 = 3;
const PASSWORD_ENC_VERSION: &str = "00";
pub const ENCRYPT_MAX_LEN: usize = 128; // used for password, pin, etc, not for all
#[cfg(target_os = "macos")]
lazy_static::lazy_static! {
pub static ref ORG: RwLock<String> = RwLock::new("com.carriez".to_owned());
}
type Size = (i32, i32, i32, i32);
type KeyPair = (Vec<u8>, Vec<u8>);
lazy_static::lazy_static! {
static ref CONFIG: RwLock<Config> = RwLock::new(Config::load());
static ref CONFIG2: RwLock<Config2> = RwLock::new(Config2::load());
static ref LOCAL_CONFIG: RwLock<LocalConfig> = RwLock::new(LocalConfig::load());
static ref STATUS: RwLock<Status> = RwLock::new(Status::load());
static ref TRUSTED_DEVICES: RwLock<(Vec<TrustedDevice>, bool)> = Default::default();
static ref ONLINE: Mutex<HashMap<String, i64>> = Default::default();
pub static ref PROD_RENDEZVOUS_SERVER: RwLock<String> = RwLock::new("".to_owned());
pub static ref EXE_RENDEZVOUS_SERVER: RwLock<String> = Default::default();
pub static ref APP_NAME: RwLock<String> = RwLock::new("RustDesk".to_owned());
static ref KEY_PAIR: Mutex<Option<KeyPair>> = Default::default();
static ref USER_DEFAULT_CONFIG: RwLock<(UserDefaultConfig, Instant)> = RwLock::new((UserDefaultConfig::load(), Instant::now()));
pub static ref NEW_STORED_PEER_CONFIG: Mutex<HashSet<String>> = Default::default();
pub static ref DEFAULT_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref OVERWRITE_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref DEFAULT_DISPLAY_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref OVERWRITE_DISPLAY_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref DEFAULT_LOCAL_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref OVERWRITE_LOCAL_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref HARD_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
pub static ref BUILTIN_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
}
#[cfg(target_os = "android")]
lazy_static::lazy_static! {
pub static ref ANDROID_RUSTLS_PLATFORM_VERIFIER_INITIALIZED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
}
lazy_static::lazy_static! {
pub static ref APP_DIR: RwLock<String> = Default::default();
}
#[cfg(any(target_os = "android", target_os = "ios"))]
lazy_static::lazy_static! {
pub static ref APP_HOME_DIR: RwLock<String> = Default::default();
}
pub const LINK_DOCS_HOME: &str = "https://rustdesk.com/docs/en/";
pub const LINK_DOCS_X11_REQUIRED: &str = "https://rustdesk.com/docs/en/manual/linux/#x11-required";
pub const LINK_HEADLESS_LINUX_SUPPORT: &str =
"https://github.com/rustdesk/rustdesk/wiki/Headless-Linux-Support";
lazy_static::lazy_static! {
pub static ref HELPER_URL: HashMap<&'static str, &'static str> = HashMap::from([
("rustdesk docs home", LINK_DOCS_HOME),
("rustdesk docs x11-required", LINK_DOCS_X11_REQUIRED),
("rustdesk x11 headless", LINK_HEADLESS_LINUX_SUPPORT),
]);
}
const NUM_CHARS: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const CHARS: &[char] = &[
'2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
];
pub const RENDEZVOUS_SERVERS: &[&str] = &["rs-ny.rustdesk.com"];
pub const RS_PUB_KEY: &str = "OeVuKk5nlHiXp+APNn0Y3pC1Iwpwn44JGqrQCsWqmBw=";
pub const RENDEZVOUS_PORT: i32 = 21116;
pub const RELAY_PORT: i32 = 21117;
pub const WS_RENDEZVOUS_PORT: i32 = 21118;
pub const WS_RELAY_PORT: i32 = 21119;
macro_rules! serde_field_string {
($default_func:ident, $de_func:ident, $default_expr:expr) => {
fn $default_func() -> String {
$default_expr
}
fn $de_func<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: de::Deserializer<'de>,
{
let s: String =
de::Deserialize::deserialize(deserializer).unwrap_or(Self::$default_func());
if s.is_empty() {
return Ok(Self::$default_func());
}
Ok(s)
}
};
}
macro_rules! serde_field_bool {
($struct_name: ident, $field_name: literal, $func: ident, $default: literal) => {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct $struct_name {
#[serde(default = $default, rename = $field_name, deserialize_with = "deserialize_bool")]
pub v: bool,
}
impl Default for $struct_name {
fn default() -> Self {
Self { v: Self::$func() }
}
}
impl $struct_name {
pub fn $func() -> bool {
UserDefaultConfig::read($field_name) == "Y"
}
}
impl Deref for $struct_name {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.v
}
}
impl DerefMut for $struct_name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.v
}
}
};
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NetworkType {
Direct,
ProxySocks,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct Config {
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "deserialize_string"
)]
pub id: String, // use
#[serde(default, deserialize_with = "deserialize_string")]
enc_id: String, // store
#[serde(default, deserialize_with = "deserialize_string")]
password: String,
#[serde(default, deserialize_with = "deserialize_string")]
salt: String,
#[serde(default, deserialize_with = "deserialize_keypair")]
key_pair: KeyPair, // sk, pk
#[serde(default, deserialize_with = "deserialize_bool")]
key_confirmed: bool,
#[serde(default, deserialize_with = "deserialize_hashmap_string_bool")]
keys_confirmed: HashMap<String, bool>,
}
#[derive(Debug, Default, PartialEq, Serialize, Deserialize, Clone)]
pub struct Socks5Server {
#[serde(default, deserialize_with = "deserialize_string")]
pub proxy: String,
#[serde(default, deserialize_with = "deserialize_string")]
pub username: String,
#[serde(default, deserialize_with = "deserialize_string")]
pub password: String,
}
// more variable configs
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct Config2 {
#[serde(default, deserialize_with = "deserialize_string")]
rendezvous_server: String,
#[serde(default, deserialize_with = "deserialize_i32")]
nat_type: i32,
#[serde(default, deserialize_with = "deserialize_i32")]
serial: i32,
#[serde(default, deserialize_with = "deserialize_string")]
unlock_pin: String,
#[serde(default, deserialize_with = "deserialize_string")]
trusted_devices: String,
#[serde(default)]
socks: Option<Socks5Server>,
// the other scalar value must before this
#[serde(default, deserialize_with = "deserialize_hashmap_string_string")]
pub options: HashMap<String, String>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct Resolution {
pub w: i32,
pub h: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct PeerConfig {
#[serde(default, deserialize_with = "deserialize_vec_u8")]
pub password: Vec<u8>,
#[serde(default, deserialize_with = "deserialize_size")]
pub size: Size,
#[serde(default, deserialize_with = "deserialize_size")]
pub size_ft: Size,
#[serde(default, deserialize_with = "deserialize_size")]
pub size_pf: Size,
#[serde(
default = "PeerConfig::default_view_style",
deserialize_with = "PeerConfig::deserialize_view_style",
skip_serializing_if = "String::is_empty"
)]
pub view_style: String,
// Image scroll style, scrolledge, scrollbar or scroll auto
#[serde(
default = "PeerConfig::default_scroll_style",
deserialize_with = "PeerConfig::deserialize_scroll_style",
skip_serializing_if = "String::is_empty"
)]
pub scroll_style: String,
#[serde(
default = "PeerConfig::default_edge_scroll_edge_thickness",
deserialize_with = "PeerConfig::deserialize_edge_scroll_edge_thickness"
)]
pub edge_scroll_edge_thickness: i32,
#[serde(
default = "PeerConfig::default_image_quality",
deserialize_with = "PeerConfig::deserialize_image_quality",
skip_serializing_if = "String::is_empty"
)]
pub image_quality: String,
#[serde(
default = "PeerConfig::default_custom_image_quality",
deserialize_with = "PeerConfig::deserialize_custom_image_quality",
skip_serializing_if = "Vec::is_empty"
)]
pub custom_image_quality: Vec<i32>,
#[serde(flatten)]
pub show_remote_cursor: ShowRemoteCursor,
#[serde(flatten)]
pub lock_after_session_end: LockAfterSessionEnd,
#[serde(flatten)]
pub terminal_persistent: TerminalPersistent,
#[serde(flatten)]
pub privacy_mode: PrivacyMode,
#[serde(flatten)]
pub allow_swap_key: AllowSwapKey,
#[serde(default, deserialize_with = "deserialize_vec_i32_string_i32")]
pub port_forwards: Vec<(i32, String, i32)>,
#[serde(default, deserialize_with = "deserialize_i32")]
pub direct_failures: i32,
#[serde(flatten)]
pub disable_audio: DisableAudio,
#[serde(flatten)]
pub disable_clipboard: DisableClipboard,
#[serde(flatten)]
pub enable_file_copy_paste: EnableFileCopyPaste,
#[serde(flatten)]
pub show_quality_monitor: ShowQualityMonitor,
#[serde(flatten)]
pub follow_remote_cursor: FollowRemoteCursor,
#[serde(flatten)]
pub follow_remote_window: FollowRemoteWindow,
#[serde(
default,
deserialize_with = "deserialize_string",
skip_serializing_if = "String::is_empty"
)]
pub keyboard_mode: String,
#[serde(flatten)]
pub view_only: ViewOnly,
#[serde(flatten)]
pub show_my_cursor: ShowMyCursor,
#[serde(flatten)]
pub sync_init_clipboard: SyncInitClipboard,
// Mouse wheel or touchpad scroll mode
#[serde(
default = "PeerConfig::default_reverse_mouse_wheel",
deserialize_with = "PeerConfig::deserialize_reverse_mouse_wheel",
skip_serializing_if = "String::is_empty"
)]
pub reverse_mouse_wheel: String,
#[serde(
default = "PeerConfig::default_displays_as_individual_windows",
deserialize_with = "PeerConfig::deserialize_displays_as_individual_windows",
skip_serializing_if = "String::is_empty"
)]
pub displays_as_individual_windows: String,
#[serde(
default = "PeerConfig::default_use_all_my_displays_for_the_remote_session",
deserialize_with = "PeerConfig::deserialize_use_all_my_displays_for_the_remote_session",
skip_serializing_if = "String::is_empty"
)]
pub use_all_my_displays_for_the_remote_session: String,
#[serde(
rename = "trackpad-speed",
default = "PeerConfig::default_trackpad_speed",
deserialize_with = "PeerConfig::deserialize_trackpad_speed"
)]
pub trackpad_speed: i32,
#[serde(
default,
deserialize_with = "deserialize_hashmap_resolutions",
skip_serializing_if = "HashMap::is_empty"
)]
pub custom_resolutions: HashMap<String, Resolution>,
// The other scalar value must before this
#[serde(
default,
deserialize_with = "deserialize_hashmap_string_string",
skip_serializing_if = "HashMap::is_empty"
)]
pub options: HashMap<String, String>, // not use delete to represent default values
// Various data for flutter ui
#[serde(default, deserialize_with = "deserialize_hashmap_string_string")]
pub ui_flutter: HashMap<String, String>,
#[serde(default)]
pub info: PeerInfoSerde,
#[serde(default)]
pub transfer: TransferSerde,
}
impl Default for PeerConfig {
fn default() -> Self {
Self {
password: Default::default(),
size: Default::default(),
size_ft: Default::default(),
size_pf: Default::default(),
view_style: Self::default_view_style(),
scroll_style: Self::default_scroll_style(),
edge_scroll_edge_thickness: Self::default_edge_scroll_edge_thickness(),
image_quality: Self::default_image_quality(),
custom_image_quality: Self::default_custom_image_quality(),
show_remote_cursor: Default::default(),
lock_after_session_end: Default::default(),
terminal_persistent: Default::default(),
privacy_mode: Default::default(),
allow_swap_key: Default::default(),
port_forwards: Default::default(),
direct_failures: Default::default(),
disable_audio: Default::default(),
disable_clipboard: Default::default(),
enable_file_copy_paste: Default::default(),
show_quality_monitor: Default::default(),
follow_remote_cursor: Default::default(),
follow_remote_window: Default::default(),
keyboard_mode: Default::default(),
view_only: Default::default(),
show_my_cursor: Default::default(),
reverse_mouse_wheel: Self::default_reverse_mouse_wheel(),
displays_as_individual_windows: Self::default_displays_as_individual_windows(),
use_all_my_displays_for_the_remote_session:
Self::default_use_all_my_displays_for_the_remote_session(),
trackpad_speed: Self::default_trackpad_speed(),
custom_resolutions: Default::default(),
options: Self::default_options(),
ui_flutter: Default::default(),
info: Default::default(),
transfer: Default::default(),
sync_init_clipboard: Default::default(),
}
}
}
#[derive(Debug, PartialEq, Default, Serialize, Deserialize, Clone)]
pub struct PeerInfoSerde {
#[serde(default, deserialize_with = "deserialize_string")]
pub username: String,
#[serde(default, deserialize_with = "deserialize_string")]
pub hostname: String,
#[serde(default, deserialize_with = "deserialize_string")]
pub platform: String,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct TransferSerde {
#[serde(default, deserialize_with = "deserialize_vec_string")]
pub write_jobs: Vec<String>,
#[serde(default, deserialize_with = "deserialize_vec_string")]
pub read_jobs: Vec<String>,
}
#[inline]
pub fn get_online_state() -> i64 {
*ONLINE.lock().unwrap().values().max().unwrap_or(&0)
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
fn patch(path: PathBuf) -> PathBuf {
if let Some(_tmp) = path.to_str() {
#[cfg(windows)]
return _tmp
.replace(
"system32\\config\\systemprofile",
"ServiceProfiles\\LocalService",
)
.into();
#[cfg(target_os = "macos")]
return _tmp.replace("Application Support", "Preferences").into();
#[cfg(target_os = "linux")]
{
if _tmp == "/root" {
if let Some(home_dir) = std::env::home_dir() {
return home_dir;
}
}
}
}
path
}
impl Config2 {
fn load() -> Config2 {
let mut config = Config::load_::<Config2>("2");
let mut store = false;
if let Some(mut socks) = config.socks {
let (password, _, store2) =
decrypt_str_or_original(&socks.password, PASSWORD_ENC_VERSION);
socks.password = password;
config.socks = Some(socks);
store |= store2;
}
let (unlock_pin, _, store2) =
decrypt_str_or_original(&config.unlock_pin, PASSWORD_ENC_VERSION);
config.unlock_pin = unlock_pin;
store |= store2;
if store {
config.store();
}
config
}
pub fn file() -> PathBuf {
Config::file_("2")
}
fn store(&self) {
let mut config = self.clone();
if let Some(mut socks) = config.socks {
socks.password =
encrypt_str_or_original(&socks.password, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN);
config.socks = Some(socks);
}
config.unlock_pin =
encrypt_str_or_original(&config.unlock_pin, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN);
Config::store_(&config, "2");
}
pub fn get() -> Config2 {
return CONFIG2.read().unwrap().clone();
}
pub fn set(cfg: Config2) -> bool {
let mut lock = CONFIG2.write().unwrap();
if *lock == cfg {
return false;
}
*lock = cfg;
lock.store();
true
}
}
pub fn load_path<T: serde::Serialize + serde::de::DeserializeOwned + Default + std::fmt::Debug>(
file: PathBuf,
) -> T {
let cfg = match confy::load_path(&file) {
Ok(config) => config,
Err(err) => {
if let confy::ConfyError::GeneralLoadError(err) = &err {
if err.kind() == std::io::ErrorKind::NotFound {
return T::default();
}
}
log::error!("Failed to load config '{}': {}", file.display(), err);
T::default()
}
};
cfg
}
#[inline]
pub fn store_path<T: serde::Serialize>(path: PathBuf, cfg: T) -> crate::ResultType<()> {
#[cfg(not(windows))]
{
use std::os::unix::fs::PermissionsExt;
Ok(confy::store_path_perms(
path,
cfg,
fs::Permissions::from_mode(0o600),
)?)
}
#[cfg(windows)]
{
Ok(confy::store_path(path, cfg)?)
}
}
impl Config {
fn load_<T: serde::Serialize + serde::de::DeserializeOwned + Default + std::fmt::Debug>(
suffix: &str,
) -> T {
let file = Self::file_(suffix);
let cfg = load_path(file);
if suffix.is_empty() {
log::trace!("{:?}", cfg);
}
cfg
}
fn store_<T: serde::Serialize>(config: &T, suffix: &str) {
let file = Self::file_(suffix);
if let Err(err) = store_path(file, config) {
log::error!("Failed to store {suffix} config: {err}");
}
}
fn load() -> Config {
let mut config = Config::load_::<Config>("");
let mut store = false;
let (password, _, store1) = decrypt_str_or_original(&config.password, PASSWORD_ENC_VERSION);
config.password = password;
store |= store1;
let mut id_valid = false;
let (id, encrypted, store2) = decrypt_str_or_original(&config.enc_id, PASSWORD_ENC_VERSION);
if encrypted {
config.id = id;
id_valid = true;
store |= store2;
} else if
// Comment out for forward compatible
// crate::get_modified_time(&Self::file_(""))
// .checked_sub(std::time::Duration::from_secs(30)) // allow modification during installation
// .unwrap_or_else(crate::get_exe_time)
// < crate::get_exe_time()
// &&
!config.id.is_empty()
&& config.enc_id.is_empty()
&& !decrypt_str_or_original(&config.id, PASSWORD_ENC_VERSION).1
{
id_valid = true;
store = true;
}
if !id_valid {
for _ in 0..3 {
if let Some(id) = Config::gen_id() {
config.id = id;
store = true;
break;
} else {
log::error!("Failed to generate new id");
}
}
}
if store {
config.store();
}
config
}
fn store(&self) {
let mut config = self.clone();
config.password =
encrypt_str_or_original(&config.password, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN);
config.enc_id = encrypt_str_or_original(&config.id, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN);
config.id = "".to_owned();
Config::store_(&config, "");
}
pub fn file() -> PathBuf {
Self::file_("")
}
fn file_(suffix: &str) -> PathBuf {
let name = format!("{}{}", *APP_NAME.read().unwrap(), suffix);
Config::with_extension(Self::path(name))
}
pub fn is_empty(&self) -> bool {
(self.id.is_empty() && self.enc_id.is_empty()) || self.key_pair.0.is_empty()
}
pub fn get_home() -> PathBuf {
#[cfg(any(target_os = "android", target_os = "ios"))]
return PathBuf::from(APP_HOME_DIR.read().unwrap().as_str());
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{
if let Some(path) = dirs_next::home_dir() {
patch(path)
} else if let Ok(path) = std::env::current_dir() {
path
} else {
std::env::temp_dir()
}
}
}
pub fn path<P: AsRef<Path>>(p: P) -> PathBuf {
#[cfg(any(target_os = "android", target_os = "ios"))]
{
let mut path: PathBuf = APP_DIR.read().unwrap().clone().into();
path.push(p);
return path;
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{
#[cfg(not(target_os = "macos"))]
let org = "".to_owned();
#[cfg(target_os = "macos")]
let org = ORG.read().unwrap().clone();
// /var/root for root
if let Some(project) =
directories_next::ProjectDirs::from("", &org, &APP_NAME.read().unwrap())
{
let mut path = patch(project.config_dir().to_path_buf());
path.push(p);
return path;
}
"".into()
}
}
#[allow(unreachable_code)]
pub fn log_path() -> PathBuf {
#[cfg(target_os = "macos")]
{
if let Some(path) = dirs_next::home_dir().as_mut() {
path.push(format!("Library/Logs/{}", *APP_NAME.read().unwrap()));
return path.clone();
}
}
#[cfg(target_os = "linux")]
{
let mut path = Self::get_home();
path.push(format!(".local/share/logs/{}", *APP_NAME.read().unwrap()));
std::fs::create_dir_all(&path).ok();
return path;
}
#[cfg(target_os = "android")]
{
let mut path = Self::get_home();
path.push(format!("{}/Logs", *APP_NAME.read().unwrap()));
std::fs::create_dir_all(&path).ok();
return path;
}
if let Some(path) = Self::path("").parent() {
let mut path: PathBuf = path.into();
path.push("log");
return path;
}
"".into()
}
pub fn ipc_path(postfix: &str) -> String {
#[cfg(windows)]
{
// \\ServerName\pipe\PipeName
// where ServerName is either the name of a remote computer or a period, to specify the local computer.
// https://docs.microsoft.com/en-us/windows/win32/ipc/pipe-names
format!(
"\\\\.\\pipe\\{}\\query{}",
*APP_NAME.read().unwrap(),
postfix
)
}
#[cfg(not(windows))]
{
use std::os::unix::fs::PermissionsExt;
#[cfg(target_os = "android")]
let mut path: PathBuf =
format!("{}/{}", *APP_DIR.read().unwrap(), *APP_NAME.read().unwrap()).into();
#[cfg(not(target_os = "android"))]
let mut path: PathBuf = format!("/tmp/{}", *APP_NAME.read().unwrap()).into();
fs::create_dir(&path).ok();
fs::set_permissions(&path, fs::Permissions::from_mode(0o0777)).ok();
path.push(format!("ipc{postfix}"));
path.to_str().unwrap_or("").to_owned()
}
}
pub fn icon_path() -> PathBuf {
let mut path = Self::path("icons");
if fs::create_dir_all(&path).is_err() {
path = std::env::temp_dir();
}
path
}
#[inline]
pub fn get_any_listen_addr(is_ipv4: bool) -> SocketAddr {
if is_ipv4 {
SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)
} else {
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0)
}
}
pub fn get_rendezvous_server() -> String {
let mut rendezvous_server = EXE_RENDEZVOUS_SERVER.read().unwrap().clone();
if rendezvous_server.is_empty() {
rendezvous_server = Self::get_option("custom-rendezvous-server");
}
if rendezvous_server.is_empty() {
rendezvous_server = PROD_RENDEZVOUS_SERVER.read().unwrap().clone();
}
if rendezvous_server.is_empty() {
rendezvous_server = CONFIG2.read().unwrap().rendezvous_server.clone();
}
if rendezvous_server.is_empty() {
rendezvous_server = Self::get_rendezvous_servers()
.drain(..)
.next()
.unwrap_or_default();
}
if !rendezvous_server.contains(':') {
rendezvous_server = format!("{rendezvous_server}:{RENDEZVOUS_PORT}");
}
rendezvous_server
}
pub fn get_rendezvous_servers() -> Vec<String> {
let s = EXE_RENDEZVOUS_SERVER.read().unwrap().clone();
if !s.is_empty() {
return vec![s];
}
let s = Self::get_option("custom-rendezvous-server");
if !s.is_empty() {
return vec![s];
}
let s = PROD_RENDEZVOUS_SERVER.read().unwrap().clone();
if !s.is_empty() {
return vec![s];
}
let serial_obsolute = CONFIG2.read().unwrap().serial > SERIAL;
if serial_obsolute {
let ss: Vec<String> = Self::get_option("rendezvous-servers")
.split(',')
.filter(|x| x.contains('.'))
.map(|x| x.to_owned())
.collect();
if !ss.is_empty() {
return ss;
}
}
return RENDEZVOUS_SERVERS.iter().map(|x| x.to_string()).collect();
}
pub fn reset_online() {
*ONLINE.lock().unwrap() = Default::default();
}
pub fn update_latency(host: &str, latency: i64) {
ONLINE.lock().unwrap().insert(host.to_owned(), latency);
let mut host = "".to_owned();
let mut delay = i64::MAX;
for (tmp_host, tmp_delay) in ONLINE.lock().unwrap().iter() {
if tmp_delay > &0 && tmp_delay < &delay {
delay = *tmp_delay;
host = tmp_host.to_string();
}
}
if !host.is_empty() {
let mut config = CONFIG2.write().unwrap();
if host != config.rendezvous_server {
log::debug!("Update rendezvous_server in config to {}", host);
log::debug!("{:?}", *ONLINE.lock().unwrap());
config.rendezvous_server = host;
config.store();
}
}
}
pub fn set_id(id: &str) {
let mut config = CONFIG.write().unwrap();
if id == config.id {
return;
}
config.id = id.into();
config.store();
}
pub fn set_nat_type(nat_type: i32) {
let mut config = CONFIG2.write().unwrap();
if nat_type == config.nat_type {
return;
}
config.nat_type = nat_type;
config.store();
}
pub fn get_nat_type() -> i32 {
CONFIG2.read().unwrap().nat_type
}
pub fn set_serial(serial: i32) {
let mut config = CONFIG2.write().unwrap();
if serial == config.serial {
return;
}
config.serial = serial;
config.store();
}
pub fn get_serial() -> i32 {
std::cmp::max(CONFIG2.read().unwrap().serial, SERIAL)
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn gen_id() -> Option<String> {
Self::get_auto_id()
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
fn gen_id() -> Option<String> {
let hostname_as_id = BUILTIN_SETTINGS
.read()
.unwrap()
.get(keys::OPTION_ALLOW_HOSTNAME_AS_ID)
.map(|v| option2bool(keys::OPTION_ALLOW_HOSTNAME_AS_ID, v))
.unwrap_or(false);
if hostname_as_id {
match whoami::fallible::hostname() {
Ok(h) => Some(h.replace(" ", "-")),
Err(e) => {
log::warn!("Failed to get hostname, \"{}\", fallback to auto id", e);
Self::get_auto_id()
}
}
} else {
Self::get_auto_id()
}
}
fn get_auto_id() -> Option<String> {
#[cfg(any(target_os = "android", target_os = "ios"))]
{
return Some(
rand::thread_rng()
.gen_range(1_000_000_000..2_000_000_000)
.to_string(),
);
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{
let mut id = 0u32;
if let Ok(Some(ma)) = mac_address::get_mac_address() {
for x in &ma.bytes()[2..] {
id = (id << 8) | (*x as u32);
}
id &= 0x1FFFFFFF;
Some(id.to_string())
} else {
None
}
}
}
pub fn get_auto_password(length: usize) -> String {
Self::get_auto_password_with_chars(length, CHARS)
}
pub fn get_auto_numeric_password(length: usize) -> String {
Self::get_auto_password_with_chars(length, NUM_CHARS)
}
fn get_auto_password_with_chars(length: usize, chars: &[char]) -> String {
let mut rng = rand::thread_rng();
(0..length)
.map(|_| chars[rng.gen::<usize>() % chars.len()])
.collect()
}
pub fn get_key_confirmed() -> bool {
CONFIG.read().unwrap().key_confirmed
}
pub fn set_key_confirmed(v: bool) {
let mut config = CONFIG.write().unwrap();
if config.key_confirmed == v {
return;
}
config.key_confirmed = v;
if !v {
config.keys_confirmed = Default::default();
}
config.store();
}
pub fn get_host_key_confirmed(host: &str) -> bool {
matches!(CONFIG.read().unwrap().keys_confirmed.get(host), Some(true))
}
pub fn set_host_key_confirmed(host: &str, v: bool) {
if Self::get_host_key_confirmed(host) == v {
return;
}
let mut config = CONFIG.write().unwrap();
config.keys_confirmed.insert(host.to_owned(), v);
config.store();
}
pub fn get_key_pair() -> KeyPair {
// lock here to make sure no gen_keypair more than once
// no use of CONFIG directly here to ensure no recursive calling in Config::load because of password dec which calling this function
let mut lock = KEY_PAIR.lock().unwrap();
if let Some(p) = lock.as_ref() {
return p.clone();
}
let mut config = Config::load_::<Config>("");
if config.key_pair.0.is_empty() {
log::info!("Generated new keypair for id: {}", config.id);
let (pk, sk) = sign::gen_keypair();
let key_pair = (sk.0.to_vec(), pk.0.into());
config.key_pair = key_pair.clone();
std::thread::spawn(|| {
let mut config = CONFIG.write().unwrap();
config.key_pair = key_pair;
config.store();
});
}
*lock = Some(config.key_pair.clone());
config.key_pair
}
pub fn no_register_device() -> bool {
BUILTIN_SETTINGS
.read()
.unwrap()
.get(keys::OPTION_REGISTER_DEVICE)
.map(|v| v == "N")
.unwrap_or(false)
}
pub fn get_id() -> String {
let mut id = CONFIG.read().unwrap().id.clone();
if id.is_empty() {
if let Some(tmp) = Config::gen_id() {
id = tmp;
Config::set_id(&id);
}
}
id
}
pub fn get_id_or(b: String) -> String {
let a = CONFIG.read().unwrap().id.clone();
if a.is_empty() {
b
} else {
a
}
}
pub fn get_options() -> HashMap<String, String> {
let mut res = DEFAULT_SETTINGS.read().unwrap().clone();
res.extend(CONFIG2.read().unwrap().options.clone());
res.extend(OVERWRITE_SETTINGS.read().unwrap().clone());
res
}