-
Notifications
You must be signed in to change notification settings - Fork 1
/
extension.ts
2157 lines (1883 loc) · 75.7 KB
/
extension.ts
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
//------------------------------------------------------------------------------
// extension.ts
//------------------------------------------------------------------------------
// Some things from 'vscode', which contains the VS Code extensibility API
import {
workspace,
window,
commands,
languages,
Diagnostic,
DiagnosticSeverity,
DiagnosticCollection,
ExtensionContext,
Range,
OutputChannel,
Position,
ProgressLocation,
Uri,
Disposable,
TextDocument,
TextLine,
StatusBarItem,
StatusBarAlignment,
WorkspaceConfiguration
} from 'vscode';
import fs = require('fs');
// For checking relative URIs against the local file system
import path = require('path');
// For accessing internet URIs
// https://www.npmjs.com/package/axios
// https://github.com/axios/axios
import {
AxiosPromise,
AxiosRequestConfig,
AxiosResponse,
CancelToken
} from 'axios';
const axios = require('axios');
const torreq = require('tor-request'); // https://www.npmjs.com/package/tor-request
const torcon = require('tor-control'); // https://www.npmjs.com/package/tor-control
var torcontrol = null;
const arrayBufferToHex = require('array-buffer-to-hex')
//Interface for links
interface Link {
text: string
address: string
lineText: TextLine
bDoHTTPSForm: boolean // address is HTTP, but check HTTPS form of it
}
//------------------------------------------------------------------------------
var myStatusBarItem: StatusBarItem = null;
var gDiagnosticsCollection: DiagnosticCollection = null;
var gDiagnosticsArray: Array<Diagnostic> = null;
var gConfiguration: WorkspaceConfiguration = null;
var gDocument = null;
var gStartingNLinks: number = 0;
var gnTimeout: number = 15; // seconds
var gbCheckInternalLinks: boolean = true;
var gbProcessIdAttributeInAnyTag: boolean = true;
var gsAddExtensionToLocalURLsWithNone: string = "";
var gbDone: boolean = true;
var gbCancelled: boolean = false;
var gLocalAnchorNames: Array<string> = null;
var gaDontCheck: Array<string> = null;
var gnMaxParallelThreads: number = 0;
var gbReportBadChars: boolean = true;
var gBadCharsSeverity: DiagnosticSeverity = DiagnosticSeverity.Information;
var gsPatternBadChars: string = "";
var gsReportBadChars = "E";
var gbReportPossibleMistakes: boolean = true;
var gPossibleMistakesSeverity: DiagnosticSeverity = DiagnosticSeverity.Information;
var gaPatternPossibleMistakes: Array<string> = null;
var gbReportHTTPSAvailable: boolean = true;
var gHTTPSAvailableSeverity: DiagnosticSeverity = DiagnosticSeverity.Information;
var gsReportRedirects: string = "";
var gReportRedirectSeverity: DiagnosticSeverity = DiagnosticSeverity.Error;
var gbReportSemanticErrors: boolean = true;
var gsReportSemanticErrors: string = "";
var gSemanticSeverity: DiagnosticSeverity = DiagnosticSeverity.Information;
var gsUserAgent: string = "";
var gsLocalRoot: string = "";
var gbCheckMailtoDestFormat: boolean = true;
var gsReportNonHandledSchemes = "";
var gReportNonHandledSchemesSeverity: DiagnosticSeverity = DiagnosticSeverity.Error;
//var //gOutputChannel: OutputChannel = null; // remove comment chars to do debugging
//------------------------------------------------------------------------------
// This method is called when your extension is activated.
// Your extension is activated the very first time the command is executed.
export function activate(extensionContext:ExtensionContext) {
//gOutputChannel = window.createOutputChannel("linkcheckerhtml");
// Show the output channel
//gOutputChannel.show(false); // preserveFocus === false
//gOutputChannel.appendLine(`activate: active`);
//gOutputChannel.appendLine(`activate: uri = ${window.activeTextEditor.document.uri.toString()}`);
myStatusBarItem = window.createStatusBarItem(StatusBarAlignment.Left, 0);
extensionContext.subscriptions.push(myStatusBarItem);
myStatusBarItem.hide();
gDiagnosticsCollection = languages.createDiagnosticCollection("linkcheckerhtml");
extensionContext.subscriptions.push(gDiagnosticsCollection);
let disposable1 = commands.registerCommand('extension.generateLinkReport', generateLinkReport);
extensionContext.subscriptions.push(disposable1);
let disposable2 = commands.registerCommand('extension.openURL', openURL);
extensionContext.subscriptions.push(disposable2);
let disposable3 = commands.registerCommand('extension.openURLasHTTPS', openURLasHTTPS);
extensionContext.subscriptions.push(disposable3);
let disposable4 = commands.registerCommand('extension.clearDiagnostics', clearDiagnostics);
extensionContext.subscriptions.push(disposable4);
//gOutputChannel.appendLine(`activate: finished`);
}
// this method is called when your extension is deactivated
export function deactivate() {
// delete any OS resources you allocated that are not
// included in extensionContext.subscriptions
}
//------------------------------------------------------------------------------
// from https://github.com/GabiGrin/vscode-auto-run-command/blob/master/src/lib/run-shell-command.ts
const runShellCommand = async (command: string): Promise<any> => {
const { exec } = require('child_process');
//gOutputChannel.appendLine(`runShellCommand: called, command "${command}"`);
return new Promise((resolve, reject) => {
exec(command, (error, _, stderr) => {
if (error) {
// we get here if xdotool can't find the window specified
//gOutputChannel.appendLine(`runShellCommand: error "${error}"`);
reject(error);
return;
}
if (stderr) {
//gOutputChannel.appendLine(`runShellCommand: stderr "${stderr}"`);
reject(stderr);
return;
}
resolve(null);
});
});
}
//------------------------------------------------------------------------------
// Open an onion URL in Tor browser.
export function openOnionURL(sURL: string) {
//gOutputChannel.appendLine(`openOnionURL: called, sURL '${sURL}'`);
/*
// METHOD 1: use tor-control
//
// see "man tor"
// to find out what config file is being used, do "tor --verify-config"
//
// any time you change /etc/tor/torrc, do "sudo systemctl restart tor"
// then check "sudo journalctl --pager-end" and "sudo ss -lptu" see listener on 9051
//
// for debugging, un-comment "Log debug file /var/log/tor/debug.log" in /etc/tor/torrc
// but you will get a TON of output
//
// if HashedControlPassword is set or CookieAuthentication == 1 in /etc/tor/torrc,
// file /run/tor/control.authcookie gets rewritten every time you start Tor service
//
// file /var/lib/tor/control_auth_cookie gets rewritten when ???
// sudo chmod a+rx /var/lib/tor ; sudo chmod a+r /var/lib/tor/control_auth_cookie ; sudo chmod a+r /run/tor/control.authcookie
fs.readFile(
//'/var/lib/tor/control_auth_cookie', // for browser
'/run/tor/control.authcookie', // for socks service
(err, data) => {
if (err) {
//gOutputChannel.appendLine(`openOnionURL.readFile: err "${err}"`);
return;
}
//gOutputChannel.appendLine(`openOnionURL.readFile: data bytelength ${data.byteLength}`);
const datahex = arrayBufferToHex(data);
//gOutputChannel.appendLine(`openOnionURL.readFile: datahex "${datahex}"`);
//torcontrol = new torcon({host:"127.0.0.1", port:9051, password:datahex, persistent:true});
torcontrol = new torcon({host:"127.0.0.1", port:9051, password:"giraffe"});
//torcontrol = new torcon({host:"127.0.0.1", port:9151, persistent:true});
//torcontrol.TorControlPort.password = 'giraffe';
// note: Tor Browser log (hamburger / Preferences / General / View Log) uses time-zone of exit relay !
// in Tor Browser log, always get "[NOTICE] New control connection opened from 127.0.0.1."
// and "[WARN] Bad password or authentication cookie on controller."
// "Error: Authentication failed with message: 515 Authentication failed: Password did not match HashedControlPassword *or* authentication cookie."
//gOutputChannel.appendLine(`openOnionURL: past new tor-control`);
// hash of "giraffe": 16:4F736B69E8F24708602DE20EE4801AFCC191DB13CDF700CB3D31BA23E6
// hash of giraffe: 16:95CD14D0F828911A60E28E633759E6866FE86E526B692EDFCD0DEC6DB9
// https://gitweb.torproject.org/torspec.git/tree/control-spec.txt
// support.torproject.org/#connectingtotor
// https://tor.stackexchange.com/questions/15098/wrong-password-when-using-system-installed-tor-with-tor-browser
// https://trac.torproject.org/projects/tor/wiki/TorBrowserBundleSAQ
// https://2019.www.torproject.org/docs/tor-manual.html.en
// https://www.codeproject.com/articles/1072864/tor-net-a-managed-tor-network-library
//torcontrol.connect();
////gOutputChannel.appendLine(`openOnionURL: past connect`);
torcontrol.getInfo(
['version', 'exit-policy/ipv4'],
function (err, res) {
//gOutputChannel.appendLine(`openOnionURL.callback: torcon.getInfo gave err "${err}", res "${res}"`);
if (!err) {
//gOutputChannel.appendLine(`openOnionURL.callback: res.code ${res.code}, res.message ${res.message}, res.data ${res.data}`);
////gOutputChannel.appendLine(`openOnionURL: res ${JSON.stringify(res)}`);
} else {
//gOutputChannel.appendLine(`openOnionURL.callback: err "${err}"`);
////gOutputChannel.appendLine(`openOnionURL: err ${JSON.stringify(err)}`);
//gOutputChannel.appendLine(`openOnionURL: res ${JSON.stringify(res)}`);
}
torcontrol.disconnect();
//gOutputChannel.appendLine(`openOnionURL.callback: past disconnect`);
torcontrol = null;
}
);
//gOutputChannel.appendLine(`openOnionURL: past getInfo`);
//torcontrol.sendCommand(
// "SHUTDOWN",
// function (err, res) {
// //gOutputChannel.appendLine(`openOnionURL.callback: torcon.sendCommand gave err "${err}", res "${res}"`);
// if (!err) {
// //gOutputChannel.appendLine(`openOnionURL.callback: res.code ${res.code}, res.message ${res.message}, res.data ${res.data}`);
// ////gOutputChannel.appendLine(`openOnionURL: res ${JSON.stringify(res)}`);
// } else {
// //gOutputChannel.appendLine(`openOnionURL.callback: err "${err}"`);
// ////gOutputChannel.appendLine(`openOnionURL: err ${JSON.stringify(err)}`);
// //gOutputChannel.appendLine(`openOnionURL: res ${JSON.stringify(res)}`);
// }
// torcontrol.disconnect();
// //gOutputChannel.appendLine(`openOnionURL.callback: past disconnect`);
// torcontrol = null;
// }
//);
////gOutputChannel.appendLine(`openOnionURL: past sendCommand`);
//torcontrol.disconnect();
////gOutputChannel.appendLine(`openOnionURL: past new disconnect`);
//torcontrol = null;
})
// METHOD 2: launch Tor Browser from command-line with --new-tab option
// gave up, launching is ridiculously contorted, at least on Linux
// and for example, the GNOME desktop file to launch Tor Browser is self-rewriting !
// METHOD 3: Define a new URL protocol type in the desktop.
// but you'd have to rewrite the URL, and Tor would get an URL it couldn't handle
// And you end up same problems as method 2.
// METHOD 4: D-Bus ? Didn't try.
// https://dbus.freedesktop.org/doc/dbus-tutorial.html
// https://github.com/Shouqun/node-dbus
// https://www.npmjs.com/package/dbus
// https://github.com/sidorares/dbus-native
// https://stackoverflow.com/questions/21440589/node-dbus-native
*/
// METHOD 5: xdotool (worked on Linux, then stopped working !)
// https://www.faqforge.com/linux/open-new-web-browser-tab-command-line-linux/
// sudo apt install xdotool
// man xdotool
gConfiguration = workspace.getConfiguration('linkcheckerhtml');
let sCmd1 = gConfiguration.torOpenURLCmd1 + "'" + sURL + "'\"";
let sCmd2 = gConfiguration.torOpenURLCmd2;
//let sCmd2 = "sleep 1";
var p1 = runShellCommand(sCmd1);
p1.then(() => {
//gOutputChannel.appendLine(`openOnionURL.p1.then: success`);
if (sCmd2.length > 0) {
var p2 = runShellCommand(sCmd2);
p2.then(() => {
//gOutputChannel.appendLine(`openOnionURL.p2.then: success`);
})
.catch(error => {
//gOutputChannel.appendLine(`openOnionURL.p2.then: error ${error}`);
})
}
})
.catch(error => {
//gOutputChannel.appendLine(`openOnionURL.p1.then: error ${error}`);
});
/*
// METHOD 6: xdotool a different way
const cp = require('child_process')
cp.exec(sCmd1, (err, stdout, stderr) => {
//gOutputChannel.appendLine('openOnionURL.1.stdout: ' + stdout);
//gOutputChannel.appendLine('openOnionURL.1.stderr: ' + stderr);
if (err) {
//gOutputChannel.appendLine('openOnionURL.1.error: ' + err);
} else {
cp.exec(sCmd2, (err, stdout, stderr) => {
//gOutputChannel.appendLine('openOnionURL.2.stdout: ' + stdout);
//gOutputChannel.appendLine('openOnionURL.2.stderr: ' + stderr);
if (err) {
//gOutputChannel.appendLine('openOnionURL.2.error: ' + err);
}
});
}
});
*/
//gOutputChannel.appendLine(`openOnionURL: returning`);
}
//------------------------------------------------------------------------------
// Open normal (non-Onion) URL in browser.
export function openNormalURL(sURL: string) {
//gOutputChannel.appendLine(`openNormalURL: called, sURL '${sURL}'`);
//gOutputChannel.appendLine(`openNormalURL: call vscode.open, sURL '${sURL}'`);
commands.executeCommand('vscode.open', Uri.parse(sURL)); // ignores local files
//gOutputChannel.appendLine(`openNormalURL: returning`);
}
//------------------------------------------------------------------------------
// Open current selected URL in browser.
export function openURL() {
//gOutputChannel.appendLine(`openURL: called`);
let editor = window.activeTextEditor;
if (!editor) return;
let selection = editor.selection;
if (!selection) return;
let sURL = editor.document.getText(selection);
//let sURL = "https://3g22222222222222.onion/";
// want to move cursor from diagnostics pane to editor pane
// but can't figure out how to do it
//window.showTextDocument(editor);
//workbench.action.navigateToLastEditLocation
if (isOnionLink(sURL)) {
openOnionURL(sURL);
} else {
openNormalURL(sURL);
}
//gOutputChannel.appendLine(`openURL: returning`);
}
// Open current selected HTTP URL as HTTPS URL in browser.
export function openURLasHTTPS() {
//gOutputChannel.appendLine(`openURLasHTTPS: called`);
let editor = window.activeTextEditor;
if (!editor) return;
let selection = editor.selection;
if (!selection) return;
let sURL = editor.document.getText(selection);
if (isPlainHttpLink(sURL)) {
var sURLasHTTPS = sURL.slice(0, 4) + "s" + sURL.slice(4);
// want to move cursor from diagnostics pane to editor pane
// but can't figure out how to do it
//window.showTextDocument(editor);
//workbench.action.navigateToLastEditLocation
if (isOnionLink(sURLasHTTPS)) {
openOnionURL(sURLasHTTPS);
} else {
openNormalURL(sURLasHTTPS);
}
}
}
//------------------------------------------------------------------------------
// Clear all diagnostics belonging to this extension.
export function clearDiagnostics() {
//gOutputChannel.appendLine(`clearDiagnostics: called`);
// should free old array ? or dispose() on the collection ?
gDiagnosticsArray = new Array<Diagnostic>();
gDiagnosticsCollection.set(gDocument.uri,gDiagnosticsArray);
}
//------------------------------------------------------------------------------
// Read configuration values into global variables.
export function readConfiguration() {
//gOutputChannel.appendLine(`readConfiguration: called`);
gConfiguration = workspace.getConfiguration('linkcheckerhtml');
gnMaxParallelThreads = gConfiguration.maxParallelThreads;
if (gnMaxParallelThreads < 1)
gnMaxParallelThreads = 1;
if (gnMaxParallelThreads > 20)
gnMaxParallelThreads = 20;
gnTimeout = gConfiguration.timeout;
if (gnTimeout < 5)
gnTimeout = 5;
if (gnTimeout > 30)
gnTimeout = 30;
gbCheckInternalLinks = gConfiguration.checkInternalLinks;
gbProcessIdAttributeInAnyTag = gConfiguration.processIdAttributeInAnyTag;
gsAddExtensionToLocalURLsWithNone = gConfiguration.addExtensionToLocalURLsWithNone;
//gsAddExtensionToLocalURLsWithNone = "html"; // TEST ONLY
gsReportBadChars = gConfiguration.reportBadChars;
//gOutputChannel.appendLine(`readConfiguration: gsReportBadChars '${gsReportBadChars}'`);
// as Error, as Warning, as Information, Don't check and report
gBadCharsSeverity = DiagnosticSeverity.Information;
switch (gsReportBadChars[3]) {
case 'E': gBadCharsSeverity = DiagnosticSeverity.Error; break;
case 'W': gBadCharsSeverity = DiagnosticSeverity.Warning; break;
case 'I': gBadCharsSeverity = DiagnosticSeverity.Information; break;
case 'H': gBadCharsSeverity = DiagnosticSeverity.Hint; break;
}
gsPatternBadChars = gConfiguration.patternBadChars;
let sReportPossibleMistakes = gConfiguration.reportPossibleMistakes;
//gOutputChannel.appendLine(`readConfiguration: sReportPossibleMistakes '${sReportPossibleMistakes}'`);
// as Error, as Warning, as Information, Don't check and report
gbReportPossibleMistakes = false;
switch (sReportPossibleMistakes[3]) {
case 'E':
case 'W':
case 'I':
case 'H':
gbReportPossibleMistakes = true;
break;
}
//gOutputChannel.appendLine(`readConfiguration: gbReportPossibleMistakes ${gbReportPossibleMistakes}`);
gPossibleMistakesSeverity = DiagnosticSeverity.Information;
switch (sReportPossibleMistakes[3]) {
case 'E': gPossibleMistakesSeverity = DiagnosticSeverity.Error; break;
case 'W': gPossibleMistakesSeverity = DiagnosticSeverity.Warning; break;
case 'I': gPossibleMistakesSeverity = DiagnosticSeverity.Information; break;
case 'H': gPossibleMistakesSeverity = DiagnosticSeverity.Hint; break;
}
let sPatternsPossibleMistakes = gConfiguration.patternsPossibleMistakes;
//gOutputChannel.appendLine(`readConfiguration: sPatternsPossibleMistakes '${sPatternsPossibleMistakes}'`);
gaPatternPossibleMistakes = new Array<string>();
var possmists = sPatternsPossibleMistakes.match(/[^\,]+/gi);
//gOutputChannel.appendLine(`readConfiguration: possmists '${possmists}'`);
if (possmists) {
// Iterate over the values found in the comma-separated list
for (let i = 0; i< possmists.length; i++) {
// Get the value
var possmist = possmists[i].match(/[^\,]+/);
let sValue = possmist[0];
// Push it to the array
gaPatternPossibleMistakes.push(sValue);
}
}
//gOutputChannel.appendLine(`readConfiguration: gaPatternPossibleMistakes[0] ${gaPatternPossibleMistakes[0]}`);
//gOutputChannel.appendLine(`readConfiguration: gaPatternPossibleMistakes[1] ${gaPatternPossibleMistakes[1]}`);
//gOutputChannel.appendLine(`readConfiguration: gaPatternPossibleMistakes[2] ${gaPatternPossibleMistakes[2]}`);
let sReportHTTPSAvailable: string = gConfiguration.reportHTTPSAvailable;
//gOutputChannel.appendLine(`readConfiguration: sReportHTTPSAvailable '${sReportHTTPSAvailable}'`);
// as Error, as Warning, as Information, Don't check and report
gbReportHTTPSAvailable = false;
switch (sReportHTTPSAvailable[3]) {
case 'E':
case 'W':
case 'I':
case 'H':
gbReportHTTPSAvailable = true;
break;
}
//gOutputChannel.appendLine(`readConfiguration: gbReportHTTPSAvailable ${gbReportHTTPSAvailable}`);
gHTTPSAvailableSeverity = DiagnosticSeverity.Information;
switch (sReportHTTPSAvailable[3]) {
case 'E': gHTTPSAvailableSeverity = DiagnosticSeverity.Error; break;
case 'W': gHTTPSAvailableSeverity = DiagnosticSeverity.Warning; break;
case 'I': gHTTPSAvailableSeverity = DiagnosticSeverity.Information; break;
case 'H': gHTTPSAvailableSeverity = DiagnosticSeverity.Hint; break;
}
let sDontCheckCSL = gConfiguration.dontCheckURLsThatStartWith;
//gOutputChannel.appendLine(`readConfiguration: sDontCheckCSL '${sDontCheckCSL}'`);
gaDontCheck = new Array<string>();
var dontchecks = sDontCheckCSL.match(/[^\,]+/gi);
//gOutputChannel.appendLine(`readConfiguration: dontchecks '${dontchecks}'`);
if (dontchecks) {
// Iterate over the values found in the comma-separated list
for (let i = 0; i< dontchecks.length; i++) {
// Get the value
var dontcheck = dontchecks[i].match(/[^\,]+/);
let sValue = dontcheck[0];
// Push it to the array
gaDontCheck.push(sValue);
}
}
//gOutputChannel.appendLine(`readConfiguration: gaDontCheck[0] ${gaDontCheck[0]}`);
//gOutputChannel.appendLine(`readConfiguration: gaDontCheck[1] ${gaDontCheck[1]}`);
//gOutputChannel.appendLine(`readConfiguration: gaDontCheck[2] ${gaDontCheck[2]}`);
gsReportRedirects = gConfiguration.reportRedirects;
gReportRedirectSeverity = DiagnosticSeverity.Information;
switch (gsReportRedirects[3]) {
case 'E': gReportRedirectSeverity = DiagnosticSeverity.Error; break;
case 'W': gReportRedirectSeverity = DiagnosticSeverity.Warning; break;
case 'I': gReportRedirectSeverity = DiagnosticSeverity.Information; break;
case 'H': gReportRedirectSeverity = DiagnosticSeverity.Hint; break;
}
//gOutputChannel.appendLine(`readConfiguration: gsReportRedirects ${gsReportRedirects}`);
gsReportSemanticErrors = gConfiguration.reportSemanticErrors;
gSemanticSeverity = DiagnosticSeverity.Information;
switch (gsReportSemanticErrors[3]) {
case 'E': gSemanticSeverity = DiagnosticSeverity.Error; break;
case 'W': gSemanticSeverity = DiagnosticSeverity.Warning; break;
case 'I': gSemanticSeverity = DiagnosticSeverity.Information; break;
case 'H': gSemanticSeverity = DiagnosticSeverity.Hint; break;
}
//gOutputChannel.appendLine(`readConfiguration: gsReportSemanticErrors ${gsReportSemanticErrors}`);
gbReportSemanticErrors = false;
switch (gsReportSemanticErrors[3]) {
case 'E':
case 'W':
case 'I':
case 'H':
gbReportSemanticErrors = true;
break;
}
gsUserAgent = gConfiguration.userAgent;
//gOutputChannel.appendLine(`readConfiguration: gsUserAgent '${gsUserAgent}'`);
gsLocalRoot = gConfiguration.localRoot;
//gOutputChannel.appendLine(`readConfiguration: gsLocalRoot '${gsLocalRoot}'`);
gbCheckMailtoDestFormat = gConfiguration.checkMailtoDestFormat;
//gOutputChannel.appendLine(`readConfiguration: gbCheckMailtoDestFormat ${gbCheckMailtoDestFormat}`);
gsReportNonHandledSchemes = gConfiguration.reportNonHandledSchemes;
gReportNonHandledSchemesSeverity = DiagnosticSeverity.Information;
switch (gsReportNonHandledSchemes[3]) {
case 'E': gReportNonHandledSchemesSeverity = DiagnosticSeverity.Error; break;
case 'W': gReportNonHandledSchemesSeverity = DiagnosticSeverity.Warning; break;
case 'I': gReportNonHandledSchemesSeverity = DiagnosticSeverity.Information; break;
case 'H': gReportNonHandledSchemesSeverity = DiagnosticSeverity.Hint; break;
}
}
//------------------------------------------------------------------------------
// Generate a report of broken links and the line they occur on.
function generateLinkReport() {
//gOutputChannel.appendLine(`generateLinkReport: called`);
// Get the current document
gDocument = window.activeTextEditor.document;
//gOutputChannel.appendLine(`generateLinkReport: gDocument.fileName "${gDocument.fileName}"`);
//gOutputChannel.appendLine(`generateLinkReport: gDocument.languageId "${gDocument.languageId}"`);
myStatusBarItem.text = `Checking for broken links ...`;
myStatusBarItem.show();
/*
// wanted to implement a progress notification dialog, but it
// wasn't going to behave the way I wanted
gbDone = false;
gbCancelled = false;
window.withProgress({
location: ProgressLocation.Notification,
cancellable: true
}, (progress, token) => {
//gOutputChannel.appendLine(`generateLinkReport.withProgress: called`);
token.onCancellationRequested(() => {
//gOutputChannel.appendLine(`generateLinkReport.withProgress: got cancel`);
gbCancelled = true;
});
var p = updateProgressDialog(progress);
//gOutputChannel.appendLine(`generateLinkReport.withProgress: returning`);
return p;
}
);
function updateProgressDialog(progress): Promise<any> {
//gOutputChannel.appendLine(`updateProgressDialog: called`);
var p = null;
if (!gbDone && !gbCancelled) {
//gOutputChannel.appendLine(`updateProgressDialog: keep going`);
progress.report({ message: myStatusBarItem.text });
p = new Promise(resolve => {
if (!gbDone && !gbCancelled) {
setTimeout(() => {
//gOutputChannel.appendLine(`updateProgressDialog: timeout fired`);
updateProgressDialog(progress)
}, 1000);
}
});
} else {
// whoops; want to get rid of the progress dialog here,
// but turns out the API does not provide for that,
// user has to close the dialog manually.
}
//gOutputChannel.appendLine(`updateProgressDialog: returning`);
return p;
}
*/
clearDiagnostics();
/*
var diag = new Diagnostic(new Range(new Position(1,10),new Position(2,20)), "message", DiagnosticSeverity.Error);
gDiagnosticsArray.push(diag);
gDiagnosticsCollection.set(gDocument.uri,gDiagnosticsArray);
*/
readConfiguration();
if (gsReportBadChars[0] != 'D') {
// scan text for bad characters
let p4 = checkBadChars(gDocument);
p4.then((sResult) => {
//gOutputChannel.appendLine(`generateLinkReport.p4.then: called`);
});
}
if (gbReportPossibleMistakes) {
// scan text for possible mistakes
let p3 = checkPossibleMistakes(gDocument);
p3.then((sResult) => {
//gOutputChannel.appendLine(`generateLinkReport.p3.then: called`);
});
}
if (gbReportSemanticErrors
&& ((gDocument.languageId == 'html')||(gDocument.languageId == 'php'))) {
// scan text for possible errors in semantic HTML
let p5 = scanSemanticHTML(gDocument);
p5.then((sResult) => {
//gOutputChannel.appendLine(`generateLinkReport.p5.then: called`);
});
}
// Possible race-condition if there are no tags to check ?
// We never wait for p3-p5 to complete.
gLocalAnchorNames = new Array<string>();
// Get all links in the document
var p1 = null;
switch (gDocument.languageId) {
case 'html': p1 = getHtmlLinks(gDocument); break;
case 'php': p1 = getHtmlLinks(gDocument); break;
case 'xml': p1 = getXmlRssLinks(gDocument); break;
case 'markdown': p1 = getMarkdownLinks(gDocument); break;
// apparently RSS gets reported as XML
}
p1.then((links: Link[]) => {
// callback function for the "success" branch of the p1 Promise
// Promise resolved now, so we're in a different context than before
//gOutputChannel.appendLine(`generateLinkReport.p1.then: got ${links.length} links`);
gStartingNLinks = links.length;
myStatusBarItem.text = `Checking ${gStartingNLinks} links ...`;
myStatusBarItem.show();
let p2 = throttleActions(links, gnMaxParallelThreads);
p2.then((links) => {
//gOutputChannel.appendLine(`generateLinkReport.p2.then: called`);
gLocalAnchorNames = null;
myStatusBarItem.text = ``;
myStatusBarItem.show();
gbDone = true;
//gOutputChannel.appendLine(`generateLinkReport.p2.then: all done`);
});
});
//gOutputChannel.appendLine(`generateLinkReport: returning`);
}
//------------------------------------------------------------------------------
// Performs a list of callable actions (promise factories) so that only a limited
// number of promises are pending at any given time.
//
// Returns A Promise that resolves to the full list of values when everything is done.
function throttleActions(links: Array<Link>, limit: number): Promise<any> {
//gOutputChannel.appendLine(`throttleActions: called, ${links.length} links, limit ${limit}`);
// We'll need to store which is the next promise in the list.
let i = 0;
// Now define what happens when any of the actions completes. Javascript is
// (mostly) single-threaded, so only one completion handler will call at a
// given time. Because we return doNextAction, the Promise chain continues as
// long as there's an action left in the list.
function doNextAction() {
//gOutputChannel.appendLine(`doNextAction: called, ${links.length-i} links left`);
if (gbCancelled)
return null;
if (i < links.length)
myStatusBarItem.text = `Checking ${gStartingNLinks} links, ${links.length-i} more to do ...`;
else
myStatusBarItem.text = `Checking ${gStartingNLinks} links, waiting for last few to complete ...`;
myStatusBarItem.show();
if (i < links.length) {
// Save the current value of i, so we can put the result in the right place
let linkIndex = i++;
//gOutputChannel.appendLine(`doNextAction: returning`);
return Promise.resolve(doALink(links[linkIndex]))
.then(result => {
//gOutputChannel.appendLine(`doNextAction: result`);
return null;
})
.catch(error => {
//gOutputChannel.appendLine(`doNextAction: catch4`);
})
.then(doNextAction);
}
}
// Now start up the original <limit> number of promises.
// i advances in calls to doNextAction.
let listOfPromises = [];
while (i < limit && i < links.length) {
listOfPromises.push(doNextAction());
}
//gOutputChannel.appendLine(`throttleActions: returning, listOfPromises.length ${listOfPromises.length}`);
return Promise.all(listOfPromises);
}
//------------------------------------------------------------------------------
function doALink(link: Link): Promise<null> {
//gOutputChannel.appendLine(`doALink: called, link.address '${link.address}'`);
/*
var diag = null;
diag = new Diagnostic(new Range(new Position(1,10),new Position(2,20)), "messageHHHH", DiagnosticSeverity.Error);
gDiagnosticsArray.push(diag);
gDiagnosticsCollection.set(gDocument.uri,gDiagnosticsArray);
*/
//gOutputChannel.appendLine(`doALink: link on line ${link.lineText.lineNumber + 1} is ${link.address}'`);
let lineNumber = link.lineText.lineNumber;
var myPromise = null;
// Is it a Tor/onion link?
if (isOnionLink(link.address)) {
//gOutputChannel.appendLine(`doALink: onion link address '${link.address}'`);
var address = link.address;
let sDomain = getDomainFromOnionLink(address);
//gOutputChannel.appendLine(`doALink: sDomain '${sDomain}'`);
if ((sDomain.length != 22) && (sDomain.length != 62)) {
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(sDomain),
sDomain.length,
DiagnosticSeverity.Warning,
`Onion domain '${sDomain}' is wrong length; must be 16 or 56 characters plus '.onion'`
);
}
//gOutputChannel.appendLine(`doALink: onion address '${address}'`);
/*
torreq.request(
//'https://api.ipify.org',
address,
function (err, res, body) {
//gOutputChannel.appendLine(`doALink: torreq.request gave err "${err}", res "${res}"`);
if (!err) {
//gOutputChannel.appendLine(`doALink: res.statusCode ${res.statusCode}`);
////gOutputChannel.appendLine(`doALink: res ${JSON.stringify(res)}`);
} else {
//gOutputChannel.appendLine(`doALink: err "${err}"`);
////gOutputChannel.appendLine(`doALink: err ${JSON.stringify(err)}`);
}
}
);
*/
myPromise = new Promise((resolve, reject) => {
torreq.request(address, true, (err, res, body) => {
//gOutputChannel.appendLine(`doALink.torreq: returned err "${err}", res "${res}" for "${address}"`);
//return (err ? reject(err) : resolve(res.statusCode))
if (err)
reject(err);
else
resolve(res.statusCode);
});
});
myPromise.then(
(response) =>
{
// callback function for the "result" branch of the torreq Promise
//gOutputChannel.appendLine(`doALink.torreqPromise.then: got response "${response}" for "${link.address}"`);
if ((response >= 400) && (response < 600)) {
//gOutputChannel.appendLine(`doALink.torreqPromise.then: ${address} on line ${lineNumber} is unreachable.`);
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
DiagnosticSeverity.Error,
`Onion address '${address}' is unreachable: ${response}`
);
}
},
(error) =>
{
//gOutputChannel.appendLine(`doALink.torreqPromise.then: error: "${error}" for "${link.address}"`);
var sError = error.toString();
if (sError.includes('ECONNREFUSED 127.0.0.1:9050')) {
sError = "Can't check onion URLs: no Tor/socks service listening on 127.0.0.1:9050";
}
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
DiagnosticSeverity.Error,
`Onion address '${address}' is not reachable: ${sError}`
);
}
);
}
// Is it an HTTP* link or a relative link?
else if (isHttpLink(link.address)) {
// And check if they are broken or not.
var address = link.address;
if (link.bDoHTTPSForm)
address = link.address.slice(0, 4) + "s" + link.address.slice(4);
//gOutputChannel.appendLine(`doALink: address '${address}'`);
myPromise = axios.get(address,
{
validateStatus: null,
timeout: (gnTimeout * 1000),
maxRedirects: ((gsReportRedirects[0]!='D') ? 0 : 4),
headers: {'User-Agent': `${gsUserAgent}`}
});
myPromise.then(
(response) =>
{
// callback function for the "result" branch of the axios Promise
//gOutputChannel.appendLine(`doALink.axiosPromise.then: got response for url ${response.config.url}: ${response.status} (${response.statusText})`);
// JSON.stringify(response.request) gives circularity error
//gOutputChannel.appendLine(`doALink.axiosPromise.then: response.config ${JSON.stringify(response.config)}`);
//gOutputChannel.appendLine(`doALink.axiosPromise.then: response.headers ${JSON.stringify(response.headers)}`);
////gOutputChannel.appendLine(`doALink.axiosPromise.then: response.data ${JSON.stringify(response.data)}`);
//if (response.status === 301) {
// //gOutputChannel.appendLine(`doALink.axiosPromise.then: redirected to response.headers.location ${JSON.stringify(response.headers.location)}`);
//}
var nIndexOfQuestionMarkInLocation = 0;
if ((response.status > 300) && (response.status < 400))
nIndexOfQuestionMarkInLocation = response.headers.location.indexOf("?");
// as Error, as Warning, as Information, Don't report
if ((response.status > 400) && (response.status < 600)) {
//gOutputChannel.appendLine(`doALink.axiosPromise.then: ${link.address} on line ${lineNumber} is unreachable.`);
if (!link.bDoHTTPSForm) {
// HTTP form of link, and it's not found
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
DiagnosticSeverity.Error,
`'${address}' is unreachable: ${response.status} (${response.statusText})`
);
}
// else HTTPS form of HTTP link, and it's not found, don't report
} else if (((response.status > 300) && (response.status < 400))
&& (response.headers.location === response.config.url)) {
// response code says it redirected, but in fact old location is same as new location
// hardly ever get this case, often the new location is just "/", or has "/" or ".html" added
// do nothing
//gOutputChannel.appendLine(`doALink.axiosPromise.then: old location matches new location.`);
} else if (((response.status > 300) && (response.status < 400))
&& (nIndexOfQuestionMarkInLocation > 0)
&& (response.headers.location.substring(0,nIndexOfQuestionMarkInLocation) === response.config.url)) {
// response code says it redirected, but new location is just old location with "?something" appended
// hardly ever get this case, often new location is different
// do nothing
//gOutputChannel.appendLine(`doALink.axiosPromise.then: old location matches new location plus question mark.`);
} else if ((gsReportRedirects[0]!='D') && ((response.status > 300) && (response.status < 400))) {
//gOutputChannel.appendLine(`doALink.axiosPromise.then: ${link.address} on line ${lineNumber} redirected.`);
// redirected to response.headers.location
//gOutputChannel.appendLine(`doALink.axiosPromise.then: ${response.config.url}`);
//gOutputChannel.appendLine(`doALink.axiosPromise.then: ${response.config.headers}`);
if (!link.bDoHTTPSForm) {
// HTTP form of link, and it redirected
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
gReportRedirectSeverity,
`'${address}' redirects; ${response.status} (${response.statusText})${(response.headers.location ? "; "+response.headers.location : "")}`
);
} else {
// else HTTPS form of HTTP link, and it's found and redirected
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
gHTTPSAvailableSeverity,
`HTTPS form of '${link.address}' is available; ${response.status} (${response.statusText})${(response.headers.location ? "; "+response.headers.location : "")}`
);
}
} else {
//gOutputChannel.appendLine(`doALink.axiosPromise.then: ${link.address} on line ${lineNumber} is accessible.`);
if (link.bDoHTTPSForm) {
// HTTPS form of link, and it is accessible
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
gHTTPSAvailableSeverity,
`HTTPS form of '${link.address}' is available; ${response.status} (${response.statusText})${(response.headers.location ? "; "+response.headers.location : "")}`
);
}
}
},
(error) =>
{
//gOutputChannel.appendLine(`doALink.axiosPromise.catch0: ${link.address} error: ${error}`);
addDiagnostic(
lineNumber,
link.lineText.text.indexOf(link.address),
link.address.length,
DiagnosticSeverity.Error,
`'${address}' is not reachable: ${error}`
);
//gOutputChannel.appendLine(`doALink.axiosPromise.catch0: end`);
}
).catch(
(error) =>
{
if (error.response) {
//gOutputChannel.appendLine(`doALink.axiosPromise.catch1: ${link.address} error: ${error}, response ${error.response}`);
} else if (error.request) {
//gOutputChannel.appendLine(`doALink.axiosPromise.catch1: ${link.address} error: ${error}, request ${error.request}`);
} else {