This repository has been archived by the owner on Nov 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nodeConnection.ts
238 lines (214 loc) · 6.41 KB
/
nodeConnection.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
import * as fs from 'fs'
import * as net from 'net'
import { homedir, hostname } from 'os'
import * as path from 'path'
import * as util from 'util'
import { authenticate } from './auth'
import { connectGeneric, XConnection, XConnectionOptions, XConnectionSocket } from './connection'
const fsReadFile = util.promisify(fs.readFile)
interface ConnectionTypeToName {
256: 'Local'
65535: 'Wild'
254: 'Netname'
253: 'Krb5Principal'
252: 'LocalHost'
0: 'Internet'
1: 'DECnet'
2: 'Chaos'
5: 'ServerInterpreted'
6: 'Internet6'
}
const connectionTypeToName: ConnectionTypeToName = {
256: 'Local',
65535: 'Wild',
254: 'Netname',
253: 'Krb5Principal',
252: 'LocalHost',
0: 'Internet',
1: 'DECnet',
2: 'Chaos',
5: 'ServerInterpreted',
6: 'Internet6'
}
interface Cookie {
type: keyof ConnectionTypeToName
address: string
display: string
authName: string
authData: string
}
async function readXauthority(xAuthority?: string): Promise<Uint8Array | null> {
const nixFilename = xAuthority || process.env.XAUTHORITY || path.join(homedir(), '.Xauthority')
try {
return await fsReadFile(nixFilename)
} catch (err) {
if (err.code === 'ENOENT') {
// TODO we could solve this with recursion instead of c/p the readFile logic here from before
// Xming/windows uses %HOME%/Xauthority ( .Xauthority with no dot ) - try with this name
const winFilename = process.env.XAUTHORITY ?? path.join(homedir(), 'Xauthority')
try {
return await fsReadFile(winFilename)
} catch (err) {
if (err.code === 'ENOENT') {
return null
} else {
throw err
}
}
} else {
throw err
}
}
}
function parseXauth(buf: Uint8Array): Cookie[] {
let offset = 0
const auth: Cookie[] = []
const cookieProperties: (keyof Omit<Cookie, 'type'>)[] = [
'address',
'display',
'authName',
'authData'
]
while (offset < buf.length) {
const type = buf[offset + 1] | (buf[offset] << 8)
if (!connectionTypeToName.hasOwnProperty(type)) {
throw new Error('Unknown address type')
}
const cookie: Partial<Cookie> = {
type: type as keyof ConnectionTypeToName
}
offset += 2
cookieProperties.forEach((property) => {
const length = buf[offset + 1] | (buf[offset] << 8)
offset += 2
if (cookie.type === 0 && property === 'address') {
// Internet
// 4 bytes of ip addess, convert to w.x.y.z string
cookie.address = [buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3]]
.map((octet) => octet.toString(10))
.join('.')
} else {
let res = ''
const end = offset + length
let offzet = offset
while (offzet < end) {
res += String.fromCharCode(buf[offzet++])
}
cookie[property] = res
}
offset += length
})
auth.push(cookie as Cookie)
}
return auth
}
async function connectSocket(
host: string,
displayNum: string,
socketPath?: string
): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = socketPath
? net.createConnection(socketPath)
: net.createConnection(6000 + parseInt(displayNum, 10), host)
socket.on('ready', () => {
// client.init(stream)
resolve(socket)
})
socket.on('error', (err: NodeJS.ErrnoException) => {
if (socket.connecting && socketPath && err.code === 'ENOENT') {
return connectSocket('localhost', displayNum)
} else if (socket.connecting) {
reject(err)
} else {
socket.destroy(err)
}
})
})
}
export async function getAuthenticationCookie(
displayNum: string,
authHost: string,
socketFamily: 'IPv4' | 'IPv6' | undefined,
xAuthority?: string
): Promise<{ authName: string; authData: string }> {
let family: number
if (socketFamily === 'IPv4') {
family = 0 // Internet
} else if (socketFamily === 'IPv6') {
family = 6 // Internet6
} else {
family = 256 // Local
}
const data = await readXauthority(xAuthority)
if (!data) {
return {
authName: '',
authData: ''
}
}
const auth = parseXauth(data)
for (let cookieNum in auth) {
const cookie = auth[cookieNum]
if (
(connectionTypeToName[cookie.type] === 'Wild' ||
(cookie.type === family && cookie.address === authHost)) &&
(cookie.display.length === 0 || cookie.display === displayNum)
) {
return cookie
}
}
// If no cookie is found, proceed without authentication
return {
authName: '',
authData: ''
}
}
export async function connect(options?: XConnectionOptions): Promise<XConnection> {
const connectionSetup = async () => {
const display = options?.display ?? process.env.DISPLAY ?? ':0'
const xAuthority = options?.xAuthority
const displayMatch = display.match(/^(?:[^:]*?\/)?(.*):(\d+)(?:.(\d+))?$/)
if (!displayMatch) {
throw new Error('Cannot parse display')
}
const host = displayMatch[1]
const displayNum = displayMatch[2] ?? '0'
const screenNum = displayMatch[3] ?? '0'
let socketPath: string | undefined
// try local socket on non-windows platforms
if (['cygwin', 'win32', 'win64'].indexOf(process.platform) < 0) {
// FIXME check if mac is ok?
// @ts-ignore
if (process.platform === 'darwin' || process.platform === 'mac') {
// socket path on OSX is /tmp/launch-(some id)/org.x:0
if (display[0] === '/') {
socketPath = display
}
} else if (!host) {
socketPath = '/tmp/.X11-unix/X' + displayNum
}
}
const socket = await connectSocket(host, displayNum, socketPath)
const xConnectionSocket: XConnectionSocket = {
write(data: Uint8Array) {
socket.write(data)
},
close() {
socket.end()
}
}
socket.on('data', (data) => xConnectionSocket.onData?.(data))
let authHost = socket.remoteAddress
let socketFamily = socket.remoteFamily as 'IPv4' | 'IPv6' | undefined
if (!authHost || authHost === '127.0.0.1' || authHost === '::1') {
authHost = hostname()
socketFamily = undefined
}
// tslint:disable-next-line:no-floating-promises
const cookie = await getAuthenticationCookie(displayNum, authHost, socketFamily, xAuthority)
const setup = await authenticate(xConnectionSocket, displayNum, authHost, socketFamily, cookie)
return { setup, xConnectionSocket }
}
return connectGeneric(connectionSetup)
}