2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is guacamole-common-js.
17 * The Initial Developer of the Original Code is
19 * Portions created by the Initial Developer are Copyright (C) 2010
20 * the Initial Developer. All Rights Reserved.
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
38 // Guacamole namespace
39 var Guacamole = Guacamole || {};
42 * Core object providing abstract communication for Guacamole. This object
43 * is a null implementation whose functions do nothing. Guacamole applications
44 * should use {@link Guacamole.HTTPTunnel} instead, or implement their own tunnel based
48 * @see Guacamole.HTTPTunnel
50 Guacamole.Tunnel = function() {
53 * Connect to the tunnel with the given optional data. This data is
54 * typically used for authentication. The format of data accepted is
55 * up to the tunnel implementation.
57 * @param {String} data The data to send to the tunnel when connecting.
59 this.connect = function(data) {};
62 * Disconnect from the tunnel.
64 this.disconnect = function() {};
67 * Send the given message through the tunnel to the service on the other
68 * side. All messages are guaranteed to be received in the order sent.
70 * @param {...} elements The elements of the message to send to the
71 * service on the other side of the tunnel.
73 this.sendMessage = function(elements) {};
76 * Fired whenever an error is encountered by the tunnel.
79 * @param {String} message A human-readable description of the error that
85 * Fired once for every complete Guacamole instruction received, in order.
88 * @param {String} opcode The Guacamole instruction opcode.
89 * @param {Array} parameters The parameters provided for the instruction,
92 this.oninstruction = null;
97 * Guacamole Tunnel implemented over HTTP via XMLHttpRequest.
100 * @augments Guacamole.Tunnel
101 * @param {String} tunnelURL The URL of the HTTP tunneling service.
103 Guacamole.HTTPTunnel = function(tunnelURL) {
106 * Reference to this HTTP tunnel.
112 var TUNNEL_CONNECT = tunnelURL + "?connect";
113 var TUNNEL_READ = tunnelURL + "?read:";
114 var TUNNEL_WRITE = tunnelURL + "?write:";
117 var STATE_CONNECTED = 1;
118 var STATE_DISCONNECTED = 2;
120 var currentState = STATE_IDLE;
122 var POLLING_ENABLED = 1;
123 var POLLING_DISABLED = 0;
125 // Default to polling - will be turned off automatically if not needed
126 var pollingMode = POLLING_ENABLED;
128 var sendingMessages = false;
129 var outputMessageBuffer = "";
131 this.sendMessage = function() {
133 // Do not attempt to send messages if not connected
134 if (currentState != STATE_CONNECTED)
137 // Do not attempt to send empty messages
138 if (arguments.length == 0)
142 * Converts the given value to a length/string pair for use as an
143 * element in a Guacamole instruction.
145 * @param value The value to convert.
146 * @return {String} The converted value.
148 function getElement(value) {
149 var string = new String(value);
150 return string.length + "." + string;
153 // Initialized message with first element
154 var message = getElement(arguments[0]);
156 // Append remaining elements
157 for (var i=1; i<arguments.length; i++)
158 message += "," + getElement(arguments[i]);
163 // Add message to buffer
164 outputMessageBuffer += message;
166 // Send if not currently sending
167 if (!sendingMessages)
168 sendPendingMessages();
172 function sendPendingMessages() {
174 if (outputMessageBuffer.length > 0) {
176 sendingMessages = true;
178 var message_xmlhttprequest = new XMLHttpRequest();
179 message_xmlhttprequest.open("POST", TUNNEL_WRITE + tunnel_uuid);
180 message_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
182 // Once response received, send next queued event.
183 message_xmlhttprequest.onreadystatechange = function() {
184 if (message_xmlhttprequest.readyState == 4) {
186 // If an error occurs during send, handle it
187 if (message_xmlhttprequest.status != 200)
188 handleHTTPTunnelError(message_xmlhttprequest);
190 // Otherwise, continue the send loop
192 sendPendingMessages();
197 message_xmlhttprequest.send(outputMessageBuffer);
198 outputMessageBuffer = ""; // Clear buffer
202 sendingMessages = false;
206 function getHTTPTunnelErrorMessage(xmlhttprequest) {
208 var status = xmlhttprequest.status;
210 if (status >= 200 && status <= 299) return "Success";
211 if (status >= 400 && status <= 499) return "Unauthorized";
212 if (status >= 500 && status <= 599) return "Connection lost";
214 return "Unknown error";
218 function handleHTTPTunnelError(xmlhttprequest) {
221 var message = getHTTPTunnelErrorMessage(xmlhttprequest);
223 // Call error handler
224 if (tunnel.onerror) tunnel.onerror(message);
232 function handleResponse(xmlhttprequest) {
235 var nextRequest = null;
237 var dataUpdateEvents = 0;
239 // The location of the last element's terminator
242 // Where to start the next length search or the next element
246 var elements = new Array();
248 function parseResponse() {
250 // Do not handle responses if not connected
251 if (currentState != STATE_CONNECTED) {
253 // Clean up interval if polling
254 if (interval != null)
255 clearInterval(interval);
260 // Do not parse response yet if not ready
261 if (xmlhttprequest.readyState < 2) return;
263 // Attempt to read status
265 try { status = xmlhttprequest.status; }
267 // If status could not be read, assume successful.
268 catch (e) { status = 200; }
270 // Start next request as soon as possible IF request was successful
271 if (nextRequest == null && status == 200)
272 nextRequest = makeRequest();
274 // Parse stream when data is received and when complete.
275 if (xmlhttprequest.readyState == 3 ||
276 xmlhttprequest.readyState == 4) {
278 // Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
279 if (pollingMode == POLLING_ENABLED) {
280 if (xmlhttprequest.readyState == 3 && interval == null)
281 interval = setInterval(parseResponse, 30);
282 else if (xmlhttprequest.readyState == 4 && interval != null)
283 clearInterval(interval);
286 // If canceled, stop transfer
287 if (xmlhttprequest.status == 0) {
292 // Halt on error during request
293 else if (xmlhttprequest.status != 200) {
294 handleHTTPTunnelError(xmlhttprequest);
298 // Attempt to read in-progress data
300 try { current = xmlhttprequest.responseText; }
302 // Do not attempt to parse if data could not be read
303 catch (e) { return; }
305 // While search is within currently received data
306 while (elementEnd < current.length) {
308 // If we are waiting for element data
309 if (elementEnd >= startIndex) {
311 // We now have enough data for the element. Parse.
312 var element = current.substring(startIndex, elementEnd);
313 var terminator = current.substring(elementEnd, elementEnd+1);
315 // Add element to array
316 elements.push(element);
318 // If last element, handle instruction
319 if (terminator == ";") {
322 var opcode = elements.shift();
324 // Call instruction handler.
325 if (tunnel.oninstruction != null)
326 tunnel.oninstruction(opcode, elements);
333 // Start searching for length at character after
334 // element terminator
335 startIndex = elementEnd + 1;
339 // Search for end of length
340 var lengthEnd = current.indexOf(".", startIndex);
341 if (lengthEnd != -1) {
344 var length = parseInt(current.substring(elementEnd+1, lengthEnd));
346 // If we're done parsing, handle the next response.
349 // Clean up interval if polling
350 if (interval != null)
351 clearInterval(interval);
354 xmlhttprequest.onreadystatechange = null;
355 xmlhttprequest.abort();
357 // Start handling next request
359 handleResponse(nextRequest);
366 // Calculate start of element
367 startIndex = lengthEnd + 1;
369 // Calculate location of element terminator
370 elementEnd = startIndex + length;
374 // If no period yet, continue search when more data
377 startIndex = current.length;
387 // If response polling enabled, attempt to detect if still
388 // necessary (via wrapping parseResponse())
389 if (pollingMode == POLLING_ENABLED) {
390 xmlhttprequest.onreadystatechange = function() {
392 // If we receive two or more readyState==3 events,
393 // there is no need to poll.
394 if (xmlhttprequest.readyState == 3) {
396 if (dataUpdateEvents >= 2) {
397 pollingMode = POLLING_DISABLED;
398 xmlhttprequest.onreadystatechange = parseResponse;
406 // Otherwise, just parse
408 xmlhttprequest.onreadystatechange = parseResponse;
415 function makeRequest() {
418 var xmlhttprequest = new XMLHttpRequest();
419 xmlhttprequest.open("POST", TUNNEL_READ + tunnel_uuid);
420 xmlhttprequest.send(null);
422 return xmlhttprequest;
426 this.connect = function(data) {
428 // Start tunnel and connect synchronously
429 var connect_xmlhttprequest = new XMLHttpRequest();
430 connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, false);
431 connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
432 connect_xmlhttprequest.send(data);
434 // If failure, throw error
435 if (connect_xmlhttprequest.status != 200) {
436 var message = getHTTPTunnelErrorMessage(connect_xmlhttprequest);
437 throw new Error(message);
440 // Get UUID from response
441 tunnel_uuid = connect_xmlhttprequest.responseText;
443 // Start reading data
444 currentState = STATE_CONNECTED;
445 handleResponse(makeRequest());
449 this.disconnect = function() {
450 currentState = STATE_DISCONNECTED;
455 Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
459 * Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
462 * @augments Guacamole.Tunnel
463 * @param {String} tunnelURL The URL of the WebSocket tunneling service.
465 Guacamole.WebSocketTunnel = function(tunnelURL) {
468 * Reference to this WebSocket tunnel.
473 * The WebSocket used by this tunnel.
478 * The WebSocket protocol corresponding to the protocol used for the current
487 1000: "Connection closed normally.",
488 1001: "Connection shut down.",
489 1002: "Protocol error.",
490 1003: "Invalid data.",
491 1004: "[UNKNOWN, RESERVED]",
492 1005: "No status code present.",
493 1006: "Connection closed abnormally.",
494 1007: "Inconsistent data type.",
495 1008: "Policy violation.",
496 1009: "Message too large.",
497 1010: "Extension negotiation failed."
501 var STATE_CONNECTED = 1;
502 var STATE_DISCONNECTED = 2;
504 var currentState = STATE_IDLE;
506 // Transform current URL to WebSocket URL
508 // If not already a websocket URL
509 if ( tunnelURL.substring(0, 3) != "ws:"
510 && tunnelURL.substring(0, 4) != "wss:") {
512 var protocol = ws_protocol[window.location.protocol];
514 // If absolute URL, convert to absolute WS URL
515 if (tunnelURL.substring(0, 1) == "/")
518 + "//" + window.location.host
521 // Otherwise, construct absolute from relative URL
524 // Get path from pathname
525 var slash = window.location.pathname.lastIndexOf("/");
526 var path = window.location.pathname.substring(0, slash + 1);
528 // Construct absolute URL
531 + "//" + window.location.host
539 this.sendMessage = function(elements) {
541 // Do not attempt to send messages if not connected
542 if (currentState != STATE_CONNECTED)
545 // Do not attempt to send empty messages
546 if (arguments.length == 0)
550 * Converts the given value to a length/string pair for use as an
551 * element in a Guacamole instruction.
553 * @param value The value to convert.
554 * @return {String} The converted value.
556 function getElement(value) {
557 var string = new String(value);
558 return string.length + "." + string;
561 // Initialized message with first element
562 var message = getElement(arguments[0]);
564 // Append remaining elements
565 for (var i=1; i<arguments.length; i++)
566 message += "," + getElement(arguments[i]);
571 socket.send(message);
575 this.connect = function(data) {
578 socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
580 socket.onopen = function(event) {
581 currentState = STATE_CONNECTED;
584 socket.onclose = function(event) {
586 // If connection closed abnormally, signal error.
587 if (event.code != 1000 && tunnel.onerror)
588 tunnel.onerror(status_code[event.code]);
592 socket.onerror = function(event) {
594 // Call error handler
595 if (tunnel.onerror) tunnel.onerror(event.data);
599 socket.onmessage = function(event) {
601 var message = event.data;
609 // Search for end of length
610 var lengthEnd = message.indexOf(".", startIndex);
611 if (lengthEnd != -1) {
614 var length = parseInt(message.substring(elementEnd+1, lengthEnd));
616 // Calculate start of element
617 startIndex = lengthEnd + 1;
619 // Calculate location of element terminator
620 elementEnd = startIndex + length;
624 // If no period, incomplete instruction.
626 throw new Error("Incomplete instruction.");
628 // We now have enough data for the element. Parse.
629 var element = message.substring(startIndex, elementEnd);
630 var terminator = message.substring(elementEnd, elementEnd+1);
632 // Add element to array
633 elements.push(element);
635 // If last element, handle instruction
636 if (terminator == ";") {
639 var opcode = elements.shift();
641 // Call instruction handler.
642 if (tunnel.oninstruction != null)
643 tunnel.oninstruction(opcode, elements);
650 // Start searching for length at character after
651 // element terminator
652 startIndex = elementEnd + 1;
654 } while (startIndex < message.length);
660 this.disconnect = function() {
661 currentState = STATE_DISCONNECTED;
667 Guacamole.WebSocketTunnel.prototype = new Guacamole.Tunnel();
671 * Guacamole Tunnel which cycles between all specified tunnels until
672 * no tunnels are left. Another tunnel is used if an error occurs but
673 * no instructions have been received. If an instruction has been
674 * received, or no tunnels remain, the error is passed directly out
675 * through the onerror handler (if defined).
678 * @augments Guacamole.Tunnel
679 * @param {...} tunnel_chain The tunnels to use, in order of priority.
681 Guacamole.ChainedTunnel = function(tunnel_chain) {
684 * Reference to this chained tunnel.
686 var chained_tunnel = this;
689 * The currently wrapped tunnel, if any.
691 var current_tunnel = null;
694 * Data passed in via connect(), to be used for
695 * wrapped calls to other tunnels' connect() functions.
700 * Array of all tunnels passed to this ChainedTunnel through the
701 * constructor arguments.
705 // Load all tunnels into array
706 for (var i=0; i<arguments.length; i++)
707 tunnels.push(arguments[i]);
710 * Sets the current tunnel
712 function attach(tunnel) {
714 // Clear handlers of current tunnel, if any
715 if (current_tunnel) {
716 current_tunnel.onerror = null;
717 current_tunnel.oninstruction = null;
720 // Set own functions to tunnel's functions
721 chained_tunnel.disconnect = tunnel.disconnect;
722 chained_tunnel.sendMessage = tunnel.sendMessage;
724 // Record current tunnel
725 current_tunnel = tunnel;
727 // Wrap own oninstruction within current tunnel
728 current_tunnel.oninstruction = function(opcode, elements) {
731 chained_tunnel.oninstruction(opcode, elements);
733 // Use handler permanently from now on
734 current_tunnel.oninstruction = chained_tunnel.oninstruction;
736 // Pass through errors (without trying other tunnels)
737 current_tunnel.onerror = chained_tunnel.onerror;
741 // Attach next tunnel on error
742 current_tunnel.onerror = function(message) {
745 var next_tunnel = tunnels.shift();
747 // If there IS a next tunnel, try using it.
751 // Otherwise, call error handler
752 else if (chained_tunnel.onerror)
753 chained_tunnel.onerror(message);
759 // Attempt connection
760 current_tunnel.connect(connect_data);
765 // Call error handler of current tunnel on error
766 current_tunnel.onerror(e.message);
773 this.connect = function(data) {
775 // Remember connect data
779 var next_tunnel = tunnels.shift();
781 // Attach first tunnel
785 // If there IS no first tunnel, error
786 else if (chained_tunnel.onerror)
787 chained_tunnel.onerror("No tunnels to try.");
793 Guacamole.ChainedTunnel.prototype = new Guacamole.Tunnel();