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;
207 function handleHTTPTunnelError(xmlhttprequest) {
209 // Get error message (if any)
210 var message = xmlhttprequest.getResponseHeader("X-Guacamole-Error-Message");
212 message = "Internal server error";
214 // Call error handler
215 if (tunnel.onerror) tunnel.onerror(message);
223 function handleResponse(xmlhttprequest) {
226 var nextRequest = null;
228 var dataUpdateEvents = 0;
230 // The location of the last element's terminator
233 // Where to start the next length search or the next element
237 var elements = new Array();
239 function parseResponse() {
241 // Do not handle responses if not connected
242 if (currentState != STATE_CONNECTED) {
244 // Clean up interval if polling
245 if (interval != null)
246 clearInterval(interval);
251 // Do not parse response yet if not ready
252 if (xmlhttprequest.readyState < 2) return;
254 // Attempt to read status
256 try { status = xmlhttprequest.status; }
258 // If status could not be read, assume successful.
259 catch (e) { status = 200; }
261 // Start next request as soon as possible IF request was successful
262 if (nextRequest == null && status == 200)
263 nextRequest = makeRequest();
265 // Parse stream when data is received and when complete.
266 if (xmlhttprequest.readyState == 3 ||
267 xmlhttprequest.readyState == 4) {
269 // Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
270 if (pollingMode == POLLING_ENABLED) {
271 if (xmlhttprequest.readyState == 3 && interval == null)
272 interval = setInterval(parseResponse, 30);
273 else if (xmlhttprequest.readyState == 4 && interval != null)
274 clearInterval(interval);
277 // If canceled, stop transfer
278 if (xmlhttprequest.status == 0) {
283 // Halt on error during request
284 else if (xmlhttprequest.status != 200) {
285 handleHTTPTunnelError(xmlhttprequest);
289 // Attempt to read in-progress data
291 try { current = xmlhttprequest.responseText; }
293 // Do not attempt to parse if data could not be read
294 catch (e) { return; }
296 // While search is within currently received data
297 while (elementEnd < current.length) {
299 // If we are waiting for element data
300 if (elementEnd >= startIndex) {
302 // We now have enough data for the element. Parse.
303 var element = current.substring(startIndex, elementEnd);
304 var terminator = current.substring(elementEnd, elementEnd+1);
306 // Add element to array
307 elements.push(element);
309 // If last element, handle instruction
310 if (terminator == ";") {
313 var opcode = elements.shift();
315 // Call instruction handler.
316 if (tunnel.oninstruction != null)
317 tunnel.oninstruction(opcode, elements);
324 // Start searching for length at character after
325 // element terminator
326 startIndex = elementEnd + 1;
330 // Search for end of length
331 var lengthEnd = current.indexOf(".", startIndex);
332 if (lengthEnd != -1) {
335 var length = parseInt(current.substring(elementEnd+1, lengthEnd));
337 // If we're done parsing, handle the next response.
340 // Clean up interval if polling
341 if (interval != null)
342 clearInterval(interval);
345 xmlhttprequest.onreadystatechange = null;
346 xmlhttprequest.abort();
348 // Start handling next request
350 handleResponse(nextRequest);
357 // Calculate start of element
358 startIndex = lengthEnd + 1;
360 // Calculate location of element terminator
361 elementEnd = startIndex + length;
365 // If no period yet, continue search when more data
368 startIndex = current.length;
378 // If response polling enabled, attempt to detect if still
379 // necessary (via wrapping parseResponse())
380 if (pollingMode == POLLING_ENABLED) {
381 xmlhttprequest.onreadystatechange = function() {
383 // If we receive two or more readyState==3 events,
384 // there is no need to poll.
385 if (xmlhttprequest.readyState == 3) {
387 if (dataUpdateEvents >= 2) {
388 pollingMode = POLLING_DISABLED;
389 xmlhttprequest.onreadystatechange = parseResponse;
397 // Otherwise, just parse
399 xmlhttprequest.onreadystatechange = parseResponse;
406 function makeRequest() {
409 var xmlhttprequest = new XMLHttpRequest();
410 xmlhttprequest.open("POST", TUNNEL_READ + tunnel_uuid);
411 xmlhttprequest.send(null);
413 return xmlhttprequest;
417 this.connect = function(data) {
419 // Start tunnel and connect synchronously
420 var connect_xmlhttprequest = new XMLHttpRequest();
421 connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, false);
422 connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
423 connect_xmlhttprequest.send(data);
425 // If failure, throw error
426 if (connect_xmlhttprequest.status != 200) {
428 var message = connect_xmlhttprequest.getResponseHeader("X-Guacamole-Error-Message");
430 message = "Internal error";
432 throw new Error(message);
436 // Get UUID from response
437 tunnel_uuid = connect_xmlhttprequest.responseText;
439 // Start reading data
440 currentState = STATE_CONNECTED;
441 handleResponse(makeRequest());
445 this.disconnect = function() {
446 currentState = STATE_DISCONNECTED;
451 Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
455 * Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
458 * @augments Guacamole.Tunnel
459 * @param {String} tunnelURL The URL of the WebSocket tunneling service.
461 Guacamole.WebSocketTunnel = function(tunnelURL) {
464 * Reference to this WebSocket tunnel.
469 * The WebSocket used by this tunnel.
474 * The WebSocket protocol corresponding to the protocol used for the current
483 1000: "Connection closed normally.",
484 1001: "Connection shut down.",
485 1002: "Protocol error.",
486 1003: "Invalid data.",
487 1004: "[UNKNOWN, RESERVED]",
488 1005: "No status code present.",
489 1006: "Connection closed abnormally.",
490 1007: "Inconsistent data type.",
491 1008: "Policy violation.",
492 1009: "Message too large.",
493 1010: "Extension negotiation failed."
497 var STATE_CONNECTED = 1;
498 var STATE_DISCONNECTED = 2;
500 var currentState = STATE_IDLE;
502 // Transform current URL to WebSocket URL
504 // If not already a websocket URL
505 if ( tunnelURL.substring(0, 3) != "ws:"
506 && tunnelURL.substring(0, 4) != "wss:") {
508 var protocol = ws_protocol[window.location.protocol];
510 // If absolute URL, convert to absolute WS URL
511 if (tunnelURL.substring(0, 1) == "/")
514 + "//" + window.location.host
517 // Otherwise, construct absolute from relative URL
520 // Get path from pathname
521 var slash = window.location.pathname.lastIndexOf("/");
522 var path = window.location.pathname.substring(0, slash + 1);
524 // Construct absolute URL
527 + "//" + window.location.host
535 this.sendMessage = function(elements) {
537 // Do not attempt to send messages if not connected
538 if (currentState != STATE_CONNECTED)
541 // Do not attempt to send empty messages
542 if (arguments.length == 0)
546 * Converts the given value to a length/string pair for use as an
547 * element in a Guacamole instruction.
549 * @param value The value to convert.
550 * @return {String} The converted value.
552 function getElement(value) {
553 var string = new String(value);
554 return string.length + "." + string;
557 // Initialized message with first element
558 var message = getElement(arguments[0]);
560 // Append remaining elements
561 for (var i=1; i<arguments.length; i++)
562 message += "," + getElement(arguments[i]);
567 socket.send(message);
571 this.connect = function(data) {
574 socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
576 socket.onopen = function(event) {
577 currentState = STATE_CONNECTED;
580 socket.onclose = function(event) {
582 // If connection closed abnormally, signal error.
583 if (event.code != 1000 && tunnel.onerror)
584 tunnel.onerror(status_code[event.code]);
588 socket.onerror = function(event) {
590 // Call error handler
591 if (tunnel.onerror) tunnel.onerror(event.data);
595 socket.onmessage = function(event) {
597 var message = event.data;
605 // Search for end of length
606 var lengthEnd = message.indexOf(".", startIndex);
607 if (lengthEnd != -1) {
610 var length = parseInt(message.substring(elementEnd+1, lengthEnd));
612 // Calculate start of element
613 startIndex = lengthEnd + 1;
615 // Calculate location of element terminator
616 elementEnd = startIndex + length;
620 // If no period, incomplete instruction.
622 throw new Error("Incomplete instruction.");
624 // We now have enough data for the element. Parse.
625 var element = message.substring(startIndex, elementEnd);
626 var terminator = message.substring(elementEnd, elementEnd+1);
628 // Add element to array
629 elements.push(element);
631 // If last element, handle instruction
632 if (terminator == ";") {
635 var opcode = elements.shift();
637 // Call instruction handler.
638 if (tunnel.oninstruction != null)
639 tunnel.oninstruction(opcode, elements);
646 // Start searching for length at character after
647 // element terminator
648 startIndex = elementEnd + 1;
650 } while (startIndex < message.length);
656 this.disconnect = function() {
657 currentState = STATE_DISCONNECTED;
663 Guacamole.WebSocketTunnel.prototype = new Guacamole.Tunnel();
667 * Guacamole Tunnel which cycles between all specified tunnels until
668 * no tunnels are left. Another tunnel is used if an error occurs but
669 * no instructions have been received. If an instruction has been
670 * received, or no tunnels remain, the error is passed directly out
671 * through the onerror handler (if defined).
674 * @augments Guacamole.Tunnel
675 * @param {...} tunnel_chain The tunnels to use, in order of priority.
677 Guacamole.ChainedTunnel = function(tunnel_chain) {
680 * Reference to this chained tunnel.
682 var chained_tunnel = this;
685 * The currently wrapped tunnel, if any.
687 var current_tunnel = null;
690 * Data passed in via connect(), to be used for
691 * wrapped calls to other tunnels' connect() functions.
696 * Array of all tunnels passed to this ChainedTunnel through the
697 * constructor arguments.
701 // Load all tunnels into array
702 for (var i=0; i<arguments.length; i++)
703 tunnels.push(arguments[i]);
706 * Sets the current tunnel
708 function attach(tunnel) {
710 // Set own functions to tunnel's functions
711 chained_tunnel.disconnect = tunnel.disconnect;
712 chained_tunnel.sendMessage = tunnel.sendMessage;
714 // Record current tunnel
715 current_tunnel = tunnel;
717 // Wrap own oninstruction within current tunnel
718 current_tunnel.oninstruction = function(opcode, elements) {
721 chained_tunnel.oninstruction(opcode, elements);
723 // Use handler permanently from now on
724 current_tunnel.oninstruction = chained_tunnel.oninstruction;
726 // Pass through errors (without trying other tunnels)
727 current_tunnel.onerror = chained_tunnel.onerror;
731 // Attach next tunnel on error
732 current_tunnel.onerror = function(message) {
735 var next_tunnel = tunnels.shift();
737 // If there IS a next tunnel, try using it.
741 // Otherwise, call error handler
742 else if (chained_tunnel.onerror)
743 chained_tunnel.onerror(message);
749 // Attempt connection
750 current_tunnel.connect(connect_data);
755 // Call error handler of current tunnel on error
756 current_tunnel.onerror(e.message);
763 this.connect = function(data) {
765 // Remember connect data
769 var next_tunnel = tunnels.shift();
771 // Attach first tunnel
775 // If there IS no first tunnel, error
776 else if (chained_tunnel.onerror)
777 chained_tunnel.onerror("No tunnels to try.");
783 Guacamole.ChainedTunnel.prototype = new Guacamole.Tunnel();