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;
211 if (status == 0) return "Disconnected";
212 if (status == 200) return "Success";
213 if (status == 403) return "Unauthorized";
214 if (status == 404) return "Connection closed"; /* While it may be more
215 * accurate to say the
216 * connection does not
217 * exist, it is confusing
220 * In general, this error
221 * will only happen when
222 * the tunnel does not
223 * exist, which happens
224 * after the connection
226 * tunnel is detached.
228 // Internal server errors
229 if (status >= 500 && status <= 599) return "Server error";
231 // Otherwise, unknown
232 return "Unknown error";
236 function handleHTTPTunnelError(xmlhttprequest) {
239 var message = getHTTPTunnelErrorMessage(xmlhttprequest);
241 // Call error handler
242 if (tunnel.onerror) tunnel.onerror(message);
250 function handleResponse(xmlhttprequest) {
253 var nextRequest = null;
255 var dataUpdateEvents = 0;
257 // The location of the last element's terminator
260 // Where to start the next length search or the next element
264 var elements = new Array();
266 function parseResponse() {
268 // Do not handle responses if not connected
269 if (currentState != STATE_CONNECTED) {
271 // Clean up interval if polling
272 if (interval != null)
273 clearInterval(interval);
278 // Do not parse response yet if not ready
279 if (xmlhttprequest.readyState < 2) return;
281 // Attempt to read status
283 try { status = xmlhttprequest.status; }
285 // If status could not be read, assume successful.
286 catch (e) { status = 200; }
288 // Start next request as soon as possible IF request was successful
289 if (nextRequest == null && status == 200)
290 nextRequest = makeRequest();
292 // Parse stream when data is received and when complete.
293 if (xmlhttprequest.readyState == 3 ||
294 xmlhttprequest.readyState == 4) {
296 // Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
297 if (pollingMode == POLLING_ENABLED) {
298 if (xmlhttprequest.readyState == 3 && interval == null)
299 interval = setInterval(parseResponse, 30);
300 else if (xmlhttprequest.readyState == 4 && interval != null)
301 clearInterval(interval);
304 // If canceled, stop transfer
305 if (xmlhttprequest.status == 0) {
310 // Halt on error during request
311 else if (xmlhttprequest.status != 200) {
312 handleHTTPTunnelError(xmlhttprequest);
316 // Attempt to read in-progress data
318 try { current = xmlhttprequest.responseText; }
320 // Do not attempt to parse if data could not be read
321 catch (e) { return; }
323 // While search is within currently received data
324 while (elementEnd < current.length) {
326 // If we are waiting for element data
327 if (elementEnd >= startIndex) {
329 // We now have enough data for the element. Parse.
330 var element = current.substring(startIndex, elementEnd);
331 var terminator = current.substring(elementEnd, elementEnd+1);
333 // Add element to array
334 elements.push(element);
336 // If last element, handle instruction
337 if (terminator == ";") {
340 var opcode = elements.shift();
342 // Call instruction handler.
343 if (tunnel.oninstruction != null)
344 tunnel.oninstruction(opcode, elements);
351 // Start searching for length at character after
352 // element terminator
353 startIndex = elementEnd + 1;
357 // Search for end of length
358 var lengthEnd = current.indexOf(".", startIndex);
359 if (lengthEnd != -1) {
362 var length = parseInt(current.substring(elementEnd+1, lengthEnd));
364 // If we're done parsing, handle the next response.
367 // Clean up interval if polling
368 if (interval != null)
369 clearInterval(interval);
372 xmlhttprequest.onreadystatechange = null;
373 xmlhttprequest.abort();
375 // Start handling next request
377 handleResponse(nextRequest);
384 // Calculate start of element
385 startIndex = lengthEnd + 1;
387 // Calculate location of element terminator
388 elementEnd = startIndex + length;
392 // If no period yet, continue search when more data
395 startIndex = current.length;
405 // If response polling enabled, attempt to detect if still
406 // necessary (via wrapping parseResponse())
407 if (pollingMode == POLLING_ENABLED) {
408 xmlhttprequest.onreadystatechange = function() {
410 // If we receive two or more readyState==3 events,
411 // there is no need to poll.
412 if (xmlhttprequest.readyState == 3) {
414 if (dataUpdateEvents >= 2) {
415 pollingMode = POLLING_DISABLED;
416 xmlhttprequest.onreadystatechange = parseResponse;
424 // Otherwise, just parse
426 xmlhttprequest.onreadystatechange = parseResponse;
433 function makeRequest() {
436 var xmlhttprequest = new XMLHttpRequest();
437 xmlhttprequest.open("POST", TUNNEL_READ + tunnel_uuid);
438 xmlhttprequest.send(null);
440 return xmlhttprequest;
444 this.connect = function(data) {
446 // Start tunnel and connect synchronously
447 var connect_xmlhttprequest = new XMLHttpRequest();
448 connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, false);
449 connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
450 connect_xmlhttprequest.send(data);
452 // If failure, throw error
453 if (connect_xmlhttprequest.status != 200) {
454 var message = getHTTPTunnelErrorMessage(connect_xmlhttprequest);
455 throw new Error(message);
458 // Get UUID from response
459 tunnel_uuid = connect_xmlhttprequest.responseText;
461 // Start reading data
462 currentState = STATE_CONNECTED;
463 handleResponse(makeRequest());
467 this.disconnect = function() {
468 currentState = STATE_DISCONNECTED;
473 Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
477 * Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
480 * @augments Guacamole.Tunnel
481 * @param {String} tunnelURL The URL of the WebSocket tunneling service.
483 Guacamole.WebSocketTunnel = function(tunnelURL) {
486 * Reference to this WebSocket tunnel.
491 * The WebSocket used by this tunnel.
496 * The WebSocket protocol corresponding to the protocol used for the current
505 1000: "Connection closed normally.",
506 1001: "Connection shut down.",
507 1002: "Protocol error.",
508 1003: "Invalid data.",
509 1004: "[UNKNOWN, RESERVED]",
510 1005: "No status code present.",
511 1006: "Connection closed abnormally.",
512 1007: "Inconsistent data type.",
513 1008: "Policy violation.",
514 1009: "Message too large.",
515 1010: "Extension negotiation failed."
519 var STATE_CONNECTED = 1;
520 var STATE_DISCONNECTED = 2;
522 var currentState = STATE_IDLE;
524 // Transform current URL to WebSocket URL
526 // If not already a websocket URL
527 if ( tunnelURL.substring(0, 3) != "ws:"
528 && tunnelURL.substring(0, 4) != "wss:") {
530 var protocol = ws_protocol[window.location.protocol];
532 // If absolute URL, convert to absolute WS URL
533 if (tunnelURL.substring(0, 1) == "/")
536 + "//" + window.location.host
539 // Otherwise, construct absolute from relative URL
542 // Get path from pathname
543 var slash = window.location.pathname.lastIndexOf("/");
544 var path = window.location.pathname.substring(0, slash + 1);
546 // Construct absolute URL
549 + "//" + window.location.host
557 this.sendMessage = function(elements) {
559 // Do not attempt to send messages if not connected
560 if (currentState != STATE_CONNECTED)
563 // Do not attempt to send empty messages
564 if (arguments.length == 0)
568 * Converts the given value to a length/string pair for use as an
569 * element in a Guacamole instruction.
571 * @param value The value to convert.
572 * @return {String} The converted value.
574 function getElement(value) {
575 var string = new String(value);
576 return string.length + "." + string;
579 // Initialized message with first element
580 var message = getElement(arguments[0]);
582 // Append remaining elements
583 for (var i=1; i<arguments.length; i++)
584 message += "," + getElement(arguments[i]);
589 socket.send(message);
593 this.connect = function(data) {
596 socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
598 socket.onopen = function(event) {
599 currentState = STATE_CONNECTED;
602 socket.onclose = function(event) {
604 // If connection closed abnormally, signal error.
605 if (event.code != 1000 && tunnel.onerror)
606 tunnel.onerror(status_code[event.code]);
610 socket.onerror = function(event) {
612 // Call error handler
613 if (tunnel.onerror) tunnel.onerror(event.data);
617 socket.onmessage = function(event) {
619 var message = event.data;
627 // Search for end of length
628 var lengthEnd = message.indexOf(".", startIndex);
629 if (lengthEnd != -1) {
632 var length = parseInt(message.substring(elementEnd+1, lengthEnd));
634 // Calculate start of element
635 startIndex = lengthEnd + 1;
637 // Calculate location of element terminator
638 elementEnd = startIndex + length;
642 // If no period, incomplete instruction.
644 throw new Error("Incomplete instruction.");
646 // We now have enough data for the element. Parse.
647 var element = message.substring(startIndex, elementEnd);
648 var terminator = message.substring(elementEnd, elementEnd+1);
650 // Add element to array
651 elements.push(element);
653 // If last element, handle instruction
654 if (terminator == ";") {
657 var opcode = elements.shift();
659 // Call instruction handler.
660 if (tunnel.oninstruction != null)
661 tunnel.oninstruction(opcode, elements);
668 // Start searching for length at character after
669 // element terminator
670 startIndex = elementEnd + 1;
672 } while (startIndex < message.length);
678 this.disconnect = function() {
679 currentState = STATE_DISCONNECTED;
685 Guacamole.WebSocketTunnel.prototype = new Guacamole.Tunnel();
689 * Guacamole Tunnel which cycles between all specified tunnels until
690 * no tunnels are left. Another tunnel is used if an error occurs but
691 * no instructions have been received. If an instruction has been
692 * received, or no tunnels remain, the error is passed directly out
693 * through the onerror handler (if defined).
696 * @augments Guacamole.Tunnel
697 * @param {...} tunnel_chain The tunnels to use, in order of priority.
699 Guacamole.ChainedTunnel = function(tunnel_chain) {
702 * Reference to this chained tunnel.
704 var chained_tunnel = this;
707 * The currently wrapped tunnel, if any.
709 var current_tunnel = null;
712 * Data passed in via connect(), to be used for
713 * wrapped calls to other tunnels' connect() functions.
718 * Array of all tunnels passed to this ChainedTunnel through the
719 * constructor arguments.
723 // Load all tunnels into array
724 for (var i=0; i<arguments.length; i++)
725 tunnels.push(arguments[i]);
728 * Sets the current tunnel
730 function attach(tunnel) {
732 // Clear handlers of current tunnel, if any
733 if (current_tunnel) {
734 current_tunnel.onerror = null;
735 current_tunnel.oninstruction = null;
738 // Set own functions to tunnel's functions
739 chained_tunnel.disconnect = tunnel.disconnect;
740 chained_tunnel.sendMessage = tunnel.sendMessage;
742 // Record current tunnel
743 current_tunnel = tunnel;
745 // Wrap own oninstruction within current tunnel
746 current_tunnel.oninstruction = function(opcode, elements) {
749 chained_tunnel.oninstruction(opcode, elements);
751 // Use handler permanently from now on
752 current_tunnel.oninstruction = chained_tunnel.oninstruction;
754 // Pass through errors (without trying other tunnels)
755 current_tunnel.onerror = chained_tunnel.onerror;
759 // Attach next tunnel on error
760 current_tunnel.onerror = function(message) {
763 var next_tunnel = tunnels.shift();
765 // If there IS a next tunnel, try using it.
769 // Otherwise, call error handler
770 else if (chained_tunnel.onerror)
771 chained_tunnel.onerror(message);
777 // Attempt connection
778 current_tunnel.connect(connect_data);
783 // Call error handler of current tunnel on error
784 current_tunnel.onerror(e.message);
791 this.connect = function(data) {
793 // Remember connect data
797 var next_tunnel = tunnels.shift();
799 // Attach first tunnel
803 // If there IS no first tunnel, error
804 else if (chained_tunnel.onerror)
805 chained_tunnel.onerror("No tunnels to try.");
811 Guacamole.ChainedTunnel.prototype = new Guacamole.Tunnel();