-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTunnel.js
1377 lines (1095 loc) · 40.9 KB
/
Tunnel.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
/*
* 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.
*/
var Guacamole = Guacamole || {};
/**
* Core object providing abstract communication for Guacamole. This object
* is a null implementation whose functions do nothing. Guacamole applications
* should use {@link Guacamole.HTTPTunnel} instead, or implement their own tunnel based
* on this one.
*
* @constructor
* @see Guacamole.HTTPTunnel
*/
Guacamole.Tunnel = function() {
/**
* Connect to the tunnel with the given optional data. This data is
* typically used for authentication. The format of data accepted is
* up to the tunnel implementation.
*
* @param {string} [data]
* The data to send to the tunnel when connecting.
*/
this.connect = function(data) {};
/**
* Disconnect from the tunnel.
*/
this.disconnect = function() {};
/**
* Send the given message through the tunnel to the service on the other
* side. All messages are guaranteed to be received in the order sent.
*
* @param {...*} elements
* The elements of the message to send to the service on the other side
* of the tunnel.
*/
this.sendMessage = function(elements) {};
/**
* Changes the stored numeric state of this tunnel, firing the onstatechange
* event if the new state is different and a handler has been defined.
*
* @private
* @param {!number} state
* The new state of this tunnel.
*/
this.setState = function(state) {
// Notify only if state changes
if (state !== this.state) {
this.state = state;
if (this.onstatechange)
this.onstatechange(state);
}
};
/**
* Changes the stored UUID that uniquely identifies this tunnel, firing the
* onuuid event if a handler has been defined.
*
* @private
* @param {string} uuid
* The new state of this tunnel.
*/
this.setUUID = function setUUID(uuid) {
this.uuid = uuid;
if (this.onuuid)
this.onuuid(uuid);
};
/**
* Returns whether this tunnel is currently connected.
*
* @returns {!boolean}
* true if this tunnel is currently connected, false otherwise.
*/
this.isConnected = function isConnected() {
return this.state === Guacamole.Tunnel.State.OPEN
|| this.state === Guacamole.Tunnel.State.UNSTABLE;
};
/**
* The current state of this tunnel.
*
* @type {!number}
*/
this.state = Guacamole.Tunnel.State.CLOSED;
/**
* The maximum amount of time to wait for data to be received, in
* milliseconds. If data is not received within this amount of time,
* the tunnel is closed with an error. The default value is 15000.
*
* @type {!number}
*/
this.receiveTimeout = 15000;
/**
* The amount of time to wait for data to be received before considering
* the connection to be unstable, in milliseconds. If data is not received
* within this amount of time, the tunnel status is updated to warn that
* the connection appears unresponsive and may close. The default value is
* 1500.
*
* @type {!number}
*/
this.unstableThreshold = 1500;
/**
* The UUID uniquely identifying this tunnel. If not yet known, this will
* be null.
*
* @type {string}
*/
this.uuid = null;
/**
* Fired when the UUID that uniquely identifies this tunnel is known.
*
* @event
* @param {!string}
* The UUID uniquely identifying this tunnel.
*/
this.onuuid = null;
/**
* Fired whenever an error is encountered by the tunnel.
*
* @event
* @param {!Guacamole.Status} status
* A status object which describes the error.
*/
this.onerror = null;
/**
* Fired whenever the state of the tunnel changes.
*
* @event
* @param {!number} state
* The new state of the client.
*/
this.onstatechange = null;
/**
* Fired once for every complete Guacamole instruction received, in order.
*
* @event
* @param {!string} opcode
* The Guacamole instruction opcode.
*
* @param {!string[]} parameters
* The parameters provided for the instruction, if any.
*/
this.oninstruction = null;
};
/**
* The Guacamole protocol instruction opcode reserved for arbitrary internal
* use by tunnel implementations. The value of this opcode is guaranteed to be
* the empty string (""). Tunnel implementations may use this opcode for any
* purpose. It is currently used by the HTTP tunnel to mark the end of the HTTP
* response, and by the WebSocket tunnel to transmit the tunnel UUID and send
* connection stability test pings/responses.
*
* @constant
* @type {!string}
*/
Guacamole.Tunnel.INTERNAL_DATA_OPCODE = '';
/**
* All possible tunnel states.
*
* @type {!Object.<string, number>}
*/
Guacamole.Tunnel.State = {
/**
* A connection is in pending. It is not yet known whether connection was
* successful.
*
* @type {!number}
*/
"CONNECTING": 0,
/**
* Connection was successful, and data is being received.
*
* @type {!number}
*/
"OPEN": 1,
/**
* The connection is closed. Connection may not have been successful, the
* tunnel may have been explicitly closed by either side, or an error may
* have occurred.
*
* @type {!number}
*/
"CLOSED": 2,
/**
* The connection is open, but communication through the tunnel appears to
* be disrupted, and the connection may close as a result.
*
* @type {!number}
*/
"UNSTABLE" : 3
};
/**
* Guacamole Tunnel implemented over HTTP via XMLHttpRequest.
*
* @constructor
* @augments Guacamole.Tunnel
*
* @param {!string} tunnelURL
* The URL of the HTTP tunneling service.
*
* @param {boolean} [crossDomain=false]
* Whether tunnel requests will be cross-domain, and thus must use CORS
* mechanisms and headers. By default, it is assumed that tunnel requests
* will be made to the same domain.
*
* @param {object} [extraTunnelHeaders={}]
* Key value pairs containing the header names and values of any additional
* headers to be sent in tunnel requests. By default, no extra headers will
* be added.
*/
Guacamole.HTTPTunnel = function(tunnelURL, crossDomain, extraTunnelHeaders) {
/**
* Reference to this HTTP tunnel.
*
* @private
* @type {!Guacamole.HTTPTunnel}
*/
var tunnel = this;
var TUNNEL_CONNECT = tunnelURL + "?connect";
var TUNNEL_READ = tunnelURL + "?read:";
var TUNNEL_WRITE = tunnelURL + "?write:";
var POLLING_ENABLED = 1;
var POLLING_DISABLED = 0;
// Default to polling - will be turned off automatically if not needed
var pollingMode = POLLING_ENABLED;
var sendingMessages = false;
var outputMessageBuffer = "";
// If requests are expected to be cross-domain, the cookie that the HTTP
// tunnel depends on will only be sent if withCredentials is true
var withCredentials = !!crossDomain;
/**
* The current receive timeout ID, if any.
*
* @private
* @type {number}
*/
var receive_timeout = null;
/**
* The current connection stability timeout ID, if any.
*
* @private
* @type {number}
*/
var unstableTimeout = null;
/**
* The current connection stability test ping interval ID, if any. This
* will only be set upon successful connection.
*
* @private
* @type {number}
*/
var pingInterval = null;
/**
* The number of milliseconds to wait between connection stability test
* pings.
*
* @private
* @constant
* @type {!number}
*/
var PING_FREQUENCY = 500;
/**
* Additional headers to be sent in tunnel requests. This dictionary can be
* populated with key/value header pairs to pass information such as authentication
* tokens, etc.
*
* @private
* @type {!object}
*/
var extraHeaders = extraTunnelHeaders || {};
/**
* The name of the HTTP header containing the session token specific to the
* HTTP tunnel implementation.
*
* @private
* @constant
* @type {!string}
*/
var TUNNEL_TOKEN_HEADER = 'Guacamole-Tunnel-Token';
/**
* The session token currently assigned to this HTTP tunnel. All distinct
* HTTP tunnel connections will have their own dedicated session token.
*
* @private
* @type {string}
*/
var tunnelSessionToken = null;
/**
* Adds the configured additional headers to the given request.
*
* @private
* @param {!XMLHttpRequest} request
* The request where the configured extra headers will be added.
*
* @param {!object} headers
* The headers to be added to the request.
*/
function addExtraHeaders(request, headers) {
for (var name in headers) {
request.setRequestHeader(name, headers[name]);
}
}
/**
* Resets the state of timers tracking network activity and stability. If
* those timers are not yet started, invoking this function starts them.
* This function should be invoked when the tunnel is established and every
* time there is network activity on the tunnel, such that the timers can
* safely assume the network and/or server are not responding if this
* function has not been invoked for a significant period of time.
*
* @private
*/
var resetTimers = function resetTimers() {
// Get rid of old timeouts (if any)
window.clearTimeout(receive_timeout);
window.clearTimeout(unstableTimeout);
// Clear unstable status
if (tunnel.state === Guacamole.Tunnel.State.UNSTABLE)
tunnel.setState(Guacamole.Tunnel.State.OPEN);
// Set new timeout for tracking overall connection timeout
receive_timeout = window.setTimeout(function () {
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_TIMEOUT, "Server timeout."));
}, tunnel.receiveTimeout);
// Set new timeout for tracking suspected connection instability
unstableTimeout = window.setTimeout(function() {
tunnel.setState(Guacamole.Tunnel.State.UNSTABLE);
}, tunnel.unstableThreshold);
};
/**
* Closes this tunnel, signaling the given status and corresponding
* message, which will be sent to the onerror handler if the status is
* an error status.
*
* @private
* @param {!Guacamole.Status} status
* The status causing the connection to close;
*/
function close_tunnel(status) {
// Get rid of old timeouts (if any)
window.clearTimeout(receive_timeout);
window.clearTimeout(unstableTimeout);
// Cease connection test pings
window.clearInterval(pingInterval);
// Ignore if already closed
if (tunnel.state === Guacamole.Tunnel.State.CLOSED)
return;
// If connection closed abnormally, signal error.
if (status.code !== Guacamole.Status.Code.SUCCESS && tunnel.onerror) {
// Ignore RESOURCE_NOT_FOUND if we've already connected, as that
// only signals end-of-stream for the HTTP tunnel.
if (tunnel.state === Guacamole.Tunnel.State.CONNECTING
|| status.code !== Guacamole.Status.Code.RESOURCE_NOT_FOUND)
tunnel.onerror(status);
}
// Reset output message buffer
sendingMessages = false;
// Mark as closed
tunnel.setState(Guacamole.Tunnel.State.CLOSED);
}
this.sendMessage = function() {
// Do not attempt to send messages if not connected
if (!tunnel.isConnected())
return;
// Do not attempt to send empty messages
if (!arguments.length)
return;
// Add message to buffer
outputMessageBuffer += Guacamole.Parser.toInstruction(arguments);
// Send if not currently sending
if (!sendingMessages)
sendPendingMessages();
};
function sendPendingMessages() {
// Do not attempt to send messages if not connected
if (!tunnel.isConnected())
return;
if (outputMessageBuffer.length > 0) {
sendingMessages = true;
var message_xmlhttprequest = new XMLHttpRequest();
message_xmlhttprequest.open("POST", TUNNEL_WRITE + tunnel.uuid);
message_xmlhttprequest.withCredentials = withCredentials;
addExtraHeaders(message_xmlhttprequest, extraHeaders);
message_xmlhttprequest.setRequestHeader("Content-type", "application/octet-stream");
message_xmlhttprequest.setRequestHeader(TUNNEL_TOKEN_HEADER, tunnelSessionToken);
// Once response received, send next queued event.
message_xmlhttprequest.onreadystatechange = function() {
if (message_xmlhttprequest.readyState === 4) {
resetTimers();
// If an error occurs during send, handle it
if (message_xmlhttprequest.status !== 200)
handleHTTPTunnelError(message_xmlhttprequest);
// Otherwise, continue the send loop
else
sendPendingMessages();
}
};
message_xmlhttprequest.send(outputMessageBuffer);
outputMessageBuffer = ""; // Clear buffer
}
else
sendingMessages = false;
}
function handleHTTPTunnelError(xmlhttprequest) {
// Pull status code directly from headers provided by Guacamole
var code = parseInt(xmlhttprequest.getResponseHeader("Guacamole-Status-Code"));
if (code) {
var message = xmlhttprequest.getResponseHeader("Guacamole-Error-Message");
close_tunnel(new Guacamole.Status(code, message));
}
// Failing that, derive a Guacamole status code from the HTTP status
// code provided by the browser
else if (xmlhttprequest.status)
close_tunnel(new Guacamole.Status(
Guacamole.Status.Code.fromHTTPCode(xmlhttprequest.status),
xmlhttprequest.statusText));
// Otherwise, assume server is unreachable
else
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_NOT_FOUND));
}
function handleResponse(xmlhttprequest) {
var interval = null;
var nextRequest = null;
var dataUpdateEvents = 0;
var parser = new Guacamole.Parser();
parser.oninstruction = function instructionReceived(opcode, args) {
// Switch to next request if end-of-stream is signalled
if (opcode === Guacamole.Tunnel.INTERNAL_DATA_OPCODE && args.length === 0) {
// Reset parser state by simply switching to an entirely new
// parser
parser = new Guacamole.Parser();
parser.oninstruction = instructionReceived;
// Clean up interval if polling
if (interval)
clearInterval(interval);
// Clean up object
xmlhttprequest.onreadystatechange = null;
xmlhttprequest.abort();
// Start handling next request
if (nextRequest)
handleResponse(nextRequest);
}
// Call instruction handler.
else if (opcode !== Guacamole.Tunnel.INTERNAL_DATA_OPCODE && tunnel.oninstruction)
tunnel.oninstruction(opcode, args);
};
function parseResponse() {
// Do not handle responses if not connected
if (!tunnel.isConnected()) {
// Clean up interval if polling
if (interval !== null)
clearInterval(interval);
return;
}
// Do not parse response yet if not ready
if (xmlhttprequest.readyState < 2) return;
// Attempt to read status
var status;
try { status = xmlhttprequest.status; }
// If status could not be read, assume successful.
catch (e) { status = 200; }
// Start next request as soon as possible IF request was successful
if (!nextRequest && status === 200)
nextRequest = makeRequest();
// Parse stream when data is received and when complete.
if (xmlhttprequest.readyState === 3 ||
xmlhttprequest.readyState === 4) {
resetTimers();
// Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
if (pollingMode === POLLING_ENABLED) {
if (xmlhttprequest.readyState === 3 && !interval)
interval = setInterval(parseResponse, 30);
else if (xmlhttprequest.readyState === 4 && interval)
clearInterval(interval);
}
// If canceled, stop transfer
if (xmlhttprequest.status === 0) {
tunnel.disconnect();
return;
}
// Halt on error during request
else if (xmlhttprequest.status !== 200) {
handleHTTPTunnelError(xmlhttprequest);
return;
}
// Attempt to read in-progress data
var current;
try { current = xmlhttprequest.responseText; }
// Do not attempt to parse if data could not be read
catch (e) { return; }
try {
parser.receive(current, true);
}
catch (e) {
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.SERVER_ERROR, e.message));
return;
}
}
}
// If response polling enabled, attempt to detect if still
// necessary (via wrapping parseResponse())
if (pollingMode === POLLING_ENABLED) {
xmlhttprequest.onreadystatechange = function() {
// If we receive two or more readyState==3 events,
// there is no need to poll.
if (xmlhttprequest.readyState === 3) {
dataUpdateEvents++;
if (dataUpdateEvents >= 2) {
pollingMode = POLLING_DISABLED;
xmlhttprequest.onreadystatechange = parseResponse;
}
}
parseResponse();
};
}
// Otherwise, just parse
else
xmlhttprequest.onreadystatechange = parseResponse;
parseResponse();
}
/**
* Arbitrary integer, unique for each tunnel read request.
* @private
*/
var request_id = 0;
function makeRequest() {
// Make request, increment request ID
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("GET", TUNNEL_READ + tunnel.uuid + ":" + (request_id++));
xmlhttprequest.setRequestHeader(TUNNEL_TOKEN_HEADER, tunnelSessionToken);
xmlhttprequest.withCredentials = withCredentials;
addExtraHeaders(xmlhttprequest, extraHeaders);
xmlhttprequest.send(null);
return xmlhttprequest;
}
this.connect = function(data) {
// Start waiting for connect
resetTimers();
// Mark the tunnel as connecting
tunnel.setState(Guacamole.Tunnel.State.CONNECTING);
// Start tunnel and connect
var connect_xmlhttprequest = new XMLHttpRequest();
connect_xmlhttprequest.onreadystatechange = function() {
if (connect_xmlhttprequest.readyState !== 4)
return;
// If failure, throw error
if (connect_xmlhttprequest.status !== 200) {
handleHTTPTunnelError(connect_xmlhttprequest);
return;
}
resetTimers();
// Get UUID and HTTP-specific tunnel session token from response
tunnel.setUUID(connect_xmlhttprequest.responseText);
tunnelSessionToken = connect_xmlhttprequest.getResponseHeader(TUNNEL_TOKEN_HEADER);
// Fail connect attempt if token is not successfully assigned
if (!tunnelSessionToken) {
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_NOT_FOUND));
return;
}
// Mark as open
tunnel.setState(Guacamole.Tunnel.State.OPEN);
// Ping tunnel endpoint regularly to test connection stability
pingInterval = setInterval(function sendPing() {
tunnel.sendMessage("nop");
}, PING_FREQUENCY);
// Start reading data
handleResponse(makeRequest());
};
connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, true);
connect_xmlhttprequest.withCredentials = withCredentials;
addExtraHeaders(connect_xmlhttprequest, extraHeaders);
connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
connect_xmlhttprequest.send(data);
};
this.disconnect = function() {
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.SUCCESS, "Manually closed."));
};
};
Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
/**
* Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
*
* @constructor
* @augments Guacamole.Tunnel
* @param {!string} tunnelURL
* The URL of the WebSocket tunneling service.
*/
Guacamole.WebSocketTunnel = function(tunnelURL) {
/**
* Reference to this WebSocket tunnel.
*
* @private
* @type {Guacamole.WebSocketTunnel}
*/
var tunnel = this;
/**
* The parser that this tunnel will use to parse received Guacamole
* instructions. The parser is created when the tunnel is (re-)connected.
* Initially, this will be null.
*
* @private
* @type {Guacamole.Parser}
*/
var parser = null;
/**
* The WebSocket used by this tunnel.
*
* @private
* @type {WebSocket}
*/
var socket = null;
/**
* The current receive timeout ID, if any.
*
* @private
* @type {number}
*/
var receive_timeout = null;
/**
* The current connection stability timeout ID, if any.
*
* @private
* @type {number}
*/
var unstableTimeout = null;
/**
* The current connection stability test ping timeout ID, if any. This
* will only be set upon successful connection.
*
* @private
* @type {number}
*/
var pingTimeout = null;
/**
* The WebSocket protocol corresponding to the protocol used for the current
* location.
*
* @private
* @type {!Object.<string, string>}
*/
var ws_protocol = {
"http:": "ws:",
"https:": "wss:"
};
/**
* The number of milliseconds to wait between connection stability test
* pings.
*
* @private
* @constant
* @type {!number}
*/
var PING_FREQUENCY = 500;
/**
* The timestamp of the point in time that the last connection stability
* test ping was sent, in milliseconds elapsed since midnight of January 1,
* 1970 UTC.
*
* @private
* @type {!number}
*/
var lastSentPing = 0;
// Transform current URL to WebSocket URL
// If not already a websocket URL
if ( tunnelURL.substring(0, 3) !== "ws:"
&& tunnelURL.substring(0, 4) !== "wss:") {
var protocol = ws_protocol[window.location.protocol];
// If absolute URL, convert to absolute WS URL
if (tunnelURL.substring(0, 1) === "/")
tunnelURL =
protocol
+ "//" + window.location.host
+ tunnelURL;
// Otherwise, construct absolute from relative URL
else {
// Get path from pathname
var slash = window.location.pathname.lastIndexOf("/");
var path = window.location.pathname.substring(0, slash + 1);
// Construct absolute URL
tunnelURL =
protocol
+ "//" + window.location.host
+ path
+ tunnelURL;
}
}
/**
* Sends an internal "ping" instruction to the Guacamole WebSocket
* endpoint, verifying network connection stability. If the network is
* stable, the Guacamole server will receive this instruction and respond
* with an identical ping.
*
* @private
*/
var sendPing = function sendPing() {
var currentTime = new Date().getTime();
tunnel.sendMessage(Guacamole.Tunnel.INTERNAL_DATA_OPCODE, 'ping', currentTime);
lastSentPing = currentTime;
};
/**
* Resets the state of timers tracking network activity and stability. If
* those timers are not yet started, invoking this function starts them.
* This function should be invoked when the tunnel is established and every
* time there is network activity on the tunnel, such that the timers can
* safely assume the network and/or server are not responding if this
* function has not been invoked for a significant period of time.
*
* @private
*/
var resetTimers = function resetTimers() {
// Get rid of old timeouts (if any)
window.clearTimeout(receive_timeout);
window.clearTimeout(unstableTimeout);
window.clearTimeout(pingTimeout);
// Clear unstable status
if (tunnel.state === Guacamole.Tunnel.State.UNSTABLE)
tunnel.setState(Guacamole.Tunnel.State.OPEN);
// Set new timeout for tracking overall connection timeout
receive_timeout = window.setTimeout(function () {
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_TIMEOUT, "Server timeout."));
}, tunnel.receiveTimeout);
// Set new timeout for tracking suspected connection instability
unstableTimeout = window.setTimeout(function() {
tunnel.setState(Guacamole.Tunnel.State.UNSTABLE);
}, tunnel.unstableThreshold);
var currentTime = new Date().getTime();
var pingDelay = Math.max(lastSentPing + PING_FREQUENCY - currentTime, 0);
// Ping tunnel endpoint regularly to test connection stability, sending
// the ping immediately if enough time has already elapsed
if (pingDelay > 0)
pingTimeout = window.setTimeout(sendPing, pingDelay);
else
sendPing();
};
/**
* Closes this tunnel, signaling the given status and corresponding
* message, which will be sent to the onerror handler if the status is
* an error status.
*
* @private
* @param {!Guacamole.Status} status
* The status causing the connection to close;
*/
function close_tunnel(status) {
// Get rid of old timeouts (if any)
window.clearTimeout(receive_timeout);
window.clearTimeout(unstableTimeout);
window.clearTimeout(pingTimeout);
// Ignore if already closed
if (tunnel.state === Guacamole.Tunnel.State.CLOSED)
return;
// If connection closed abnormally, signal error.
if (status.code !== Guacamole.Status.Code.SUCCESS && tunnel.onerror)
tunnel.onerror(status);
// Mark as closed
tunnel.setState(Guacamole.Tunnel.State.CLOSED);
socket.close();
}
this.sendMessage = function(elements) {
// Do not attempt to send messages if not connected
if (!tunnel.isConnected())
return;
// Do not attempt to send empty messages
if (!arguments.length)
return;
socket.send(Guacamole.Parser.toInstruction(arguments));
};
this.connect = function(data) {
resetTimers();
// Mark the tunnel as connecting
tunnel.setState(Guacamole.Tunnel.State.CONNECTING);
parser = new Guacamole.Parser();
parser.oninstruction = function instructionReceived(opcode, args) {
// Update state and UUID when first instruction received
if (tunnel.uuid === null) {
// Associate tunnel UUID if received
if (opcode === Guacamole.Tunnel.INTERNAL_DATA_OPCODE && args.length === 1)
tunnel.setUUID(args[0]);
// Tunnel is now open and UUID is available
tunnel.setState(Guacamole.Tunnel.State.OPEN);
}
// Call instruction handler.
if (opcode !== Guacamole.Tunnel.INTERNAL_DATA_OPCODE && tunnel.oninstruction)
tunnel.oninstruction(opcode, args);
};
// Connect socket
socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
socket.onopen = function(event) {
resetTimers();
};
socket.onclose = function(event) {
// Pull status code directly from closure reason provided by Guacamole
if (event.reason)