-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkFtthFree.pl
1531 lines (1441 loc) · 65.4 KB
/
checkFtthFree.pl
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
#!/usr/bin/env perl
#
# checkFtthFree
# Copyright (C) 2023-2024 Yann Riou <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: AGPL-3.0-or-later
#
use warnings;
use strict;
use utf8;
use Encode ();
use List::Util qw'any min sum0';
use Time::HiRes qw'time sleep';
use constant {
DARWIN => $^O eq 'darwin',
LINUX => $^O eq 'linux',
MSWIN32 => $^O eq 'MSWin32',
OPENBSD => $^O eq 'openbsd',
};
require HTTP::Tiny;
require Net::Ping;
{
no warnings 'once';
$Net::Ping::pingstring="PING\n";
}
require POSIX;
require Time::Piece;
my ($SYSCTL_CMD_PATH,$IP_CMD_PATH,$ETHTOOL_CMD_PATH,$ROUTE_CMD_PATH,$IFCONFIG_CMD_PATH,$NETSTAT_CMD_PATH);
if(! MSWIN32) {
$SYSCTL_CMD_PATH=findCmd('sysctl');
if(LINUX) {
($IP_CMD_PATH,$ETHTOOL_CMD_PATH)=(map {findCmd($_)} (qw'ip ethtool'));
}else{
($ROUTE_CMD_PATH,$IFCONFIG_CMD_PATH,$NETSTAT_CMD_PATH)=(map {findCmd($_)} (qw'route ifconfig netstat'))
}
}
sub findCmd {
my $cmd=shift;
foreach my $knownPath (map {$_.'/'.$cmd} (qw'/sbin /usr/sbin /bin /usr/bin')) {
return $knownPath if(-f $knownPath && -r _ && -x _);
}
require IPC::Cmd;
return IPC::Cmd::can_run($cmd);
}
my $VERSION='0.24';
my $PROGRAM_NAME='checkFtthFree';
my $IPV6_COMPAT=eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.25) };
my %TEST_DATA = ( 'local' => { IPv4 => ['212.27.38.253',8095,'/fixed/10G',2,10] },
Internet => { IPv4 => { download => { 12876 => { BBR => ['ipv4.scaleway.testdebit.info',80,'/10G.iso',10,30],
CUBIC => ['ping.online.net',80,'/10000Mo.dat',10,30] },
5410 => { BBR => ['ipv4.paris.testdebit.info',80,'/10G.iso',10,30],
CUBIC => ['ipv4.bouygues.testdebit.info',80,'/10G.iso',10,30] } },
upload => { 12876 => ['ipv4.scaleway.testdebit.info',80,'',10,30],
5410 => ['ipv4.paris.testdebit.info',80,'',10,30] } },
IPv6 => { download => { 12876 => { BBR => ['ipv6.scaleway.testdebit.info',80,'/10G.iso',10,30],
CUBIC => ['ping6.online.net',80,'/10000Mo.dat',10,30] },
5410 => { BBR => ['ipv6.paris.testdebit.info',80,'/10G.iso',10,30],
CUBIC => ['ipv6.bouygues.testdebit.info',80,'/10G.iso',10,30] } },
upload => { 12876 => ['ipv6.scaleway.testdebit.info',80,'',10,30],
5410 => ['ipv6.paris.testdebit.info',80,'',10,30] } },
} );
my %AS_NAMES = ( 5410 => 'Bouygues Telecom',
6799 => 'OTE',
12322 => 'Free',
12876 => 'Scaleway',
16276 => 'OVHcloud',
21409 => 'Ikoula',
24904 => 'Kwaoo K-Net',
53589 => 'PlanetHoster',
197133 => 'Mediactive Network',
200780 => 'Appliwave' );
my $MTU=1500;
my $MSS=$MTU-40;
my $TCP_EFFICIENCY=$MSS/($MTU+38);
my $GOODPUT_1Gbps_Bytes=1_000_000_000*$TCP_EFFICIENCY/8;
my $GOODPUT_700Mbps_Bytes=700_000_000*$TCP_EFFICIENCY/8;
my $RECOMMENDED_MIN_RTT_MAX_FOR_FULL_BANDWIDTH=15;
my $RECOMMENDED_MIN_RCV_WINDOW_SIZE=$GOODPUT_1Gbps_Bytes*$RECOMMENDED_MIN_RTT_MAX_FOR_FULL_BANDWIDTH/1000;
my $RECOMMENDED_MIN_SND_WINDOW_SIZE=$GOODPUT_700Mbps_Bytes*$RECOMMENDED_MIN_RTT_MAX_FOR_FULL_BANDWIDTH/1000;
my $TCP_WMEM_SND_WINDOW_RATIO=7/10;
my %cmdOpts=('check-update' => ['Effectue seulement la vérification de disponibilité de nouvelle version','c'],
'skip-check-update' => ['Désactive la vérification de disponibilité de nouvelle version','C'],
'skip-intro' => ["Désactive le message d'introduction et démarre immédiatement les tests",'I'],
'net-conf' => ['Effectue seulement la lecture de la configuration réseau','n'],
'skip-net-conf' => ['Désactive la lecture de la configuration réseau (empêche la détection de certains problèmes)','N'],
suggestions => ['Affiche des suggestions pour résoudre des problèmes de configuration réseau ou compléter les tests si besoin','s'],
freebox => ['Effectue seulement les tests locaux à partir de la Freebox (pas de test Internet)','f'],
'skip-freebox' => ['Désactive les tests locaux à partir de la Freebox (tests Internet uniquement, empêche la détection de certains problèmes)','F'],
latency => ['Effectue seulement les tests de latence (pas de test de débit)','l'],
'skip-latency' => ['Désactive les tests de latence (tests de débit uniquement, empêche la détection de certains problèmes)','L'],
upload => ['Effectue un test de débit montant au lieu de descendant (EXPERIMENTAL)','u'],
'binary-units' => ["Utilise les préfixes binaires pour le système d'unités de débit",'b'],
'extended-test' => ['Effectue des tests plus longs (multiplie par 2 la durée max des tests)','e'],
'quiet' => ["Mode silencieux: désactive les messages d'analyse et d'avertissement",'q'],
help => ["Affiche l'aide",'h'],
version => ['Affiche la version','v'],
ipv6 => ['Effectue les tests Internet en IPv6 (IPv4 par défaut)','6']);
my %cmdOptsAliases = map {$cmdOpts{$_}[1] => $_} (keys %cmdOpts);
my $httpClient=HTTP::Tiny->new(proxy => undef, http_proxy => undef, https_proxy => undef);
my ($WIN32_ACP_NB,$WIN32_OUTPUTCP);
if(MSWIN32) {
require Win32;
($WIN32_ACP_NB,$WIN32_OUTPUTCP)=(Win32::GetACP(),'cp'.Win32::GetConsoleOutputCP());
eval "use open ':std', OUT => ':encoding($WIN32_OUTPUTCP)'";
if($@) {
quit("Impossible de configurer l'encodage de la console Windows:\n$@");
}
}else{
eval "use open ':std', ':encoding(utf8)'";
}
sub win32PowershellExec {
my $psCmd="powershell.exe \"$_[0]\" 2>NUL";
my $previousCP=Win32::GetConsoleCP();
Win32::SetConsoleCP($WIN32_ACP_NB); # Prevent powershell.exe from replacing current font when UTF-8 is used...
my @res = map {Encode::decode($WIN32_OUTPUTCP,$_)} (wantarray() ? `$psCmd` : scalar(`$psCmd`));
Win32::SetConsoleCP($previousCP);
return @res;
};
my %options;
foreach my $arg (@ARGV) {
if(substr($arg,0,2) eq '--') {
my $cmdOpt=substr($arg,2);
if(exists $cmdOpts{$cmdOpt}) {
$options{$cmdOpt}++;
}else{
print "Option invalide \"$cmdOpt\"\n";
usage();
}
}elsif(substr($arg,0,1) eq '-') {
my $cmdOptsString=substr($arg,1);
my @cmdOptsList=split(//,$cmdOptsString);
foreach my $cmdOpt (@cmdOptsList) {
if(exists $cmdOptsAliases{$cmdOpt}) {
$options{$cmdOptsAliases{$cmdOpt}}++;
}else{
print "Option invalide \"$cmdOpt\"\n";
usage();
}
}
}else{
print "Paramètre invalide \"$arg\"\n";
usage();
}
}
my $maxTransferDuration=8;
my $maxNbPings=10*2**($options{'extended-test'}//0);
$maxTransferDuration=15*2**($options{'extended-test'}-1) if($options{'extended-test'});
usage() if(any {$options{$_->[0]} && $options{$_->[1]}} (['check-update','skip-check-update'],
['freebox','skip-freebox'],
['freebox','upload'],
['freebox','alternate-srv'],
['freebox','all-srv'],
['alternate-srv','all-srv'],
['latency','skip-latency'],
['latency','upload'],
['net-conf','quiet'],
['suggestions','quiet']));
quit("Le support d'IPv6 nécessite le module Perl IO::Socket::IP v0.25 ou supérieur") if($options{ipv6} && ! $IPV6_COMPAT);
sub usage {
print "\nUsage:\n $0 [<options>]\n";
foreach my $cmdOpt (sort {my $cic=lc($cmdOpts{$a}[1]) cmp lc($cmdOpts{$b}[1]); $cic ? $cic : $cmdOpts{$b}[1] cmp $cmdOpts{$a}[1]} keys %cmdOpts) {
print " --$cmdOpt (-$cmdOpts{$cmdOpt}[1]) : $cmdOpts{$cmdOpt}[0]\n";
}
quit();
}
my $timestampPrinted;
sub quit {
my $msg=shift;
print "$msg\n" if(defined $msg);
if($timestampPrinted) {
printTimestampLine();
}else{
print "\n";
}
if(MSWIN32) {
print "Appuyer sur Entrée pour quitter...\n";
<STDIN>;
}
exit;
}
sub printTimestampLine {
my $timestamp=time();
my @localtime=localtime($timestamp);
$localtime[4]++;
@localtime = map {sprintf('%02d',$_)} @localtime;
my $timeString=($localtime[5]+1900)
.'-'.$localtime[4]
.'-'.$localtime[3]
.' '.$localtime[2]
.':'.$localtime[1]
.':'.$localtime[0]
.' '.getTzOffset($timestamp);
my $timestampPadding='-' x (int(77-length($timeString))/2);
print "$timestampPadding $timeString $timestampPadding\n";
$timestampPrinted=1;
}
sub getTzOffset {
my $t=defined $_[0] ? $_[0] : time();
my ($lMin,$lHour,$lYear,$lYday)=(localtime($t))[1,2,5,7];
my ($gMin,$gHour,$gYear,$gYday)=(gmtime($t))[1,2,5,7];
my $deltaMin=($lMin-$gMin)+($lHour-$gHour)*60+( $lYear-$gYear || $lYday - $gYday)*24*60;
my $sign=$deltaMin>=0?'+':'-';
$deltaMin=abs($deltaMin);
my ($deltaHour,$deltaHourMin)=(int($deltaMin/60),$deltaMin%60);
return $sign.sprintf('%.2u%.2u',$deltaHour,$deltaHourMin);
}
sub checkForNewVersion {
return unless($VERSION =~ /^(\d+)\.(\d+)$/);
my ($currentVersionMajor,$currentVersionMinor)=($1,$2);
$httpClient->{timeout}=10;
my $result=$httpClient->get('http://checkversion.royalwebhosting.net/'.lc($PROGRAM_NAME));
if($result->{success}) {
my $newVersion=$result->{content};
if($newVersion =~ /^(\d+)\.(\d+)$/) {
my ($latestVersionMajor,$latestVersionMinor)=($1,$2);
$newVersion="$latestVersionMajor.$latestVersionMinor";
if($latestVersionMajor > $currentVersionMajor
|| ($latestVersionMajor == $currentVersionMajor && $latestVersionMinor > $currentVersionMinor)) {
print +('-' x 79)."\n";
print "Une nouvelle version de $PROGRAM_NAME est disponible ($newVersion)\n";
print "Vous utilisez actuellement la version $VERSION\n";
print "Vous pouvez télécharger la dernière version à partir du lien ci-dessous:\n";
print " https://github.com/Yaribz/$PROGRAM_NAME/releases/latest/download/$PROGRAM_NAME.".($0 =~ /\.exe$/i ? 'exe' : 'pl')."\n";
print "Vous pouvez désactiver la vérification de version avec le paramètre --skip-check-update (-C)\n";
print +('-' x 79)."\n";
print "Appuyer sur Ctrl-c pour quitter, ou Entrée pour continuer avec votre version actuelle.\n";
exit unless(defined <STDIN>);
}
}else{
print "[!] Impossible de vérifier si une nouvelle version est disponible (valeur de nouvelle version invalide \"$newVersion\")\n";
}
}else{
my $errorDetail = $result->{status} == 599 ? $result->{content} : "HTTP status: $result->{status}, reason: $result->{reason}";
$errorDetail=~s/\x{0092}/'/g if(MSWIN32);
chomp($errorDetail);
print "[!] Impossible de vérifier si une nouvelle version est disponible ($errorDetail)\n";
}
}
sub printIntroMsg {
print <<EOT;
===============================================================================
$PROGRAM_NAME
---------------
Programme de diagnostic de connexion FTTH Free
Ce programme analyse la configuration réseau du système et effectue différents
tests TCP (latence et débit mono-connexion) afin d'évaluer les performances de
la connexion FTTH et détecter d'éventuels dysfonctionnements.
Diverses options sont disponibles pour configurer ou désactiver certains tests,
voir --help (-h) pour plus d'information.
Avant de continuer, veuillez vérifier que rien d'autre ne consomme de la bande
passante sur le réseau (ordinateurs, Freebox player, télévision...), ni du CPU
sur le système de test (mises à jour automatiques, antivirus...).
===============================================================================
Appuyer sur Entrée pour continuer (ou Ctrl-C pour annuler)...
EOT
exit unless(defined <STDIN>);
}
sub printHeaderLine {
my $osName=getOsName()//$^O;
my $cbofTag="[$PROGRAM_NAME v$VERSION]";
my $osNamePaddingLength=79-length($cbofTag)-length($osName);
$osNamePaddingLength=1 if($osNamePaddingLength < 1);
print $cbofTag.(' ' x $osNamePaddingLength).$osName."\n";
}
sub getOsName {
my $n;
if(MSWIN32) {
$n=Win32::GetOSDisplayName();
substr($n,9,1)='1' if(substr($n,0,10) eq 'Windows 10' && (Win32::GetOSVersion())[3] >= 22000);
}else{
my @uname=POSIX::uname();
my ($sysName,$sysRelease,$sysArch)=@uname[0,2,4];
if($sysName) {
$n=$sysName;
$n.=" $sysRelease" if($sysRelease);
$n.=" ($sysArch)" if($sysArch);
}
}
return $n;
}
my %netConf;
my %WIN32_TCP_SETTINGS = map {$_ => 1} (qw'AutoTuningLevelEffective AutoTuningLevelGroupPolicy AutoTuningLevelLocal CongestionProvider EcnCapability ScalingHeuristics Timestamps');
my %netAdapterErrors;
sub getNetConf {
if(MSWIN32) {
my $TCP_PROPERTIES=join(', ',keys %WIN32_TCP_SETTINGS);
my $NET_ADAPTER_ADVANCED_PROPERTIES=join(', ',(qw'EEE FlowControl InterruptModeration IPChecksumOffloadIPv4 JumboPacket LsoV1IPv4 LsoV2IPv4 LsoV2IPv6 LSOv2IPv4 LSOv2IPv6 PacketCoalescing ReceiveBuffers RscIPv4 RscIPv6 SpeedDuplex TCPChecksumOffloadIPv4 TCPChecksumOffloadIPv6 TCPConnectionOffloadIPv4 TCPConnectionOffloadIPv6 TCPUDPChecksumOffloadIPv4 TCPUDPChecksumOffloadIPv6 TransmitBuffers'));
my $defaultIp = $options{ipv6} ? '::0' : '0.0.0.0';
my $powershellScript = (<<"END_OF_POWERSHELL_SCRIPT" =~ s/\n//gr);
\$ErrorActionPreference='silentlycontinue';
Get-NetTCPSetting Internet | Format-List -Property $TCP_PROPERTIES;
\$defaultInterfaceName=(Find-NetRoute -RemoteIpAddress $defaultIp)[0].InterfaceAlias;
if(\$defaultInterfaceName -ne \$null) {
Get-NetAdapter -Name \$defaultInterfaceName | Format-List -Property LinkSpeed, PhysicalMediaType, DriverDescription, DriverProvider, DriverVersionString, DriverDate;
\$advancedProperties = New-Object PSObject;
Get-NetAdapterAdvancedProperty -Name \$defaultInterfaceName | Where-Object -Property RegistryKeyword -Match '^\\*' | ForEach-Object { \$advancedProperties | Add-Member -MemberType NoteProperty -Name (\$_.RegistryKeyword).substring(1) -Value \$_.DisplayValue };
\$advancedProperties | Format-List -Property $NET_ADAPTER_ADVANCED_PROPERTIES;
Get-NetAdapterHardwareInfo -Name \$defaultInterfaceName | Format-List -Property PcieLinkSpeed, PcieLinkWidth;
Get-NetConnectionProfile -InterfaceAlias \$defaultInterfaceName | Format-List -Property NetworkCategory;
Get-NetAdapterStatistics -Name \$defaultInterfaceName | Format-List -Property OutboundDiscardedPackets, OutboundPacketErrors, ReceivedDiscardedPackets, ReceivedPacketErrors;
}
END_OF_POWERSHELL_SCRIPT
my @netConfLines = win32PowershellExec($powershellScript);
map {$netConf{$1}=$2 if(/^\s*([^:]*[^\s:])\s*:\s*(.*[^\s])\s*$/)} @netConfLines;
foreach my $netAdapterCounter (qw'OutboundDiscardedPackets OutboundPacketErrors ReceivedDiscardedPackets ReceivedPacketErrors') {
$netAdapterErrors{$netAdapterCounter} = delete $netConf{$netAdapterCounter} if(exists $netConf{$netAdapterCounter});
}
if(defined $netConf{AutoTuningLevelEffective}) {
if($netConf{AutoTuningLevelEffective} eq 'Local') {
delete $netConf{AutoTuningLevelGroupPolicy};
delete $netConf{AutoTuningLevelEffective};
}elsif($netConf{AutoTuningLevelEffective} eq 'GroupPolicy') {
delete $netConf{AutoTuningLevelLocal};
delete $netConf{AutoTuningLevelEffective};
}
}
$netConf{Driver} = delete $netConf{DriverDescription}
if(exists $netConf{DriverDescription});
if(exists $netConf{DriverVersionString}) {
$netConf{DriverVersion}=delete $netConf{DriverVersionString};
my @driverVersionDetails;
map {push(@driverVersionDetails,delete $netConf{$_}) if(exists $netConf{$_})} (qw'DriverProvider DriverDate');
$netConf{DriverVersion}.=' ('.join(', ',@driverVersionDetails).')' if(@driverVersionDetails);
}
$netConf{JumboPacket}='Disabled'
if(exists $netConf{JumboPacket} && $netConf{JumboPacket} eq '1514');
my @ipVersionedParams;
map {push(@ipVersionedParams,$1) if(/^(.+)IPv4$/)} (keys %netConf);
foreach my $ipVersionedParam (@ipVersionedParams) {
my ($ipv4Param,$ipv6Param) = map {$ipVersionedParam.$_} (qw'IPv4 IPv6');
if(exists $netConf{$ipv6Param} && $netConf{$ipv4Param} eq $netConf{$ipv6Param}) {
$netConf{$ipVersionedParam} = delete $netConf{$ipv4Param};
delete $netConf{$ipv6Param};
}
}
}elsif(defined $SYSCTL_CMD_PATH) {
my @netConfFields;
if(LINUX) {
if(defined $IP_CMD_PATH) {
my @cmdOutputLines = $options{ipv6} ? `$IP_CMD_PATH -6 route show default 2>/dev/null` : `$IP_CMD_PATH -4 route show default 2>/dev/null`;
my $device;
foreach my $line (@cmdOutputLines) {
if($line =~ /\sdev\s+([^\s\/]{1,15})\s/) {
$device=$1;
last;
}
}
if(defined $device) {
my %devices=(intf => $device);
my $activeDevice=getFileFirstLine("/sys/class/net/$device/bonding/active_slave");
%devices = (intf => $activeDevice, bonding => $device ) if(defined $activeDevice);
$netConf{$_.'.dev'}=$devices{$_} foreach(keys %devices);
my %INTF_SETTINGS = map {$_ => 1} (qw'mtu qdisc qlen');
foreach my $devType (keys %devices) {
my $dev=$devices{$devType};
@cmdOutputLines=`$IP_CMD_PATH link show $dev 2>/dev/null`;
foreach my $line (@cmdOutputLines) {
next unless($line =~ /\s(mtu\s.*)$/);
my @linkSettings=split(/\s+/,$1);
last if(@linkSettings % 2);
for my $i (0..$#linkSettings/2) {
my ($linkSettingName,$linkSettingValue)=($linkSettings[$i*2],$linkSettings[$i*2+1]);
next unless($INTF_SETTINGS{$linkSettingName});
$netConf{"$devType.$linkSettingName"}=$linkSettingValue;
}
last;
}
}
if(defined $ETHTOOL_CMD_PATH) {
{ # General info
@cmdOutputLines=`$ETHTOOL_CMD_PATH $devices{intf} 2>/dev/null`;
my %ETHTOOL_PARAM_MAPPING=(
speed => 'speed',
duplex => 'duplex',
'auto-negotiation' => 'autoneg',
port => 'port',
);
foreach my $line (@cmdOutputLines) {
next unless($line =~ /^\s*([^:]*[^:\s])\s*:\s*(.*[^\s])\s*$/);
my ($lcParam,$val)=(lc($1),$2);
next unless(exists $ETHTOOL_PARAM_MAPPING{$lcParam});
$netConf{'link.'.$ETHTOOL_PARAM_MAPPING{$lcParam}}=$val;
}
}
{ # Driver
@cmdOutputLines=`$ETHTOOL_CMD_PATH -i $devices{intf} 2>/dev/null`;
my %driverInfo;
foreach my $line (@cmdOutputLines) {
$driverInfo{lc($1)}=$2 if($line =~ /^\s*([^:]*[^\s:])\s*:\s*(.*[^\s])\s*$/);
}
if(exists $driverInfo{driver}) {
$netConf{'intf.driver'}=$driverInfo{driver};
$netConf{'intf.driver'}.=" $driverInfo{version}" if(exists $driverInfo{version});
}
$netConf{'intf.firmware-version'}=$driverInfo{'firmware-version'} if(exists $driverInfo{'firmware-version'});
}
{ # Coalescing
@cmdOutputLines=`$ETHTOOL_CMD_PATH -c $devices{intf} 2>/dev/null`;
my ($adaptiveRx,$rxUsecs,$rxFrames,$adaptiveTx,$txUsecs,$txFrames);
foreach my $line (@cmdOutputLines) {
if($line =~ /^\s*adaptive[\- ]rx\s*:\s*([^\s]+)(?:\s+tx\s*:\s*([^\s]+))?\s*$/i) {
$adaptiveRx=$1;
$adaptiveTx=$2 if(defined $2);
}elsif($line =~ /^\s*adaptive[\- ]tx\s*:\s*([^\s]+)(?:\s+rx\s*:\s*([^\s]+))?\s*$/i) {
$adaptiveTx=$1;
$adaptiveRx=$2 if(defined $2);
}elsif($line =~ /^\s*rx[\- ]usecs\s*:\s*(\d+)\s*$/i) {
$rxUsecs=$1;
}elsif($line =~ /^\s*tx[\- ]usecs\s*:\s*(\d+)\s*$/i) {
$txUsecs=$1;
}elsif($line =~ /^\s*rx[\- ]frames\s*:\s*(\d+)\s*$/i) {
$rxFrames=$1;
}elsif($line =~ /^\s*tx[\- ]frames\s*:\s*(\d+)\s*$/i) {
$txFrames=$1;
}
}
if(defined $adaptiveRx && lc($adaptiveRx) eq 'on') {
$netConf{'intf.coalesce-rx'}='adaptive';
}else{
my @rxVals;
if(defined $adaptiveRx) {
my $lcAdaptiveRx=lc($adaptiveRx);
push(@rxVals,'adaptive='.$lcAdaptiveRx)
unless(any {$lcAdaptiveRx eq $_} (qw'off n/a'));
}
push(@rxVals,$rxUsecs.' usecs') if(defined $rxUsecs);
push(@rxVals,$rxFrames.' frames') if(defined $rxFrames);
$netConf{'intf.coalesce-rx'}=join(' / ',@rxVals) if(@rxVals);
}
if(defined $adaptiveTx && lc($adaptiveTx) eq 'on') {
$netConf{'intf.coalesce-tx'}='adaptive';
}else{
my @txVals;
if(defined $adaptiveTx) {
my $lcAdaptiveTx=lc($adaptiveTx);
push(@txVals,'adaptive='.$lcAdaptiveTx)
unless(any {$lcAdaptiveTx eq $_} (qw'off n/a'));
}
push(@txVals,$txUsecs.' usecs') if(defined $txUsecs);
push(@txVals,$txFrames.' frames') if(defined $txFrames);
$netConf{'intf.coalesce-tx'}=join(' / ',@txVals) if(@txVals);
}
}
{ # Ring buffer
@cmdOutputLines=`$ETHTOOL_CMD_PATH -g $devices{intf} 2>/dev/null`;
my ($currentSection,%ringValues);
foreach my $line (@cmdOutputLines) {
if($line =~ /\smaximums\s*:\s*$/i) {
$currentSection='max';
}elsif($line =~ /^current\s.*:\s*$/i) {
$currentSection='current';
}elsif(defined $currentSection && $line =~ /^\s*([rt]x)\s*:\s*([^\s]+)\s*$/i) {
$ringValues{uc($1)}{$currentSection}=$2;
}
}
if(exists $ringValues{RX} && exists $ringValues{RX}{current}) {
$netConf{'intf.ring-rx'}=$ringValues{RX}{current};
$netConf{'intf.ring-rx'}.=" (max: $ringValues{RX}{max})" if(exists $ringValues{RX}{max});
}
if(exists $ringValues{TX} && exists $ringValues{TX}{current}) {
$netConf{'intf.ring-tx'}=$ringValues{TX}{current};
$netConf{'intf.ring-tx'}.=" (max: $ringValues{TX}{max})" if(exists $ringValues{TX}{max});
}
}
{ # Offloading and features
@cmdOutputLines=`$ETHTOOL_CMD_PATH -k $devices{intf} 2>/dev/null`;
my %ETHTOOL_PARAM_MAPPING=(
'rx-checksumming' => 'cksum_rx',
'tx-checksumming' => 'cksum_tx',
'tcp-segmentation-offload' => 'tso',
'generic-segmentation-offload' => 'gso',
'generic-receive-offload' => 'gro',
'large-receive-offload' => 'lro',
);
my @offloaded;
foreach my $line (@cmdOutputLines) {
next unless($line =~ /^\s*([^:]*[^\s:])\s*:\s*([^\[]*[^\s\[])(?:\s+\[[^\]]*\])?\s*$/);
my $lcParam=lc($1);
if($lcParam eq 'scatter-gather') {
$netConf{'intf.dma-sg'}=$2;
}elsif(exists $ETHTOOL_PARAM_MAPPING{$lcParam}) {
my ($lcVal,$mappedVal)=(lc($2),$ETHTOOL_PARAM_MAPPING{$lcParam});
if($lcVal eq 'on') {
push(@offloaded,'+'.$mappedVal);
}elsif(any {$lcVal eq $_} (qw'off n/a')) {
push(@offloaded,'-'.$mappedVal);
}else{
push(@offloaded,$mappedVal.'='.$2);
}
}
}
$netConf{'intf.offload'}=join(' | ',@offloaded) if(@offloaded);
}
}
foreach my $linkParam (qw'duplex speed') {
my $fullParam='link.'.$linkParam;
next if(defined $netConf{$fullParam});
my $val=getFileFirstLine("/sys/class/net/$devices{intf}/$linkParam");
$netConf{$fullParam}=$val if(defined $val);
}
my %SYSCLASS_PARAM_MAPPING=(mtu => 'mtu', tx_queue_len => 'qlen');
foreach my $intfParam (keys %SYSCLASS_PARAM_MAPPING) {
my $fullParam='intf.'.$SYSCLASS_PARAM_MAPPING{$intfParam};
next if(defined $netConf{$fullParam});
my $val=getFileFirstLine("/sys/class/net/$devices{intf}/$intfParam");
$netConf{$fullParam}=$val if(defined $val);
}
my %SYSCLASS_DEVICE_PARAM_MAPPING=(current_link_speed => 'link_speed', current_link_width => 'link_width');
foreach my $intfParam (keys %SYSCLASS_DEVICE_PARAM_MAPPING) {
my $val=getFileFirstLine("/sys/class/net/$devices{intf}/device/$intfParam");
$netConf{'dev.'.$SYSCLASS_DEVICE_PARAM_MAPPING{$intfParam}}=$val if(defined $val);
}
}
}
my $r_netErrors=linuxGetNetErrorCounters($netConf{'intf.dev'});
%netAdapterErrors=%{$r_netErrors};
@netConfFields=qw'
net.core.default_qdisc
net.core.netdev_budget
net.core.netdev_budget_usecs
net.core.netdev_max_backlog
net.core.rmem_max
net.core.wmem_max
net.ipv4.tcp_adv_win_scale
net.ipv4.tcp_congestion_control
net.ipv4.tcp_dsack
net.ipv4.tcp_ecn
net.ipv4.tcp_mem
net.ipv4.tcp_no_metrics_save
net.ipv4.tcp_rmem
net.ipv4.tcp_sack
net.ipv4.tcp_timestamps
net.ipv4.tcp_window_scaling
net.ipv4.tcp_wmem';
}else{
if(defined $ROUTE_CMD_PATH) {
my @cmdOutputLines = $options{ipv6} ? `$ROUTE_CMD_PATH -n get -inet6 default` : `$ROUTE_CMD_PATH -n get default`;
my $device;
foreach my $line (@cmdOutputLines) {
if($line =~ /^\s*interface\s*:\s*([^\s\/]{1,15})\s*$/) {
$device=$1;
last;
}
}
if(defined $device) {
$netConf{'intf.dev'}=$device;
if(defined $IFCONFIG_CMD_PATH) {
my $ifConfigFlag = DARWIN ? '-v ' : '';
my @ifconfigCmdRes = `$IFCONFIG_CMD_PATH $ifConfigFlag$device`;
my %IFCONFIG_PARAM_MAPPING=(media => 'link.media', type => 'link.type', scheduler => 'intf.qdisc', 'link rate' => 'link.speed');
my (@enabledOpts,%enabledOptsDedup);
foreach my $line (@ifconfigCmdRes) {
if(! exists $netConf{'intf.mtu'} && $line =~ /\smtu\s(\d+)/) {
$netConf{'intf.mtu'}=$1;
}elsif($line =~ /^\s*(?:options|enabled|ec_enabled)\s*=\s*[\da-fA-F]+\s*<([^>]+)>\s*/) {
foreach my $opt (split(/,/,$1)) {
next if(lc(substr($opt,0,5)) eq 'vlan_' || exists $enabledOptsDedup{$opt});
$enabledOptsDedup{$opt}=1;
push(@enabledOpts,$opt);
}
}elsif($line =~ /^\s*([\w ]*[^\s])\s*:\s*(.*[^\s])\s*$/ && exists $IFCONFIG_PARAM_MAPPING{$1}) {
$netConf{$IFCONFIG_PARAM_MAPPING{$1}}=$2;
}
}
$netConf{'intf.options'}=join(',',@enabledOpts) if(@enabledOpts);
}
my $r_intfErrors=bsdGetIntfErrorCounters($device);
%netAdapterErrors=%{$r_intfErrors};
}
}
@netConfFields=qw'
kern.ipc.maxsockbuf
net.inet.ip.ifq.maxlen
net.inet.ip.intr_queue_maxlen
net.inet.ip.maxqueue
net.inet.tcp.sendspace
net.inet.tcp.recvspace
net.inet.tcp.sendbuf_auto
net.inet.tcp.doautosndbuf
net.inet.tcp.sendbuf_max
net.inet.tcp.autosndbufmax
net.inet.tcp.sendbuf_inc
net.inet.tcp.sendbuf_auto_lowat
net.inet.tcp.recvbuf_auto
net.inet.tcp.doautorcvbuf
net.inet.tcp.recvbuf_max
net.inet.tcp.autorcvbufmax
net.inet.tcp.recvbuf_inc
net.inet.tcp.reass.maxqueuelen
net.inet.tcp.sack.enable
net.inet.tcp.ecn.enable
net.inet.tcp.hostcache.enable
net.inet.tcp.rfc1323
net.inet.tcp.rfc3042
net.inet.tcp.functions_available
net.inet.tcp.functions_default
net.inet.tcp.cc.available
net.inet.tcp.cc.algorithm
net.inet.tcp.timestamps
net.inet.tcp.congctl.available
net.inet.tcp.congctl.selected
net.inet.tcp.reasslimit
net.inet.tcp.sack
net.inet.tcp.ecn
net.inet.tcp.ecn_initiate_out
net.inet.tcp.ecn_negotiate_in
net.inet6.ip6.ifq.maxlen
net.inet6.ip6.intr_queue_maxlen
net.link.generic.system.rcvq_maxlen
net.link.generic.system.sndq_maxlen
net.link.ifqmaxlen';
}
my @netConfLines=`$SYSCTL_CMD_PATH -a 2>/dev/null`;
foreach my $line (@netConfLines) {
if($line =~ /^\s*([^:=]*[^\s:=])\s*[:=]\s*(.*[^\s])\s*$/ && (any {$1 eq $_} @netConfFields)) {
$netConf{$1}=$2;
}
}
}
}
sub getFileFirstLine {
my $filePath=shift;
my $fileHdl;
return unless(-f $filePath && -r _ && open($fileHdl,'<',$filePath));
my $content=<$fileHdl>;
close($fileHdl);
return unless(defined $content);
chomp($content);
return if($content eq '');
return $content;
}
sub linuxGetNetErrorCounters {
my $dev=shift;
my %errorCounters;
if(defined $dev) {
my $devStatDir="/sys/class/net/$dev/statistics";
if(-d $devStatDir && -r _ && opendir(my $statDh,$devStatDir)) {
my @errorCounterNames = grep {(/_errors$/ || /_dropped$/ || $_ eq 'collisions') && -f "$devStatDir/$_" && -r _} readdir($statDh);
closedir($statDh);
foreach my $errorCounter (@errorCounterNames) {
my $counterFh;
next unless(open($counterFh,'<',"$devStatDir/$errorCounter"));
my $counterValue=<$counterFh>;
close($counterFh);
next unless(defined $counterValue && $counterValue =~ /^(\d+)/);
$errorCounters{$errorCounter}=$1;
}
}
}
my $softnetStatFile='/proc/net/softnet_stat';
if(-f $softnetStatFile && -r _ && open(my $softnetStatFh,'<',$softnetStatFile)) {
while(my $statLine=<$softnetStatFh>) {
next unless($statLine =~ /^[\da-fA-F]+\s+([\da-fA-F]+)\s+([\da-fA-F]+)/);
$errorCounters{rx_softnet_dropped}+=hex('0x'.$1);
$errorCounters{rx_softnet_squeezed}+=hex('0x'.$2);
}
close($softnetStatFh);
}
return \%errorCounters;
}
sub bsdGetIntfErrorCounters {
return {} unless(defined $NETSTAT_CMD_PATH);
my $dev=shift;
my $r_linkCounters=bsdGetLinkCounters($dev);
if(OPENBSD) {
my $r_linkErrorCounters=bsdGetLinkCounters($dev,'e');
$r_linkCounters->{$_}//=$r_linkErrorCounters->{$_} foreach(keys %{$r_linkErrorCounters});
}
my %errorCounters;
foreach my $counter (keys %{$r_linkCounters}) {
my $lcCounter=lc($counter);
next unless($counter =~ /^colls?$/i
|| $counter =~ /^[io]?drops?$/i
|| $counter =~ /^[io]errs$/i);
next unless($r_linkCounters->{$counter} =~ /^\d+$/);
$errorCounters{$counter}=$r_linkCounters->{$counter};
}
return \%errorCounters;
}
sub bsdGetLinkCounters {
my ($dev,$flag)=@_;
$flag//='d';
my @cmdOutputLines=`$NETSTAT_CMD_PATH -${flag}nI $dev 2>/dev/null`;
my @fieldNames;
foreach my $line (@cmdOutputLines) {
chomp($line);
next if($line =~ /^\s*$/);
if(@fieldNames) {
my @vals=split(/\s+/,$line);
my %data;
$data{$fieldNames[$_]}=$vals[$_] for(0..$#fieldNames);
next unless(exists $data{Network} && substr(lc($data{Network}),0,5) eq '<link');
return \%data;
}else{
@fieldNames=split(/\s+/,$line);
}
}
return {};
}
my ($rcvWindow,$rmemMaxParam,$rmemMaxValuePrefix,$tcpAdvWinScale,$sndWindow,$wmemMaxParam,$wmemMaxValuePrefix,$degradedTcpConf);
sub netConfAnalysis {
if(! %netConf) {
print "[!] Echec de lecture de la configuration réseau du système\n";
return;
}
print "Configuration réseau du système:\n";
if(MSWIN32) {
my %prefixedConf;
foreach my $param (keys %netConf) {
my $prefix;
if($param eq 'NetworkCategory') {
$prefix='NetProfile';
}elsif(exists $WIN32_TCP_SETTINGS{$param}) {
$prefix='Tcp';
}else{
$prefix='Adapter';
}
$prefixedConf{$prefix.'.'.$param}=$netConf{$param};
}
map {print " $_: $prefixedConf{$_}\n"} (sort keys %prefixedConf);
if(defined $netConf{AutoTuningLevelLocal}) {
processWindowsAutoTuningLevel('AutoTuningLevelLocal');
if($netConf{AutoTuningLevelLocal} ne 'Normal') {
print "[!] La valeur actuelle de AutoTuningLevelLocal peut dégrader les performances\n";
if($options{suggestions}) {
print " Recommandation: ajuster le paramètre avec l'une des deux commandes suivantes\n";
print " [PowerShell] Set-NetTCPSetting -SettingName Internet -AutoTuningLevelLocal Normal\n";
print " [cmd.exe] netsh interface tcp set global autotuninglevel=normal\n";
}
}
}elsif(defined $netConf{AutoTuningLevelGroupPolicy}) {
processWindowsAutoTuningLevel('AutoTuningLevelGroupPolicy');
if($netConf{AutoTuningLevelGroupPolicy} ne 'Normal') {
print "[!] La stratégie de groupe appliquée aux paramètres AutoTuningLevelEffective et AutoTuningLevelGroupPolicy peut dégrader les performances\n";
if($options{suggestions}) {
print " Recommandation: effectuer l'une des deux actions suivantes\n";
print " - configurer la valeur du paramètre AutoTuningLevelGroupPolicy à \"Normal\" dans la stratégie de groupe\n";
print " - utiliser la configuration locale pour ce paramètre (configurer le valeur du paramètre AutoTuningLevelEffective à \"Local\")\n";
}
}
}
if(defined $netConf{ScalingHeuristics} && $netConf{ScalingHeuristics} ne 'Disabled') {
$degradedTcpConf=1;
print "[!] La valeur actuelle de ScalingHeuristics peut dégrader les performances\n";
if($options{suggestions}) {
print " Recommandation: ajuster le paramètre avec une des deux commandes suivantes\n";
print " [PowerShell] Set-NetTCPSetting -SettingName Internet -ScalingHeuristics Disabled\n";
print " [cmd.exe] netsh interface tcp set heuristics disabled\n";
}
}
if(defined $netConf{LinkSpeed} && $netConf{LinkSpeed} ne 'Unknown'
&& defined $netConf{PcieLinkSpeed} && $netConf{PcieLinkSpeed} ne 'Unknown'
&& defined $netConf{PcieLinkWidth}) {
checkPcieLinkSpeedConsistency('LinkSpeed','PcieLinkSpeed','PcieLinkWidth');
}
}else{
map {print " $_: $netConf{$_}\n"} (sort keys %netConf);
if(LINUX) {
my $rmemMax;
if(defined $netConf{'net.core.rmem_max'}) {
if($netConf{'net.core.rmem_max'} =~ /^\s*(\d+)\s*$/) {
($rmemMax,$rmemMaxParam)=($1,'net.core.rmem_max');
}else{
print "[!] Valeur de net.core.rmem_max non reconnue\n";
}
}
if(defined $netConf{'net.ipv4.tcp_rmem'}) {
if($netConf{'net.ipv4.tcp_rmem'} =~ /^\s*(\d+)\s+(\d+)\s+(\d+)\s*$/) {
($rmemMax,$rmemMaxParam,$rmemMaxValuePrefix)=($3,'net.ipv4.tcp_rmem',"$1 $2 ");
}else{
print "[!] Valeur de net.ipv4.tcp_rmem non reconnue\n";
}
}
if(defined $netConf{'net.ipv4.tcp_adv_win_scale'}) {
if($netConf{'net.ipv4.tcp_adv_win_scale'} =~ /^\s*(-?\d+)\s*$/ && $&) {
$tcpAdvWinScale=$1;
}else{
print "[!] Valeur de net.ipv4.tcp_adv_win_scale non reconnue\n";
}
}
if(defined $rmemMax) {
if(defined $tcpAdvWinScale) {
my $overHeadFactor=2 ** abs($tcpAdvWinScale);
$rcvWindow=$rmemMax/$overHeadFactor;
$rcvWindow=$rmemMax-$rcvWindow if($tcpAdvWinScale > 0);
}else{
print "[!] Valeur de net.ipv4.tcp_adv_win_scale non trouvée\n";
}
}
my $wmemMax;
if(defined $netConf{'net.core.wmem_max'}) {
if($netConf{'net.core.wmem_max'} =~ /^\s*(\d+)\s*$/) {
($wmemMax,$wmemMaxParam)=($1,'net.core.wmem_max');
}else{
print "[!] Valeur de net.core.wmem_max non reconnue\n";
}
}
if(defined $netConf{'net.ipv4.tcp_wmem'}) {
if($netConf{'net.ipv4.tcp_wmem'} =~ /^\s*(\d+)\s+(\d+)\s+(\d+)\s*$/) {
($wmemMax,$wmemMaxParam,$wmemMaxValuePrefix)=($3,'net.ipv4.tcp_wmem',"$1 $2 ");
}else{
print "[!] Valeur de net.ipv4.tcp_wmem non reconnue\n";
}
}
$sndWindow=$wmemMax*$TCP_WMEM_SND_WINDOW_RATIO if(defined $wmemMax);
if(exists $netConf{'link.speed'}
&& exists $netConf{'dev.link_speed'} && $netConf{'dev.link_speed'} ne 'Unknown'
&& exists $netConf{'dev.link_width'} && $netConf{'dev.link_width'}) {
checkPcieLinkSpeedConsistency('link.speed','dev.link_speed','dev.link_width');
}
}else{
my %bsdParams;
if(defined $netConf{'kern.ipc.maxsockbuf'}) {
if($netConf{'kern.ipc.maxsockbuf'} =~ /^\s*(\d+)\s*$/) {
$bsdParams{maxsockbuf}=$1;
}else{
print "[!] Valeur de kern.ipc.maxsockbuf non reconnue\n";
}
}
foreach my $tcpParam (qw'recvbuf_auto doautorcvbuf sendbuf_auto doautosndbuf') {
my $fullParam='net.inet.tcp.'.$tcpParam;
if(defined $netConf{$fullParam}) {
if($netConf{$fullParam} =~ /^\s*([01])\s*$/) {
$bsdParams{$tcpParam}=$1;
}else{
print "[!] Valeur de $fullParam non reconnue\n";
}
}
}
foreach my $tcpParam (qw'recvbuf_max autorcvbufmax recvspace sendbuf_max autosndbufmax sendspace') {
my $fullParam='net.inet.tcp.'.$tcpParam;
if(defined $netConf{$fullParam}) {
if($netConf{$fullParam} =~ /^\s*(\d+)\s*$/) {
$bsdParams{$tcpParam}=$1;
}else{
print "[!] Valeur de $fullParam non reconnue\n";
}
}
}
if(defined $bsdParams{maxsockbuf} && defined $bsdParams{recvspace} && defined $bsdParams{sendspace} && $bsdParams{maxsockbuf} < $bsdParams{recvspace} + $bsdParams{sendspace}) {
$bsdParams{maxsockbuf}=$bsdParams{recvspace}+$bsdParams{sendspace};
}
my $recvBufMaxParam = defined $bsdParams{recvbuf_max} ? 'recvbuf_max' : defined $bsdParams{autorcvbufmax} ? 'autorcvbufmax' : undef;
my $sendBufMaxParam = defined $bsdParams{sendbuf_max} ? 'sendbuf_max' : defined $bsdParams{autosndbufmax} ? 'autosndbufmax' : undef;
my $recvBufAutoEnabled=$bsdParams{recvbuf_auto}//$bsdParams{doautorcvbuf};
$recvBufAutoEnabled//=1 if(defined $recvBufMaxParam);
my $sendBufAutoEnabled=$bsdParams{sendbuf_auto}//$bsdParams{doautosndbuf};
$sendBufAutoEnabled//=1 if(defined $sendBufMaxParam);
if($recvBufAutoEnabled) {
($rmemMaxParam,$rcvWindow)=('kern.ipc.maxsockbuf',$bsdParams{maxsockbuf}-($bsdParams{sendspace}//0)) if(defined $bsdParams{maxsockbuf});
($rmemMaxParam,$rcvWindow)=('net.inet.tcp.'.$recvBufMaxParam,$bsdParams{$recvBufMaxParam}) if(defined $recvBufMaxParam && (! defined $rcvWindow || $rcvWindow > $bsdParams{$recvBufMaxParam}));
}else{
($rmemMaxParam,$rcvWindow)=('net.inet.tcp.recvspace',$bsdParams{recvspace}) if(defined $bsdParams{recvspace});
}
if($sendBufAutoEnabled) {
($wmemMaxParam,$sndWindow)=('kern.ipc.maxsockbuf',$bsdParams{maxsockbuf}) if(defined $bsdParams{maxsockbuf});
($wmemMaxParam,$sndWindow)=('net.inet.tcp.'.$sendBufMaxParam,$bsdParams{$sendBufMaxParam}) if(defined $sendBufMaxParam && (! defined $sndWindow || $sndWindow > $bsdParams{$sendBufMaxParam}));
}else{
($wmemMaxParam,$sndWindow)=('net.inet.tcp.sendspace',$bsdParams{sendspace}) if(defined $bsdParams{sendspace});
}
}
}
if(defined $rcvWindow) {
my $maxRttMsFor1Gbps = int($rcvWindow * 1000 / $GOODPUT_1Gbps_Bytes + 0.5);
print " => Latence TCP max pour une réception à 1 Gbps: ${maxRttMsFor1Gbps} ms\n";
if(! MSWIN32 && $maxRttMsFor1Gbps < $RECOMMENDED_MIN_RTT_MAX_FOR_FULL_BANDWIDTH) {
if(LINUX) {
if($tcpAdvWinScale < -3) {
print "[!] Les valeurs actuelles de net.ipv4.tcp_adv_win_scale et $rmemMaxParam peuvent dégrader les performances\n";
}else{
print "[!] La valeur actuelle de $rmemMaxParam peut dégrader les performances\n";
if($options{suggestions}) {
print " Recommandation: ajuster le paramètre avec la commande suivante\n";
print " sysctl -w $rmemMaxParam=".rcvWindowToRmemValue($RECOMMENDED_MIN_RCV_WINDOW_SIZE)."\n";
}
}
}else{
print "[!] La valeur actuelle de $rmemMaxParam peut dégrader les performances\n";
}
}
}
if(defined $sndWindow) {
my $maxRttMsFor700Mbps = int($sndWindow * 1000 / $GOODPUT_700Mbps_Bytes + 0.5);
print " => Latence TCP max pour une émission à 700 Mbps: ${maxRttMsFor700Mbps} ms\n";
if($maxRttMsFor700Mbps < $RECOMMENDED_MIN_RTT_MAX_FOR_FULL_BANDWIDTH) {
print "[!] La valeur actuelle de $wmemMaxParam peut dégrader les performances\n";
if(LINUX && $options{suggestions}) {
print " Recommandation: ajuster le paramètre avec la commande suivante\n";
print " sysctl -w $wmemMaxParam=".sndWindowToWmemValue($RECOMMENDED_MIN_SND_WINDOW_SIZE)."\n";
}
}
}
}
my %windowsAutoTuningLevels=(Disabled => 0,
HighlyRestricted => 2,
Restricted => 4,
Normal => 8,
Experimental => 14);
sub processWindowsAutoTuningLevel {
my $autoTuningParam=shift;
my $autoTuningLevel=$netConf{$autoTuningParam};
if(exists $windowsAutoTuningLevels{$autoTuningLevel}) {
$rcvWindow=65535*2**$windowsAutoTuningLevels{$autoTuningLevel};
}else{
print "[!] Valeur de $autoTuningParam non reconnue\n";
$degradedTcpConf=1;
}
}
sub checkPcieLinkSpeedConsistency {
my ($paramLinkSpeed,$paramPcieLinkSpeed,$paramPcieLinkWidth)=@_;
my $linkSpeed;
if($netConf{$paramLinkSpeed} =~ /^(\d+) ?([KMGT]?)b[p\/]s$/) {
$linkSpeed=$1;
my $unitPrefix=$2;
$linkSpeed*={K => 1E3, M => 1E6, G => 1E9, T => 1E12}->{$unitPrefix} if($unitPrefix);
}elsif(LINUX && $netConf{$paramLinkSpeed} =~ /^\d+$/) {
$linkSpeed = $netConf{$paramLinkSpeed} * 1E6;
}else{
print "[!] Valeur de $paramLinkSpeed non reconnue\n";
return;
}
if($netConf{$paramPcieLinkSpeed} !~ /^(\d+(?:\.\d)?) GT\/s/) {
print "[!] Valeur de $paramPcieLinkSpeed non reconnue\n";
return;
}
my $pcieEfficiency;
if($1 < 8) {
$pcieEfficiency=4/5;
}elsif($1 < 64) {
$pcieEfficiency=64/65;
}else{
$pcieEfficiency=121/128;
}
my $pcieLinkSpeed = $1 * 1E9 * $pcieEfficiency;
if($netConf{$paramPcieLinkWidth} !~ /^\d+$/) {
print "[!] Valeur de $paramPcieLinkWidth non reconnue\n";
return;
}
$pcieLinkSpeed*=$netConf{$paramPcieLinkWidth};
if($pcieLinkSpeed < $linkSpeed) {
print "[!] La carte réseau utilise actuellement une interface PCI Express avec un taux de transfert ne permettant pas d'atteindre le débit maximum du lien réseau\n";
print " Recommandation: connecter la carte réseau sur un autre slot PCI Express (consulter le manuel de la carte mère si besoin pour trouver un slot adéquat)\n"
if($options{suggestions});