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)
185 sendPendingMessages();
188 message_xmlhttprequest.send(outputMessageBuffer);
189 outputMessageBuffer = ""; // Clear buffer
193 sendingMessages = false;
198 function handleResponse(xmlhttprequest) {
201 var nextRequest = null;
203 var dataUpdateEvents = 0;
205 // The location of the last element's terminator
208 // Where to start the next length search or the next element
212 var elements = new Array();
214 function parseResponse() {
216 // Do not handle responses if not connected
217 if (currentState != STATE_CONNECTED) {
219 // Clean up interval if polling
220 if (interval != null)
221 clearInterval(interval);
226 // Attempt to read status
228 try { status = xmlhttprequest.status; }
230 // If status could not be read, assume successful.
231 catch (e) { status = 200; }
233 // Start next request as soon as possible IF request was successful
234 if (xmlhttprequest.readyState >= 2 && nextRequest == null && status == 200)
235 nextRequest = makeRequest();
237 // Parse stream when data is received and when complete.
238 if (xmlhttprequest.readyState == 3 ||
239 xmlhttprequest.readyState == 4) {
241 // Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
242 if (pollingMode == POLLING_ENABLED) {
243 if (xmlhttprequest.readyState == 3 && interval == null)
244 interval = setInterval(parseResponse, 30);
245 else if (xmlhttprequest.readyState == 4 && interval != null)
246 clearInterval(interval);
249 // If canceled, stop transfer
250 if (xmlhttprequest.status == 0) {
255 // Halt on error during request
256 else if (xmlhttprequest.status != 200) {
258 // Get error message (if any)
259 var message = xmlhttprequest.getResponseHeader("X-Guacamole-Error-Message");
261 message = "Internal server error";
263 // Call error handler
264 if (tunnel.onerror) tunnel.onerror(message);
271 // Attempt to read in-progress data
273 try { current = xmlhttprequest.responseText; }
275 // Do not attempt to parse if data could not be read
276 catch (e) { return; }
278 // While search is within currently received data
279 while (elementEnd < current.length) {
281 // If we are waiting for element data
282 if (elementEnd >= startIndex) {
284 // We now have enough data for the element. Parse.
285 var element = current.substring(startIndex, elementEnd);
286 var terminator = current.substring(elementEnd, elementEnd+1);
288 // Add element to array
289 elements.push(element);
291 // If last element, handle instruction
292 if (terminator == ";") {
295 var opcode = elements.shift();
297 // Call instruction handler.
298 if (tunnel.oninstruction != null)
299 tunnel.oninstruction(opcode, elements);
306 // Start searching for length at character after
307 // element terminator
308 startIndex = elementEnd + 1;
312 // Search for end of length
313 var lengthEnd = current.indexOf(".", startIndex);
314 if (lengthEnd != -1) {
317 var length = parseInt(current.substring(elementEnd+1, lengthEnd));
319 // If we're done parsing, handle the next response.
322 // Clean up interval if polling
323 if (interval != null)
324 clearInterval(interval);
327 xmlhttprequest.onreadystatechange = null;
328 xmlhttprequest.abort();
330 // Start handling next request
332 handleResponse(nextRequest);
339 // Calculate start of element
340 startIndex = lengthEnd + 1;
342 // Calculate location of element terminator
343 elementEnd = startIndex + length;
347 // If no period yet, continue search when more data
350 startIndex = current.length;
360 // If response polling enabled, attempt to detect if still
361 // necessary (via wrapping parseResponse())
362 if (pollingMode == POLLING_ENABLED) {
363 xmlhttprequest.onreadystatechange = function() {
365 // If we receive two or more readyState==3 events,
366 // there is no need to poll.
367 if (xmlhttprequest.readyState == 3) {
369 if (dataUpdateEvents >= 2) {
370 pollingMode = POLLING_DISABLED;
371 xmlhttprequest.onreadystatechange = parseResponse;
379 // Otherwise, just parse
381 xmlhttprequest.onreadystatechange = parseResponse;
388 function makeRequest() {
391 var xmlhttprequest = new XMLHttpRequest();
392 xmlhttprequest.open("POST", TUNNEL_READ + tunnel_uuid);
393 xmlhttprequest.send(null);
395 return xmlhttprequest;
399 this.connect = function(data) {
401 // Start tunnel and connect synchronously
402 var connect_xmlhttprequest = new XMLHttpRequest();
403 connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, false);
404 connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
405 connect_xmlhttprequest.send(data);
407 // If failure, throw error
408 if (connect_xmlhttprequest.status != 200) {
410 var message = connect_xmlhttprequest.getResponseHeader("X-Guacamole-Error-Message");
412 message = "Internal error";
414 throw new Error(message);
418 // Get UUID from response
419 tunnel_uuid = connect_xmlhttprequest.responseText;
421 // Start reading data
422 currentState = STATE_CONNECTED;
423 handleResponse(makeRequest());
427 this.disconnect = function() {
428 currentState = STATE_DISCONNECTED;
433 Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();