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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using Jellyfin.Networking.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Networking.Manager
{
/// <summary>
/// Class to take care of network interface management.
/// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>.
/// </summary>
public class NetworkManager : INetworkManager, IDisposable
{
/// <summary>
/// Contains the description of the interface along with its index.
/// </summary>
private readonly Dictionary<string, int> _interfaceNames;
/// <summary>
/// Threading lock for network properties.
/// </summary>
private readonly object _intLock = new object();
/// <summary>
/// List of all interface addresses and masks.
/// </summary>
private readonly Collection<IPObject> _interfaceAddresses;
/// <summary>
/// List of all interface MAC addresses.
/// </summary>
private readonly List<PhysicalAddress> _macAddresses;
private readonly ILogger<NetworkManager> _logger;
private readonly IConfigurationManager _configurationManager;
private readonly object _eventFireLock;
/// <summary>
/// Holds the bind address overrides.
/// </summary>
private readonly Dictionary<IPNetAddress, string> _publishedServerUrls;
/// <summary>
/// Used to stop "event-racing conditions".
/// </summary>
private bool _eventfire;
/// <summary>
/// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>)
/// or internal interface network subnets if undefined by user.
/// </summary>
private Collection<IPObject> _lanSubnets;
/// <summary>
/// User defined list of subnets to excluded from the LAN.
/// </summary>
private Collection<IPObject> _excludedSubnets;
/// <summary>
/// List of interface addresses to bind the WS.
/// </summary>
private Collection<IPObject> _bindAddresses;
/// <summary>
/// List of interface addresses to exclude from bind.
/// </summary>
private Collection<IPObject> _bindExclusions;
/// <summary>
/// Caches list of all internal filtered interface addresses and masks.
/// </summary>
private Collection<IPObject> _internalInterfaces;
/// <summary>
/// Flag set when no custom LAN has been defined in the configuration.
/// </summary>
private bool _usingPrivateAddresses;
/// <summary>
/// True if this object is disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="NetworkManager"/> class.
/// </summary>
/// <param name="configurationManager">IServerConfigurationManager instance.</param>
/// <param name="logger">Logger to use for messages.</param>
#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
_interfaceAddresses = new Collection<IPObject>();
_macAddresses = new List<PhysicalAddress>();
_interfaceNames = new Dictionary<string, int>();
_publishedServerUrls = new Dictionary<IPNetAddress, string>();
_eventFireLock = new object();
UpdateSettings(_configurationManager.GetNetworkConfiguration());
NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
_configurationManager.NamedConfigurationUpdated += ConfigurationUpdated;
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
/// <summary>
/// Event triggered on network changes.
/// </summary>
public event EventHandler? NetworkChanged;
/// <summary>
/// Gets or sets a value indicating whether testing is taking place.
/// </summary>
public static string MockNetworkSettings { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether IP6 is enabled.
/// </summary>
public bool IsIP6Enabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether IP4 is enabled.
/// </summary>
public bool IsIP4Enabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the system has IP4 is enabled.
/// </summary>
public bool SystemIP4Enabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the system has IP6 is enabled.
/// </summary>
public bool SystemIP6Enabled { get; set; }
/// <inheritdoc/>
public Collection<IPObject> RemoteAddressFilter { get; private set; }
/// <summary>
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
/// </summary>
public bool TrustAllIP6Interfaces { get; internal set; }
/// <summary>
/// Gets the Published server override list.
/// </summary>
public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls;
/// <summary>
/// Creates a new network collection.
/// </summary>
/// <param name="source">Items to assign the collection, or null.</param>
/// <returns>The collection created.</returns>
public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null)
{
var result = new Collection<IPObject>();
if (source != null)
{
foreach (var item in source)
{
result.AddItem(item);
}
}
return result;
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <inheritdoc/>
public IReadOnlyCollection<PhysicalAddress> GetMacAddresses()
{
// Populated in construction - so always has values.
return _macAddresses;
}
/// <summary>
/// REMOVE after debugging.
/// </summary>
/// <param name="msg">Message.</param>
public void Log(string msg)
{
_logger.LogInformation(msg);
}
/// <inheritdoc/>
public bool IsGatewayInterface(IPObject? addressObj)
{
var address = addressObj?.Address ?? IPAddress.None;
return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0);
}
/// <inheritdoc/>
public bool IsGatewayInterface(IPAddress? addressObj)
{
return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0);
}
/// <inheritdoc/>
public Collection<IPObject> GetLoopbacks()
{
Collection<IPObject> nc = new Collection<IPObject>();
if (IsIP4Enabled)
{
nc.AddItem(IPAddress.Loopback);
}
if (IsIP6Enabled)
{
nc.AddItem(IPAddress.IPv6Loopback);
}
return nc;
}
/// <inheritdoc/>
public bool IsExcluded(IPAddress ip)
{
return _excludedSubnets.ContainsAddress(ip);
}
/// <inheritdoc/>
public bool IsExcluded(EndPoint ip)
{
return ip != null && IsExcluded(((IPEndPoint)ip).Address);
}
/// <inheritdoc/>
public Collection<IPObject> CreateIPCollection(string[] values, bool negated = false)
{
Collection<IPObject> col = new Collection<IPObject>();
if (values == null)
{
return col;
}
for (int a = 0; a < values.Length; a++)
{
string v = values[a].Trim();
try
{
if (v.StartsWith('!'))
{
if (negated)
{
AddToCollection(col, v[1..]);
}
}
else if (!negated)
{
AddToCollection(col, v);
}
}
catch (ArgumentException e)
{
_logger.LogWarning(e, "Ignoring LAN value {Value}.", v);
}
}
return col;
}
/// <inheritdoc/>
public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false)
{
int count = _bindAddresses.Count;
if (count == 0)
{
if (_bindExclusions.Count > 0)
{
// Return all the interfaces except the ones specifically excluded.
return _interfaceAddresses.Exclude(_bindExclusions);
}
if (individualInterfaces)
{
return new Collection<IPObject>(_interfaceAddresses);
}
// No bind address and no exclusions, so listen on all interfaces.
Collection<IPObject> result = new Collection<IPObject>();
if (IsIP4Enabled)
{
result.AddItem(IPAddress.Any);
}
if (IsIP6Enabled)
{
result.AddItem(IPAddress.IPv6Any);
}
return result;
}
// Remove any excluded bind interfaces.
return _bindAddresses.Exclude(_bindExclusions);
}
/// <inheritdoc/>
public string GetBindInterface(string source, out int? port)
{
if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host))
{
return GetBindInterface(host, out port);
}
return GetBindInterface(IPHost.None, out port);
}
/// <inheritdoc/>
public string GetBindInterface(IPAddress source, out int? port)
{
return GetBindInterface(new IPNetAddress(source), out port);
}
/// <inheritdoc/>
public string GetBindInterface(HttpRequest source, out int? port)
{
string result;
if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host))
{
result = GetBindInterface(host, out port);
port ??= source.Host.Port;
}
else
{
result = GetBindInterface(IPNetAddress.None, out port);
port ??= source?.Host.Port;
}
return result;
}
/// <inheritdoc/>
public string GetBindInterface(IPObject source, out int? port)
{
port = null;
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
// Do we have a source?
bool haveSource = !source.Address.Equals(IPAddress.None);
bool isExternal = false;
if (haveSource)
{
if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
{
_logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
}
if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
{
_logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
}
isExternal = !IsInLocalNetwork(source);
if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
{
_logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
return res;
}
}
_logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal);
// No preference given, so move on to bind addresses.
if (MatchesBindInterface(source, isExternal, out string result))
{
return result;
}
if (isExternal && MatchesExternalInterface(source, out result))
{
return result;
}
// Get the first LAN interface address that isn't a loopback.
var interfaces = CreateCollection(_interfaceAddresses
.Exclude(_bindExclusions)
.Where(p => IsInLocalNetwork(p))
.OrderBy(p => p.Tag));
if (interfaces.Count > 0)
{
if (haveSource)
{
// Does the request originate in one of the interface subnets?
// (For systems with multiple internal network cards, and multiple subnets)
foreach (var intf in interfaces)
{
if (intf.Contains(source))
{
result = FormatIP6String(intf.Address);
_logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result);
return result;
}
}
}
result = FormatIP6String(interfaces.First().Address);
_logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result);
return result;
}
// There isn't any others, so we'll use the loopback.
result = IsIP6Enabled ? "::" : "127.0.0.1";
_logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result);
return result;
}
/// <inheritdoc/>
public Collection<IPObject> GetInternalBindAddresses()
{
int count = _bindAddresses.Count;
if (count == 0)
{
if (_bindExclusions.Count > 0)
{
// Return all the internal interfaces except the ones excluded.
return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)));
}
// No bind address, so return all internal interfaces.
return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback()));
}
return new Collection<IPObject>(_bindAddresses);
}
/// <inheritdoc/>
public bool IsInLocalNetwork(IPObject address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Equals(IPAddress.None))
{
return false;
}
// See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
{
return true;
}
// As private addresses can be redefined by Configuration.LocalNetworkAddresses
return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address);
}
/// <inheritdoc/>
public bool IsInLocalNetwork(string address)
{
if (IPHost.TryParse(address, out IPHost ep))
{
return _lanSubnets.ContainsAddress(ep) && !_excludedSubnets.ContainsAddress(ep);
}
return false;
}
/// <inheritdoc/>
public bool IsInLocalNetwork(IPAddress address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
// See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
{
return true;
}
// As private addresses can be redefined by Configuration.LocalNetworkAddresses
return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address);
}
/// <inheritdoc/>
public bool IsPrivateAddressRange(IPObject address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
// See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
{
return true;
}
else
{
return address.IsPrivateAddressRange();
}
}
/// <inheritdoc/>
public bool IsExcludedInterface(IPAddress address)
{
return _bindExclusions.ContainsAddress(address);
}
/// <inheritdoc/>
public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null)
{
if (filter == null)
{
return _lanSubnets.Exclude(_excludedSubnets).AsNetworks();
}
return _lanSubnets.Exclude(filter);
}
/// <inheritdoc/>
public bool IsValidInterfaceAddress(IPAddress address)
{
return _interfaceAddresses.ContainsAddress(address);
}
/// <inheritdoc/>
public bool TryParseInterface(string token, out Collection<IPObject>? result)
{
result = null;
if (string.IsNullOrEmpty(token))
{
return false;
}
if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
{
result = new Collection<IPObject>();
_logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
// Replace interface tags with the interface IP's.
foreach (IPNetAddress iface in _interfaceAddresses)
{
if (Math.Abs(iface.Tag) == index
&& ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
|| (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
{
result.AddItem(iface);
}
}
return true;
}
return false;
}
/// <summary>
/// Reloads all settings and re-initialises the instance.
/// </summary>
/// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param>
public void UpdateSettings(object configuration)
{
NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
if (!IsIP6Enabled && !IsIP4Enabled)
{
_logger.LogError("IPv4 and IPv6 cannot both be disabled.");
IsIP4Enabled = true;
}
TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
// UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding;
if (string.IsNullOrEmpty(MockNetworkSettings))
{
InitialiseInterfaces();
}
else // Used in testing only.
{
// Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway.
var interfaceList = MockNetworkSettings.Split(':');
foreach (var details in interfaceList)
{
var parts = details.Split(',');
var address = IPNetAddress.Parse(parts[0]);
var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
address.Tag = index;
_interfaceAddresses.AddItem(address);
_interfaceNames.Add(parts[2], Math.Abs(index));
}
}
InitialiseLAN(config);
InitialiseBind(config);
InitialiseRemote(config);
InitialiseOverrides(config);
}
/// <summary>
/// Protected implementation of Dispose pattern.
/// </summary>
/// <param name="disposing"><c>True</c> to dispose the managed state.</param>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated;
NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged;
}
_disposed = true;
}
}
/// <summary>
/// Tries to identify the string and return an object of that class.
/// </summary>
/// <param name="addr">String to parse.</param>
/// <param name="result">IPObject to return.</param>
/// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns>
private static bool TryParse(string addr, out IPObject result)
{
if (!string.IsNullOrEmpty(addr))
{
// Is it an IP address
if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
{
result = nw;
return true;
}
if (IPHost.TryParse(addr, out IPHost h))
{
result = h;
return true;
}
}
result = IPNetAddress.None;
return false;
}
/// <summary>
/// Converts an IPAddress into a string.
/// Ipv6 addresses are returned in [ ], with their scope removed.
/// </summary>
/// <param name="address">Address to convert.</param>
/// <returns>URI safe conversion of the address.</returns>
private static string FormatIP6String(IPAddress address)
{
var str = address.ToString();
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase);
if (i != -1)
{
str = str.Substring(0, i);
}
return $"[{str}]";
}
return str;
}
private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
{
if (evt.Key.Equals("network", StringComparison.Ordinal))
{
UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
}
}
/// <summary>
/// Checks the string to see if it matches any interface names.
/// </summary>
/// <param name="token">String to check.</param>
/// <param name="index">Interface index number.</param>
/// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns>
private bool IsInterface(string token, out int index)
{
index = -1;
// Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
// Null check required here for automated testing.
if (_interfaceNames != null && token.Length > 1)
{
bool partial = token[^1] == '*';
if (partial)
{
token = token[0..^1];
}
foreach ((string interfc, int interfcIndex) in _interfaceNames)
{
if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase))
|| (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
{
index = interfcIndex;
return true;
}
}
}
return false;
}
/// <summary>
/// Parses a string and adds it into the collection, replacing any interface references.
/// </summary>
/// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param>
/// <param name="token">String value to parse.</param>
private void AddToCollection(Collection<IPObject> col, string token)
{
// Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
// Null check required here for automated testing.
if (IsInterface(token, out int index))
{
_logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
// Replace interface tags with the interface IP's.
foreach (IPNetAddress iface in _interfaceAddresses)
{
if (Math.Abs(iface.Tag) == index
&& ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
|| (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
{
col.AddItem(iface);
}
}
}
else if (TryParse(token, out IPObject obj))
{
// Expand if the ip address is "any".
if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled)
|| (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled))
{
foreach (IPNetAddress iface in _interfaceAddresses)
{
if (obj.AddressFamily == iface.AddressFamily)
{
col.AddItem(iface);
}
}
}
else if (!IsIP6Enabled)
{
// Remove IP6 addresses from multi-homed IPHosts.
obj.Remove(AddressFamily.InterNetworkV6);
if (!obj.IsIP6())
{
col.AddItem(obj);
}
}
else if (!IsIP4Enabled)
{
// Remove IP4 addresses from multi-homed IPHosts.
obj.Remove(AddressFamily.InterNetwork);
if (obj.IsIP6())
{
col.AddItem(obj);
}
}
else
{
col.AddItem(obj);
}
}
else
{
_logger.LogDebug("Invalid or unknown object {Token}.", token);
}
}
/// <summary>
/// Handler for network change events.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param>
private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
{
_logger.LogDebug("Network availability changed.");
OnNetworkChanged();
}
/// <summary>
/// Handler for network change events.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">An <see cref="EventArgs"/>.</param>
private void OnNetworkAddressChanged(object? sender, EventArgs e)
{
_logger.LogDebug("Network address change detected.");
OnNetworkChanged();
}
/// <summary>
/// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task OnNetworkChangeAsync()
{
try
{
await Task.Delay(2000).ConfigureAwait(false);
InitialiseInterfaces();
// Recalculate LAN caches.
InitialiseLAN(_configurationManager.GetNetworkConfiguration());
NetworkChanged?.Invoke(this, EventArgs.Empty);
}
finally
{
_eventfire = false;
}
}
/// <summary>
/// Triggers our event, and re-loads interface information.
/// </summary>
private void OnNetworkChanged()
{
lock (_eventFireLock)
{
if (!_eventfire)
{
_logger.LogDebug("Network Address Change Event.");
// As network events tend to fire one after the other only fire once every second.
_eventfire = true;
OnNetworkChangeAsync().GetAwaiter().GetResult();
}
}
}
/// <summary>
/// Parses the user defined overrides into the dictionary object.
/// Overrides are the equivalent of localised publishedServerUrl, enabling
/// different addresses to be advertised over different subnets.
/// format is subnet=ipaddress|host|uri
/// when subnet = 0.0.0.0, any external address matches.
/// </summary>
private void InitialiseOverrides(NetworkConfiguration config)
{
lock (_intLock)
{
_publishedServerUrls.Clear();
string[] overrides = config.PublishedServerUriBySubnet;
if (overrides == null)
{
return;
}
foreach (var entry in overrides)
{
var parts = entry.Split('=');
if (parts.Length != 2)
{
_logger.LogError("Unable to parse bind override: {Entry}", entry);
}
else
{
var replacement = parts[1].Trim();
if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase))
{
_publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
}
else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
{
_publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
}
else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null)
{
foreach (IPNetAddress na in addresses)
{
_publishedServerUrls[na] = replacement;
}
}
else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result))
{
_publishedServerUrls[result] = replacement;
}
else
{
_logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]);
}
}
}
}
}
/// <summary>
/// Initialises the network bind addresses.
/// </summary>
private void InitialiseBind(NetworkConfiguration config)
{
lock (_intLock)
{
string[] lanAddresses = config.LocalNetworkAddresses;
// Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
if (config.IgnoreVirtualInterfaces)
{
var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',');
var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length];
Array.Copy(lanAddresses, newList, lanAddresses.Length);
Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length);
lanAddresses = newList;
}
// Read and parse bind addresses and exclusions, removing ones that don't exist.
_bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses);
_bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses);
_logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString());
_logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
}
}
/// <summary>
/// Initialises the remote address values.
/// </summary>
private void InitialiseRemote(NetworkConfiguration config)
{
lock (_intLock)
{
RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
}
}
/// <summary>
/// Initialises internal LAN cache settings.
/// </summary>
private void InitialiseLAN(NetworkConfiguration config)
{
lock (_intLock)
{
_logger.LogDebug("Refreshing LAN information.");
// Get configuration options.
string[] subnets = config.LocalNetworkSubnets;
// Create lists from user settings.
_lanSubnets = CreateIPCollection(subnets);
_excludedSubnets = CreateIPCollection(subnets, true).AsNetworks();
// If no LAN addresses are specified - all private subnets are deemed to be the LAN
_usingPrivateAddresses = _lanSubnets.Count == 0;
// NOTE: The order of the commands generating the collection in this statement matters.
// Altering the order will cause the collections to be created incorrectly.
if (_usingPrivateAddresses)
{
_logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
// Internal interfaces must be private and not excluded.
_internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
// Subnets are the same as the calculated internal interface.
_lanSubnets = new Collection<IPObject>();
// We must listen on loopback for LiveTV to function regardless of the settings.
if (IsIP6Enabled)
{
_lanSubnets.AddItem(IPNetAddress.IP6Loopback);
_lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA
_lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local
}
if (IsIP4Enabled)
{
_lanSubnets.AddItem(IPNetAddress.IP4Loopback);
_lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8"));
_lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12"));
_lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16"));
}
}
else
{
// We must listen on loopback for LiveTV to function regardless of the settings.
if (IsIP6Enabled)
{
_lanSubnets.AddItem(IPNetAddress.IP6Loopback);
}
if (IsIP4Enabled)
{
_lanSubnets.AddItem(IPNetAddress.IP4Loopback);
}
// Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
_internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i)));
}
_logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString());
_logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString());
_logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks().AsString());
}
}
/// <summary>
/// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
/// Generate a list of all active mac addresses that aren't loopback addresses.
/// </summary>
private void InitialiseInterfaces()
{
lock (_intLock)
{
_logger.LogDebug("Refreshing interfaces.");
_interfaceNames.Clear();
_interfaceAddresses.Clear();
_macAddresses.Clear();
try
{
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
.Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
foreach (NetworkInterface adapter in nics)
{
try
{
IPInterfaceProperties ipProperties = adapter.GetIPProperties();
PhysicalAddress mac = adapter.GetPhysicalAddress();
// populate mac list
if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None)
{
_macAddresses.Add(mac);
}
// populate interface address list
foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
{
if (info.Address.AddressFamily == AddressFamily.InterNetwork)
{
SystemIP4Enabled = true;
if (IsIP4Enabled)
{
IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask))
{
// Keep the number of gateways on this interface, along with its index.
Tag = ipProperties.GetIPv4Properties().Index
};
int tag = nw.Tag;
if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
{
// -ve Tags signify the interface has a gateway.
nw.Tag *= -1;
}
_interfaceAddresses.AddItem(nw);
// Store interface name so we can use the name in Collections.
_interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
_interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
}
}
else if (info.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
SystemIP6Enabled = true;
if (IsIP6Enabled)
{
IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
{
// Keep the number of gateways on this interface, along with its index.
Tag = ipProperties.GetIPv6Properties().Index
};
int tag = nw.Tag;
if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
{
// -ve Tags signify the interface has a gateway.
nw.Tag *= -1;
}
_interfaceAddresses.AddItem(nw);
// Store interface name so we can use the name in Collections.
_interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
_interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
}
}
}
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
// Ignore error, and attempt to continue.
_logger.LogError(ex, "Error encountered parsing interfaces.");
}
#pragma warning restore CA1031 // Do not catch general exception types
}
_logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
_logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString());
// If for some reason we don't have an interface info, resolve our DNS name.
if (_interfaceAddresses.Count == 0)
{
_logger.LogError("No interfaces information available. Resolving DNS name.");
IPHost host = new IPHost(Dns.GetHostName());
foreach (var a in host.GetAddresses())
{
_interfaceAddresses.AddItem(a);
}
if (_interfaceAddresses.Count == 0)
{
_logger.LogWarning("No interfaces information available. Using loopback.");
// Last ditch attempt - use loopback address.
_interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
if (IsIP6Enabled)
{
_interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
}
}
}
}
catch (NetworkInformationException ex)
{
_logger.LogError(ex, "Error in InitialiseInterfaces.");
}
}
}
/// <summary>
/// Attempts to match the source against a user defined bind interface.
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
/// <param name="bindPreference">The published server url that matches the source address.</param>
/// <param name="port">The resultant port, if one exists.</param>
/// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port)
{
bindPreference = string.Empty;
port = null;
// Check for user override.
foreach (var addr in _publishedServerUrls)
{
// Remaining. Match anything.
if (addr.Key.Address.Equals(IPAddress.Broadcast))
{
bindPreference = addr.Value;
break;
}
else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet)
{
// External.
bindPreference = addr.Value;
break;
}
else if (addr.Key.Contains(source))
{
// Match ip address.
bindPreference = addr.Value;
break;
}
}
if (string.IsNullOrEmpty(bindPreference))
{
return false;
}
// Has it got a port defined?
var parts = bindPreference.Split(':');
if (parts.Length > 1)
{
if (int.TryParse(parts[1], out int p))
{
bindPreference = parts[0];
port = p;
}
}
return true;
}
/// <summary>
/// Attempts to match the source against a user defined bind interface.
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
/// <param name="result">The result, if a match is found.</param>
/// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result)
{
result = string.Empty;
var addresses = _bindAddresses.Exclude(_bindExclusions);
int count = addresses.Count;
if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
{
// Ignore IPAny addresses.
count = 0;
}
if (count != 0)
{
// Check to see if any of the bind interfaces are in the same subnet.
IPAddress? defaultGateway = null;
IPAddress? bindAddress = null;
if (isInExternalSubnet)
{
// Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
foreach (var addr in addresses.OrderBy(p => p.Tag))
{
if (defaultGateway == null && !IsInLocalNetwork(addr))
{
defaultGateway = addr.Address;
}
if (bindAddress == null && addr.Contains(source))
{
bindAddress = addr.Address;
}
if (defaultGateway != null && bindAddress != null)
{
break;
}
}
}
else
{
// Look for the best internal address.
bindAddress = addresses
.Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None)))
.OrderBy(p => p.Tag)
.FirstOrDefault()?.Address;
}
if (bindAddress != null)
{
result = FormatIP6String(bindAddress);
_logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result);
return true;
}
if (isInExternalSubnet && defaultGateway != null)
{
result = FormatIP6String(defaultGateway);
_logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result);
return true;
}
result = FormatIP6String(addresses[0].Address);
_logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result);
if (isInExternalSubnet)
{
_logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source);
}
return true;
}
return false;
}
/// <summary>
/// Attempts to match the source against an external interface.
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="result">The result, if a match is found.</param>
/// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
private bool MatchesExternalInterface(IPObject source, out string result)
{
result = string.Empty;
// Get the first WAN interface address that isn't a loopback.
var extResult = _interfaceAddresses
.Exclude(_bindExclusions)
.Where(p => !IsInLocalNetwork(p))
.OrderBy(p => p.Tag);
if (extResult.Any())
{
// Does the request originate in one of the interface subnets?
// (For systems with multiple internal network cards, and multiple subnets)
foreach (var intf in extResult)
{
if (!IsInLocalNetwork(intf) && intf.Contains(source))
{
result = FormatIP6String(intf.Address);
_logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result);
return true;
}
}
result = FormatIP6String(extResult.First().Address);
_logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result);
return true;
}
_logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source);
return false;
}
}
}
|