forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathConsoleProxyNoVncClient.java
More file actions
403 lines (343 loc) · 13.6 KB
/
Copy pathConsoleProxyNoVncClient.java
File metadata and controls
403 lines (343 loc) · 13.6 KB
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.consoleproxy;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketException;
import org.eclipse.jetty.websocket.api.extensions.Frame;
import java.awt.Image;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import com.cloud.consoleproxy.vnc.NoVncClient;
public class ConsoleProxyNoVncClient implements ConsoleProxyClient {
private static final Logger s_logger = Logger.getLogger(ConsoleProxyNoVncClient.class);
private static int nextClientId = 0;
private NoVncClient client;
private Session session;
protected int clientId = getNextClientId();
protected long ajaxSessionId = 0;
protected long createTime = System.currentTimeMillis();
protected long lastFrontEndActivityTime = System.currentTimeMillis();
private boolean connectionAlive;
private ConsoleProxyClientParam clientParam;
private String sessionUuid;
public ConsoleProxyNoVncClient(Session session) {
this.session = session;
}
private int getNextClientId() {
return ++nextClientId;
}
@Override
public void sendClientRawKeyboardEvent(InputEventType event, int code, int modifiers) {
}
@Override
public void sendClientMouseEvent(InputEventType event, int x, int y, int code, int modifiers) {
}
@Override
public boolean isHostConnected() {
return connectionAlive;
}
@Override
public boolean isFrontEndAlive() {
if (!connectionAlive || System.currentTimeMillis()
- getClientLastFrontEndActivityTime() > ConsoleProxy.VIEWER_LINGER_SECONDS * 1000) {
s_logger.info("Front end has been idle for too long");
return false;
}
return true;
}
public void sendClientFrame(Frame f) throws IOException {
byte[] data = new byte[f.getPayloadLength()];
f.getPayload().get(data);
client.write(data);
}
@Override
public void initClient(ConsoleProxyClientParam param) {
setClientParam(param);
client = new NoVncClient();
connectionAlive = true;
this.sessionUuid = param.getSessionUuid();
updateFrontEndActivityTime();
Thread worker = new Thread(new Runnable() {
public void run() {
try {
String tunnelUrl = param.getClientTunnelUrl();
String tunnelSession = param.getClientTunnelSession();
String websocketUrl = param.getWebsocketUrl();
connectClientToVNCServer(tunnelUrl, tunnelSession, websocketUrl);
authenticateToVNCServer();
int readBytes;
byte[] b;
while (connectionAlive) {
if (client.isVncOverWebSocketConnection()) {
if (client.isVncOverWebSocketConnectionOpen()) {
updateFrontEndActivityTime();
}
connectionAlive = session.isOpen();
} else if (client.isVncOverNioSocket()) {
byte[] bytesArr;
int nextBytes = client.getNextBytes();
bytesArr = new byte[nextBytes];
client.readBytes(bytesArr, nextBytes);
s_logger.trace(String.format("Read [%s] bytes from client [%s]", nextBytes, clientId));
if (nextBytes > 0) {
session.getRemote().sendBytes(ByteBuffer.wrap(bytesArr));
updateFrontEndActivityTime();
} else {
connectionAlive = session.isOpen();
}
} else {
b = new byte[100];
readBytes = client.read(b);
s_logger.trace(String.format("Read [%s] bytes from client [%s]", readBytes, clientId));
if (readBytes == -1 || (readBytes > 0 && !sendReadBytesToNoVNC(b, readBytes))) {
connectionAlive = false;
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
s_logger.error("Error on sleep for vnc over websocket", e);
}
}
s_logger.info(String.format("Connection with client [%s] is dead.", clientId));
} catch (IOException e) {
s_logger.error("Error on VNC client", e);
}
}
});
worker.start();
}
private boolean sendReadBytesToNoVNC(byte[] b, int readBytes) {
try {
session.getRemote().sendBytes(ByteBuffer.wrap(b, 0, readBytes));
updateFrontEndActivityTime();
} catch (WebSocketException | IOException e) {
s_logger.debug("Connection exception", e);
return false;
}
return true;
}
/**
* Authenticate to VNC server when not using websockets
*
* Since we are supporting the 3.8 version of the RFB protocol, there are changes on the stages:
* 1. Handshake:
* 1.a. Protocol version
* 1.b. Security types
* 2. Security types
* 3. Initialisation
*
* Reference: https://github.com/rfbproto/rfbproto/blob/master/rfbproto.rst#7protocol-messages
*/
private void authenticateToVNCServer() throws IOException {
if (client.isVncOverWebSocketConnection()) {
return;
}
if (!client.isVncOverNioSocket()) {
String ver = client.handshake();
session.getRemote().sendBytes(ByteBuffer.wrap(ver.getBytes(), 0, ver.length()));
byte[] b = client.authenticateTunnel(getClientHostPassword());
session.getRemote().sendBytes(ByteBuffer.wrap(b, 0, 4));
} else {
authenticateVNCServerThroughNioSocket();
}
}
/**
* Handshaking messages consist on 3 phases:
* - ProtocolVersion
* - Security
* - SecurityResult
*
* Reference: https://github.com/rfbproto/rfbproto/blob/master/rfbproto.rst#71handshaking-messages
*/
protected void handshakePhase() {
handshakeProtocolVersion();
int securityType = handshakeSecurity();
handshakeSecurityResult(securityType);
client.waitForNoVNCReply();
}
protected void handshakeSecurityResult(int secType) {
client.processHandshakeSecurityType(secType, getClientHostPassword(),
getClientHostAddress(), getClientHostPort());
client.processSecurityResultMsg();
byte[] securityResultToClient = new byte[] { 0, 0, 0, 0 };
sendMessageToVNCClient(securityResultToClient, 4);
client.setWaitForNoVnc(true);
}
protected int handshakeSecurity() {
int secType = client.handshakeSecurityType();
byte[] numberTypesToClient = new byte[] { 1, (byte) secType };
sendMessageToVNCClient(numberTypesToClient, 2);
return secType;
}
protected void handshakeProtocolVersion() {
ByteBuffer verStr = client.handshakeProtocolVersion();
sendMessageToVNCClient(verStr.array(), 12);
}
protected void authenticateVNCServerThroughNioSocket() {
handshakePhase();
initialisationPhase();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Authenticated successfully");
}
}
/**
* Initialisation messages consist on:
* - ClientInit
* - ServerInit
*
* Reference: https://github.com/rfbproto/rfbproto/blob/master/rfbproto.rst#73initialisation-messages
*/
private void initialisationPhase() {
byte[] serverInitByteArray = client.readServerInit();
String displayNameForVM = String.format("%s %s", clientParam.getClientDisplayName(),
client.isTLSConnectionEstablished() ? "(TLS backend)" : "");
byte[] bytesServerInit = rewriteServerNameInServerInit(serverInitByteArray, displayNameForVM);
sendMessageToVNCClient(bytesServerInit, bytesServerInit.length);
client.setWaitForNoVnc(true);
client.waitForNoVNCReply();
}
/**
* Send a message to the noVNC client
*/
private void sendMessageToVNCClient(byte[] arr, int length) {
try {
session.getRemote().sendBytes(ByteBuffer.wrap(arr, 0, length));
} catch (IOException e) {
s_logger.error("Error sending a message to the noVNC client", e);
}
}
protected static byte[] rewriteServerNameInServerInit(byte[] serverInitBytes, String serverName) {
byte[] serverNameBytes = serverName.getBytes(StandardCharsets.UTF_8);
ByteBuffer serverInitBuffer = ByteBuffer.allocate(24 + serverNameBytes.length);
serverInitBuffer.put(serverInitBytes, 0, 20);
serverInitBuffer.putInt(serverNameBytes.length);
serverInitBuffer.put(serverNameBytes);
return serverInitBuffer.array();
}
/**
* Connect to a VNC server in one of three possible ways:
* - When tunnelUrl and tunnelSession are not empty -> via tunnel
* - When websocketUrl is not empty -> connect to websocket
* - Otherwise -> connect to TCP port on host directly
*/
private void connectClientToVNCServer(String tunnelUrl, String tunnelSession, String websocketUrl) {
try {
if (StringUtils.isNotBlank(websocketUrl)) {
s_logger.info(String.format("Connect to VNC over websocket URL: %s", websocketUrl));
client.connectToWebSocket(websocketUrl, session);
} else if (tunnelUrl != null && !tunnelUrl.isEmpty() && tunnelSession != null
&& !tunnelSession.isEmpty()) {
URI uri = new URI(tunnelUrl);
s_logger.info(String.format("Connect to VNC server via tunnel. url: %s, session: %s",
tunnelUrl, tunnelSession));
ConsoleProxy.ensureRoute(uri.getHost());
client.connectTo(uri.getHost(), uri.getPort(), uri.getPath() + "?" + uri.getQuery(),
tunnelSession, "https".equalsIgnoreCase(uri.getScheme()));
} else {
s_logger.info(String.format("Connect to VNC server directly. host: %s, port: %s",
getClientHostAddress(), getClientHostPort()));
ConsoleProxy.ensureRoute(getClientHostAddress());
client.connectTo(getClientHostAddress(), getClientHostPort());
}
} catch (Throwable e) {
s_logger.error("Unexpected exception", e);
}
}
private void setClientParam(ConsoleProxyClientParam param) {
this.clientParam = param;
}
@Override
public void closeClient() {
this.connectionAlive = false;
ConsoleProxy.removeViewer(this);
}
@Override
public String getSessionUuid() {
return sessionUuid;
}
@Override
public int getClientId() {
return this.clientId;
}
@Override
public long getAjaxSessionId() {
return this.ajaxSessionId;
}
@Override
public AjaxFIFOImageCache getAjaxImageCache() {
// Unimplemented
return null;
}
@Override
public Image getClientScaledImage(int width, int height) {
// Unimplemented
return null;
}
@Override
public String onAjaxClientStart(String title, List<String> languages, String guest) {
// Unimplemented
return null;
}
@Override
public String onAjaxClientUpdate() {
// Unimplemented
return null;
}
@Override
public String onAjaxClientKickoff() {
// Unimplemented
return null;
}
@Override
public long getClientCreateTime() {
return createTime;
}
public void updateFrontEndActivityTime() {
lastFrontEndActivityTime = System.currentTimeMillis();
}
@Override
public long getClientLastFrontEndActivityTime() {
return lastFrontEndActivityTime;
}
@Override
public String getClientHostAddress() {
return clientParam.getClientHostAddress();
}
@Override
public int getClientHostPort() {
return clientParam.getClientHostPort();
}
@Override
public String getClientHostPassword() {
return clientParam.getClientHostPassword();
}
@Override
public String getClientTag() {
if (clientParam.getClientTag() != null)
return clientParam.getClientTag();
return "";
}
public Session getSession() {
return session;
}
}