-
Notifications
You must be signed in to change notification settings - Fork 8
/
terminal.js
108 lines (91 loc) · 2.32 KB
/
terminal.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
#!/usr/bin/env node
var WebSocket = require('ws')
var pty = require('pty.js')
var cluster = require('cluster')
function generate_token(size) {
var text = ''
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for( var i=0; i < size; i++ )
text += alphabet.charAt(Math.floor(Math.random() * alphabet.length))
return text
}
var host, label
if (process.argv[2])
host = process.argv[2]
else
host = 'localhost:8080'
if (process.argv[3])
label = process.argv[3]
else
label = 'REMOTO terminal'
var token = generate_token(32)
var ws
function check() {
if (!ws || ws.readState == 3) connect()
}
function connect() {
ws = new WebSocket('ws://' + host + '/?type=terminal&token=' + token + '&label=' + label)
var term
ws.on('open', function () {
console.log("Connection opened at http://%s/#%s", host, token)
term = pty.fork('bash', [], {
name: require('fs').existsSync('/usr/share/terminfo/x/xterm-256color')
? 'xterm-256color'
: 'xterm',
cols: 160,
rows: 36,
cwd: process.env.HOME
})
term.on('data', function (data) {
var message = JSON.stringify({ type: 'OUT', message: data })
try {
ws.send(message)
} catch (ex) {
console.error(ex)
}
})
var ping = setInterval(function () {
try {
ws.send(JSON.stringify({ type: 'PING', message: 'PING!' }))
} catch (ex) {
clearInterval(ping)
console.error(ex)
}
}, 1000)
})
ws.on('message', function (message) {
try {
var obj = JSON.parse(message)
if (obj.type == 'IN') {
term.write(obj.message)
}
} catch (ex) {
console.error(message, ex)
}
})
ws.on('error', function (e) {
console.log('Connection error', e)
ws = null
// setTimeout(check, 1000)
})
ws.on('close', function (e) {
// console.log('Connection closed', e)
ws = null
setTimeout(check, 1000)
})
}
if (cluster.isMaster) {
cluster.fork()
cluster.on('exit', function (worker) {
console.log('Worker %s died, restarting...', worker.process.pid)
cluster.fork()
})
} else {
ws = null
connect()
}
process.on('uncaughtException', function (err) {
console.error((new Date).toUTCString() + ' uncaughtException:', err.message)
console.error(err.stack)
process.exit(1)
})