-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnassh_command_instance.js
1980 lines (1711 loc) · 61.5 KB
/
nassh_command_instance.js
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
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* @suppress {moduleLoad}
*/
import {punycode} from './nassh_deps.rollup.js';
/**
* The NaCl-ssh-powered terminal command.
*
* This class defines a command that can be run in an hterm.Terminal instance.
* This command creates an instance of the NaCl-ssh plugin and uses it to
* communicate with an ssh daemon.
*
* If you want to use something other than this NaCl plugin to connect to a
* remote host (like a shellinaboxd, etc), you'll want to create a brand new
* command.
*
* @param {!Object} argv The argument object passed in from the Terminal.
* @constructor
*/
nassh.CommandInstance = function(argv) {
// Command arguments.
this.argv_ = argv;
// Command environment.
this.environment_ = argv.environment || {};
// hterm.Terminal.IO instance (can accept another hterm.Terminal.IO instance).
this.io = argv.terminalIO || null;
// Relay manager.
this.relay_ = null;
// Parsed extension manifest.
this.manifest_ = null;
// The HTML5 persistent FileSystem instance for this extension.
this.fileSystem_ = null;
// A set of open streams for this instance.
this.streams_ = new nassh.StreamSet();
// The version of the ssh client to load.
this.sshClientVersion_ = 'pnacl';
// Application ID of auth agent.
this.authAgentAppID_ = null;
// Internal SSH agent.
this.authAgent_ = null;
// Whether the instance is a SFTP instance.
this.isSftp = argv.isSftp || false;
// SFTP Client for SFTP instances.
this.sftpClient = (this.isSftp) ? new nassh.sftp.Client(argv.basePath) : null;
// Whether we're setting up the connection for mounting.
this.isMount = argv.isMount || false;
// Mount options for a SFTP instance.
this.mountOptions = argv.mountOptions || null;
// Session storage (can accept another hterm tab's sessionStorage).
this.storage = argv.terminalStorage || window.sessionStorage;
// Terminal Location reference (can accept another hterm tab's location).
this.terminalLocation = argv.terminalLocation || document.location;
// Terminal Window reference (can accept another hterm tab's window).
this.terminalWindow = argv.terminalWindow || window;
/**
* @type {?string} The current connection profile.
*/
this.profileId_ = null;
// Root preference managers.
this.prefs_ = new nassh.PreferenceManager();
this.localPrefs_ = new nassh.LocalPreferenceManager();
// Prevent us from reporting an exit twice.
this.exited_ = false;
// Buffer for data coming from the terminal.
this.inputBuffer_ = new nassh.InputBuffer();
};
/**
* The name of this command used in messages to the user.
*
* Perhaps this will also be used by the user to invoke this command if we
* build a command line shell.
*/
nassh.CommandInstance.prototype.commandName = 'nassh';
/**
* Static run method invoked by the terminal.
*
* @param {!Object} argv
* @return {!nassh.CommandInstance}
*/
nassh.CommandInstance.run = function(argv) {
return new nassh.CommandInstance(argv);
};
/**
* When the command exit is from nassh instead of ssh_client. The ssh module
* can only ever exit with positive values, so negative values are reserved.
*/
nassh.CommandInstance.EXIT_INTERNAL_ERROR = -1;
/**
* Start the nassh command.
*
* Instance run method invoked by the nassh.CommandInstance ctor.
*/
nassh.CommandInstance.prototype.run = function() {
// Useful for console debugging.
window.nassh_ = this;
this.io = this.argv_.io.push();
// In case something goes horribly wrong, display an error to the user so it's
// easier for them to copy & paste when reporting issues.
window.addEventListener('error', (e) => {
this.io.println(nassh.msg('UNEXPECTED_ERROR'));
const lines = e.error.stack.split(/[\r\n]/);
lines.forEach((line) => this.io.println(line));
});
// Similar to lib.fs.err, except this logs to the terminal too.
const ferr = (msg) => {
return (err, ...args) => {
console.error(`${msg}: ${args.join(', ')}`);
this.io.println(nassh.msg('UNEXPECTED_ERROR'));
this.io.println(err);
};
};
this.prefs_.readStorage(() => {
this.manifest_ = chrome.runtime.getManifest();
// Set default window title.
this.io.print('\x1b]0;' + this.manifest_.name + ' ' +
this.manifest_.version + '\x07');
showWelcome();
nassh.getFileSystem()
.then(onFileSystemFound)
.catch(ferr('FileSystem init failed'));
this.localPrefs_.readStorage(() => {
this.localPrefs_.syncProfiles(this.prefs_);
const updater = this.updateWindowDimensions_.bind(this);
window.addEventListener('resize', updater);
// Window doesn't offer a 'move' event, and blur/resize don't seem to
// work. Listening for mouseout should be low enough overhead.
window.addEventListener('mouseout', updater);
});
});
const showWelcome = () => {
const style = {bold: true};
this.io.println(nassh.msg(
'WELCOME_VERSION',
[nassh.sgrText(this.manifest_.name, style),
nassh.sgrText(this.manifest_.version, style)]));
this.io.println(nassh.msg(
'WELCOME_FAQ',
[nassh.sgrText('https://goo.gl/muppJj', style)]));
if (hterm.windowType != 'popup' && hterm.os != 'mac') {
this.io.println('');
this.io.println(nassh.msg(
'OPEN_AS_WINDOW_TIP',
[nassh.sgrText('https://goo.gl/muppJj', style)]));
this.io.println('');
}
// Show some release highlights the first couple of runs with a new version.
// We'll reset the counter when the release notes change.
this.io.println(nassh.msg(
'WELCOME_CHANGELOG',
[nassh.sgrText(nassh.osc8Link('/html/changelog.html'), style)]));
const notes = lib.resource.getData('nassh/release/highlights');
if (this.prefs_.getNumber('welcome/notes-version') != notes.length) {
// They upgraded, so reset the counters.
this.prefs_.set('welcome/show-count', 0);
this.prefs_.set('welcome/notes-version', notes.length);
}
// Figure out how many times we've shown this.
const notesShowCount = this.prefs_.getNumber('welcome/show-count');
if (notesShowCount < 10) {
// For new runs, show the highlights directly.
this.io.print(nassh.msg('WELCOME_RELEASE_HIGHLIGHTS',
[lib.resource.getData('nassh/release/lastver')]));
this.io.println(notes.replace(/%/g, '\r\n \u00A4'));
this.prefs_.set('welcome/show-count', notesShowCount + 1);
}
// Display a random tip every time they launch to advertise features.
const num = lib.f.randomInt(1, 14);
this.io.println('');
this.io.println(nassh.msg('WELCOME_TIP_OF_DAY',
[num, nassh.msg(`TIP_${num}`)]));
this.io.println('');
if (this.manifest_.name.match(/\((dev|tot)\)/)) {
// If we're a development version, show hterm details.
const htermDate = lib.resource.getData('hterm/concat/date');
const htermVer = lib.resource.getData('hterm/changelog/version');
const htermRev = lib.resource.getData('hterm/git/HEAD');
const htermAgeMinutes =
Math.round((new Date().getTime() - new Date(htermDate).getTime()) /
1000 / 60);
this.io.println(`[dev] hterm v${htermVer} (git ${htermRev})`);
this.io.println(`[dev] built on ${htermDate} ` +
`(${htermAgeMinutes} minutes ago)`);
}
};
const onFileSystemFound = (fileSystem) => {
this.fileSystem_ = fileSystem;
const argstr = this.argv_.args.join(' ');
// This item is set before we redirect away to login to a relay server.
// If it's set now, it's the first time we're reloading after the redirect.
const pendingRelay = this.storage.getItem('nassh.pendingRelay');
this.storage.removeItem('nassh.pendingRelay');
if (!argstr || (this.storage.getItem('nassh.promptOnReload') &&
!pendingRelay)) {
// If promptOnReload is set or we haven't gotten the destination
// as an argument then we need to ask the user for the destination.
//
// The promptOnReload session item allows us to remember that we've
// displayed the dialog, so we can re-display it if the user reloads
// the page. (Items in sessionStorage are scoped to the tab, kept
// between page reloads, and discarded when the tab goes away.)
this.storage.setItem('nassh.promptOnReload', 'yes');
this.promptForDestination_();
} else {
const params = new URLSearchParams(this.terminalLocation.search);
// An undocumented hack for extension popup to force a one-off connection.
if (params.get('promptOnReload') == 'yes') {
this.storage.setItem('nassh.promptOnReload', 'yes');
}
this.connectToArgString(argstr);
}
};
};
/**
* Reconnects to host, using the same CommandInstance.
*
* @param {string} argstr The connection ArgString.
*/
nassh.CommandInstance.prototype.reconnect = function(argstr) {
// Terminal reset.
this.io.print('\x1b[!p');
this.io = this.argv_.io.push();
this.removePlugin_();
this.stdoutAcknowledgeCount_ = 0;
this.stderrAcknowledgeCount_ = 0;
this.exited_ = false;
this.connectToArgString(argstr);
};
/**
* Event for when the window dimensions change.
*/
nassh.CommandInstance.prototype.updateWindowDimensions_ = function() {
if (!this.profileId_) {
// We haven't connected yet, so nothing to save.
return;
}
// The web platform doesn't provide a way to check the window state, so use
// Chrome APIs directly for that.
chrome.windows.getCurrent((win) => {
// Ignore minimized state completely.
if (win.state === 'minimized') {
return;
}
const profile = this.localPrefs_.getProfile(lib.notNull(this.profileId_));
profile.set('win/state', win.state);
// Only record dimensions when we're not fullscreen/maximized. This allows
// the position/size to be remembered independent of temporarily going to
// the max screen dimensions.
if (win.state === 'normal') {
profile.set('win/top', window.screenTop);
profile.set('win/left', window.screenLeft);
profile.set('win/height', window.outerHeight);
profile.set('win/width', window.outerWidth);
}
});
};
/** Prompt for destination */
nassh.CommandInstance.prototype.promptForDestination_ = function() {
const connectDialog = this.io.createFrame(
lib.f.getURL('/html/nassh_connect_dialog.html'), null);
connectDialog.onMessage = (event) => {
event.data.argv.unshift(connectDialog);
this.dispatchMessage_('connect-dialog', this.onConnectDialog_, event.data);
};
// Resize the connection dialog iframe to try and fit all the content,
// but not more. This way we don't end up with a lot of empty space.
function resize() {
const body = this.iframe_.contentWindow.document.body;
const shortcutList = body.querySelector('#shortcut-list');
const dialogBillboard = body.querySelector('.dialog-billboard');
const dialogButtons = body.querySelector('.dialog-buttons');
this.container_.style.height = '0px';
let height = shortcutList.scrollHeight +
dialogBillboard.scrollHeight +
dialogButtons.scrollHeight;
// Since the document has a bit of border/padding, fudge the height
// slightly higher than the few main elements we calculated above.
height *= 1.15;
// We don't have to worry about this being too big or too small as the
// frame CSS has set min/max height attributes.
this.container_.style.height = height + 'px';
}
// Once the dialog has finished loading all of its data, resize it.
connectDialog.onLoad = function() {
// Shift the dialog to be relative to the bottom so the notices/links we
// show at the top of the are more readily visible.
this.container_.style.top = '';
this.container_.style.bottom = '10%';
const resize_ = resize.bind(this);
resize_();
window.addEventListener('resize', resize_);
this.onClose = () => {
window.removeEventListener('resize', resize_);
};
};
// Clear retry count whenever we show the dialog.
window.sessionStorage.removeItem('googleRelay.redirectCount');
connectDialog.show();
};
/** @param {string} argstr */
nassh.CommandInstance.prototype.connectToArgString = function(argstr) {
const isMount = (this.storage.getItem('nassh.isMount') == 'true');
const isSftp = (this.storage.getItem('nassh.isSftp') == 'true');
this.storage.removeItem('nassh.isMount');
this.storage.removeItem('nassh.isSftp');
// Handle profile-id:XXX forms. These are bookmarkable.
const ary = argstr.match(/^profile-id:([a-z0-9]+)(\?.*)?/i);
if (ary) {
if (isMount) {
this.mountProfile(ary[1]);
} else if (isSftp) {
this.sftpConnectToProfile(ary[1]);
} else {
this.connectToProfile(ary[1]);
}
} else {
if (isMount) {
this.mountDestination(argstr);
} else if (isSftp) {
this.sftpConnectToDestination(argstr);
} else {
this.connectToDestination(argstr);
}
}
};
/**
* Common phases that we run before making an actual connection.
*
* @param {string} profileID Terminal preference profile name.
* @param {function(!nassh.PreferenceManager)} callback Callback when the prefs
* have finished loading.
*/
nassh.CommandInstance.prototype.commonProfileSetup_ = function(
profileID, callback) {
const onReadStorage = () => {
let prefs;
try {
prefs = this.prefs_.getProfile(profileID);
} catch (e) {
this.io.println(nassh.msg('GET_PROFILE_ERROR', [profileID, e]));
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
return;
}
this.profileId_ = profileID;
document.querySelector('#terminal').focus();
this.terminalLocation.hash = 'profile-id:' + profileID;
document.title = prefs.get('description') + ' - ' +
this.manifest_.name + ' ' + this.manifest_.version;
callback(prefs);
};
// Re-read prefs from storage in case they were just changed in the connect
// dialog.
this.prefs_.readStorage(onReadStorage);
};
/**
* Turn a prefs object into the params object connectTo expects.
*
* @param {!Object} prefs
* @return {!Object}
*/
nassh.CommandInstance.prototype.prefsToConnectParams_ = function(prefs) {
return {
username: prefs.get('username'),
hostname: prefs.get('hostname'),
port: prefs.get('port'),
nasshOptions: prefs.get('nassh-options'),
identity: prefs.get('identity'),
argstr: prefs.get('argstr'),
terminalProfile: prefs.get('terminal-profile'),
};
};
/**
* Mount a remote host given a profile id. Creates a new SFTP CommandInstance
* that runs in the background page.
*
* @param {string} profileID Terminal preference profile name.
*/
nassh.CommandInstance.prototype.mountProfile = function(profileID) {
const port = chrome.runtime.connect({name: 'mount'});
// The main event loop -- process messages from the bg page.
port.onMessage.addListener((msg) => {
const {error, message, command} = msg;
// Handle all error messages here.
if (error) {
io.println(message);
io.pop();
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
port.disconnect();
return;
}
switch (command) {
case 'write':
// Display content to the user.
io.print(message);
break;
case 'overlay':
// Display the UI popup.
io.showOverlay(message, msg.timeout);
break;
case 'exit':
case 'done':
// The client has exited (bad), or the mount setup is done (good).
port.disconnect();
if (command === 'done') {
io.showOverlay(nassh.msg('MOUNTED_MESSAGE') + ' ' +
nassh.msg('CONNECT_OR_EXIT_MESSAGE'), null);
} else {
io.println(nassh.msg('DISCONNECT_MESSAGE', [msg.status]));
}
// Put the IO into dummy mode for the most part.
io.onVTKeystroke = (string) => {
const ch = string.toLowerCase();
switch (ch) {
case 'c':
case '\x12': // ctrl-r
this.terminalLocation.hash = '';
this.terminalLocation.reload();
break;
case 'e':
case 'x':
case '\x1b': // ESC
case '\x17': // ctrl-w
this.terminalWindow.close();
}
};
io.sendString = () => {};
break;
default:
io.println(`internal error: unknown command '${command}'`);
port.disconnect();
io.pop();
break;
}
});
// Not sure there's much else to do here.
port.onDisconnect.addListener(() => {
console.log('disconnect');
});
// Send all user input to the background page.
const io = this.io.push();
io.onVTKeystroke = io.sendString = (string) => {
port.postMessage({command: 'write', data: string});
};
// Once we've loaded prefs from storage, kick off the mount in the bg.
const onStartup = (prefs) => {
this.isMount = true;
this.isSftp = true;
const params = this.prefsToConnectParams_(prefs);
this.connectTo(params, () => {
if (this.relay_) {
params.relayState = this.relay_.saveState();
}
port.postMessage({
command: 'connect',
argv: {
isSftp: true,
basePath: prefs.get('mount-path'),
isMount: true,
// Mount options are passed directly to Chrome's FSP mount(),
// so don't add fields here that would otherwise collide.
mountOptions: {
fileSystemId: prefs.id,
displayName: prefs.get('description'),
writable: true,
},
},
connectOptions: params,
});
});
};
this.commonProfileSetup_(profileID, onStartup);
};
/**
* Creates a new SFTP CommandInstance that runs in the background page.
*
* @param {string} profileID Terminal preference profile name.
*/
nassh.CommandInstance.prototype.sftpConnectToProfile = function(profileID) {
const onStartup = (prefs) => {
this.isSftp = true;
this.sftpClient = new nassh.sftp.Client();
this.connectTo(this.prefsToConnectParams_(prefs));
};
this.commonProfileSetup_(profileID, onStartup);
};
/**
* Initiate a connection to a remote host given a profile id.
*
* @param {string} profileID Terminal preference profile name.
*/
nassh.CommandInstance.prototype.connectToProfile = function(profileID) {
const onStartup = (prefs) => {
this.connectTo(this.prefsToConnectParams_(prefs));
};
this.commonProfileSetup_(profileID, onStartup);
};
/**
* Parse ssh:// URIs.
*
* This supports the IANA spec:
* https://www.iana.org/assignments/uri-schemes/prov/ssh
* ssh://[<user>[;fingerprint=<hash>]@]<host>[:<port>]
*
* It also supports Secure Shell extensions to the protocol:
* ssh://[<user>@]<host>[:<port>][@<relay-host>[:<relay-port>]]
*
* Note: We don't do IPv4/IPv6/hostname validation. That's a DNS/connectivity
* problem and user error.
*
* @param {string} uri The URI to parse.
* @param {boolean=} stripSchema Whether to strip off ssh:// at the start.
* @param {boolean=} decodeComponents Whether to unescape percent encodings.
* @return {?Object} Returns null if we couldn't parse the destination.
* An object if we were able to parse out the connect settings.
*/
nassh.CommandInstance.parseURI = function(uri, stripSchema = true,
decodeComponents = false) {
let schema;
if (stripSchema) {
schema = uri.split(':', 1)[0];
if (schema === 'ssh' || schema === 'web+ssh' || schema === 'sftp' ||
schema === 'web+sftp') {
// Strip off the schema prefix.
uri = uri.substr(schema.length + 1);
if (schema.startsWith('web+')) {
schema = schema.substr(4);
}
} else {
schema = undefined;
}
// Strip off the "//" if it exists.
if (uri.startsWith('//')) {
uri = uri.substr(2);
}
}
// For empty URIs, show the connection dialog.
if (uri === '') {
return {hostname: '>connections'};
}
/* eslint-disable max-len,spaced-comment */
// Parse the connection string.
const ary = uri.match(
//|user |@| [ ipv6 %zoneid ]| host | :port |@| [ ipv6 %zoneid ]|relay| :relay port |
/^(?:([^@]*)@)?(\[[:0-9a-f]+(?:%[^\]]+)?\]|[^:@]+)(?::(\d+))?(?:@(\[[:0-9a-f]+(?:%[^\]]+)?\]|[^:]+)(?::(\d+))?)?$/);
/* eslint-enable max-len,spaced-comment */
if (!ary) {
return null;
}
const params = {};
let username = ary[1];
let hostname = ary[2];
const port = ary[3];
// If the hostname starts with bad chars, reject it. We use these internally,
// so don't want external links to access them too. We probably should filter
// out more of the ASCII space.
if (hostname.startsWith('>')) {
return null;
}
// If it's IPv6, remove the brackets.
if (hostname.startsWith('[') && hostname.endsWith(']')) {
hostname = hostname.substr(1, hostname.length - 2);
}
let relayHostname, relayPort;
if (ary[4]) {
relayHostname = ary[4];
// If it's IPv6, remove the brackets.
if (relayHostname.startsWith('[') && relayHostname.endsWith(']')) {
relayHostname = relayHostname.substr(1, relayHostname.length - 2);
}
if (ary[5]) {
relayPort = ary[5];
}
}
const decode = (x) => decodeComponents && x ? unescape(x) : x;
if (username) {
// See if there are semi-colon delimited options following the username.
// Arguments should be URI encoding their values.
const splitParams = username.split(';');
username = splitParams[0];
splitParams.slice(1, splitParams.length).forEach((param) => {
// This will take the first '=' appearing from left to right and take
// what's on its left as the param's name and what's to its right as its
// value. For example, if we have '-nassh-args=--proxy-mode=foo' then
// '-nassh-args' will be the name of the param and
// '--proxy-mode=foo' will be its value.
const key = param.split('=', 1)[0];
const validKeys = new Set([
'fingerprint', '-nassh-args', '-nassh-ssh-args',
]);
if (validKeys.has(key)) {
const value = param.substr(key.length + 1);
if (value) {
params[key.replace(/^-/, '')] = decode(value);
}
} else {
console.error(`${key} is not a valid parameter so it will be skipped`);
}
});
}
// We don't decode the hostname or port. Valid values for both shouldn't
// need it, and probably could be abused.
return Object.assign({
username: decode(username),
hostname: hostname,
port: port,
relayHostname: relayHostname,
relayPort: relayPort,
schema: schema,
uri: uri,
}, params);
};
/**
* Parse the destination string.
*
* These are strings that we get from the browser bar. It's mostly ssh://
* URIs, but it might have more stuff sprinkled in to smooth communication
* with various entry points into Secure Shell.
*
* @param {string} destination The string to connect to.
* @return {?Object} Returns null if we couldn't parse the destination.
* An object if we were able to parse out the connect settings.
*/
nassh.CommandInstance.parseDestination = function(destination) {
let stripSchema = false;
let decodeComponents = false;
// Deal with ssh:// links. They are encoded with % hexadecimal sequences.
// Note: These might be ssh: or ssh://, so have to deal with that.
if (destination.startsWith('uri:')) {
// Strip off the "uri:" before decoding it.
destination = unescape(destination.substr(4));
const schema = destination.split(':', 1)[0];
if (schema !== 'ssh' && schema !== 'web+ssh' && schema !== 'sftp' &&
schema !== 'web+sftp') {
return null;
}
stripSchema = true;
decodeComponents = true;
}
const rv = nassh.CommandInstance.parseURI(destination, stripSchema,
decodeComponents);
if (rv === null) {
return rv;
}
// Turn the relay URI settings into nassh command line options.
let nasshOptions;
if (rv.relayHostname !== undefined) {
nasshOptions = '--proxy-host=' + rv.relayHostname;
if (rv.relayPort !== undefined) {
nasshOptions += ' --proxy-port=' + rv.relayPort;
}
}
rv.nasshOptions = nasshOptions;
rv.nasshUserOptions = rv['nassh-args'];
rv.nasshUserSshOptions = rv['nassh-ssh-args'];
// If the fingerprint is set, maybe add it to the known keys list.
return rv;
};
/**
* Initiate a connection to a remote host given a destination string.
*
* @param {string} destination A string of the form username@host[:port].
*/
nassh.CommandInstance.prototype.connectToDestination = function(destination) {
if (destination == 'crosh') {
this.terminalLocation.href = 'crosh.html';
return;
}
const rv = nassh.CommandInstance.parseDestination(destination);
if (rv === null) {
this.io.println(nassh.msg('BAD_DESTINATION', [destination]));
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
return;
}
if (rv.schema === 'sftp') {
this.sftpConnectToDestination(destination);
return;
}
// We have to set the url here rather than in connectToArgString, because
// some callers may come directly to connectToDestination.
this.terminalLocation.hash = destination;
this.connectTo(rv);
};
/**
* Mount a remote host given a destination string.
*
* @param {string} destination A string of the form username@host[:port].
*/
nassh.CommandInstance.prototype.mountDestination = function(destination) {
// This code path should currently be unreachable. If that ever changes,
// we can look at merging with the mountProfile code.
this.io.println('Not implemented; please file a bug.');
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
};
/**
* Split the ssh command line string up into its components.
*
* We currently only support simple quoting -- no nested or escaped.
* That would require a proper lexer in here and not utilize regex.
* See https://crbug.com/725625 for details.
*
* @param {string} argstr The full ssh command line.
* @return {!Object} The various components.
*/
nassh.CommandInstance.splitCommandLine = function(argstr) {
let args = argstr || '';
let command = '';
// Tokenize the string first.
let i;
let ary = args.match(/("[^"]*"|\S+)/g);
if (ary) {
// If there is a -- separator in here, we split that off and leave the
// command line untouched (other than normalizing of whitespace between
// any arguments, and unused leading/trailing whitespace).
i = ary.indexOf('--');
if (i != -1) {
command = ary.splice(i + 1).join(' ').trim();
// Remove the -- delimiter.
ary.pop();
}
// Now we have to dequote the remaining arguments. The regex above did:
// '-o "foo bar"' -> ['-o', '"foo bar"']
// Based on our (simple) rules, there shouldn't be any other quotes.
ary = ary.map((x) => x.replace(/(^"|"$)/g, ''));
} else {
// Strip out any whitespace. There shouldn't be anything left that the
// regex wouldn't have matched, but let's be paranoid.
args = args.trim();
if (args) {
ary = [args];
} else {
ary = [];
}
}
return {
args: ary,
command: command,
};
};
/**
* Initiate a SFTP connection to a remote host.
*
* @param {string} destination A string of the form username@host[:port].
*/
nassh.CommandInstance.prototype.sftpConnectToDestination = function(
destination) {
const rv = nassh.CommandInstance.parseDestination(destination);
if (rv === null) {
this.io.println(nassh.msg('BAD_DESTINATION', [destination]));
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
return;
}
// We have to set the url here rather than in connectToArgString, because
// some callers may come directly to connectToDestination.
this.terminalLocation.hash = destination;
this.isSftp = true;
this.sftpClient = new nassh.sftp.Client();
this.connectTo(rv);
};
/**
* Initiate an asynchronous connection to a remote host.
*
* @param {!Object} params The various connection settings setup via the
* prefsToConnectParams_ helper.
* @param {function(!Object, !Object)=} finalize Call this instead of the
* normal connectToFinalize_.
*/
nassh.CommandInstance.prototype.connectTo = function(params, finalize) {
if (params.hostname == '>crosh') {
// TODO: This should be done better.
const template = 'crosh.html?profile=%encodeURIComponent(terminalProfile)';
this.terminalLocation.href = lib.f.replaceVars(template, params);
return;
} else if (params.hostname === '>connections') {
this.promptForDestination_();
return;
}
// If no username was specified, prompt the user for one.
if (params.username === undefined) {
const io = this.io.push();
const container = document.createElement('div');
const prompt = document.createElement('p');
prompt.textContent = 'Please enter username:';
container.appendChild(prompt);
const input = document.createElement('input');
container.appendChild(input);
io.showOverlay(container, null);
// Force focus after the browser has a chance to render things.
setTimeout(() => input.focus());
// Keep accepting input until they press Enter.
input.addEventListener('keydown', (e) => {
e.stopPropagation();
if (e.key === 'Enter') {
params.username = input.value;
io.hideOverlay();
io.pop();
this.connectTo(params, finalize);
}
}, true);
// The terminal will eat all key events, so make sure we stop that.
input.addEventListener('keyup', (e) => e.stopPropagation(), true);
input.addEventListener('keypress', (e) => e.stopPropagation(), true);
// If the terminal becomes active for some reason, force back to the input.
io.onVTKeystroke = io.sendString = (string) => {
input.focus();
};
return;
}
// First tokenize the options into an object we can work with more easily.
let options = {};
try {
options = nassh.CommandInstance.tokenizeOptions(params.nasshOptions);
} catch (e) {
this.io.println(nassh.msg('NASSH_OPTIONS_ERROR', [e]));
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
return;
}
let userOptions = {};
try {
userOptions = nassh.CommandInstance.tokenizeOptions(
params.nasshUserOptions);
} catch (e) {
this.io.println(nassh.msg('NASSH_OPTIONS_ERROR', [e]));
this.exit(nassh.CommandInstance.EXIT_INTERNAL_ERROR, true);
return;
}
// Merge nassh options from the ssh:// URI that we believe are safe.
const safeNasshOptions = new Set([
'--config', '--proxy-mode', '--proxy-host', '--proxy-port', '--proxy-user',
'--ssh-agent', '--welcome',
]);
Object.keys(userOptions).forEach((option) => {
if (safeNasshOptions.has(option)) {
options[option] = userOptions[option];
} else {
console.warn(`Option ${option} not currently supported`);
}
});
// Finally post process the combined result.
options = nassh.CommandInstance.postProcessOptions(
options, params.hostname, params.username);
// Merge ssh options from the ssh:// URI that we believe are safe.
params.userSshArgs = [];
const userSshOptionsList = nassh.CommandInstance.splitCommandLine(
params.nasshUserSshOptions).args;
const safeSshOptions = new Set([
'-4', '-6', '-a', '-A', '-C', '-q', '-v', '-V',
]);
userSshOptionsList.forEach((option) => {
if (safeSshOptions.has(option)) {
params.userSshArgs.push(option);
} else {
console.warn(`Option ${option} not currently supported`);
}
});
if (userSshOptionsList.command) {
console.warn(`Remote command '${userSshOptionsList.command}' not ` +
`currently supported`);
}