f44110d44f4373f21d3c4448e97691a8940efe39
[guacamole-common-js.git] / src / main / resources / tunnel.js
1
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
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/
9  *
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
13  * License.
14  *
15  * The Original Code is guacamole-common-js.
16  *
17  * The Initial Developer of the Original Code is
18  * Michael Jumper.
19  * Portions created by the Initial Developer are Copyright (C) 2010
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *
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.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 // Guacamole namespace
39 var Guacamole = Guacamole || {};
40
41 /**
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
45  * on this one.
46  * 
47  * @constructor
48  * @see Guacamole.HTTPTunnel
49  */
50 Guacamole.Tunnel = function() {
51
52     /**
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.
56      * 
57      * @param {String} data The data to send to the tunnel when connecting.
58      */
59     this.connect = function(data) {};
60     
61     /**
62      * Disconnect from the tunnel.
63      */
64     this.disconnect = function() {};
65     
66     /**
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.
69      * 
70      * @param {...} elements The elements of the message to send to the
71      *                       service on the other side of the tunnel.
72      */
73     this.sendMessage = function(elements) {};
74     
75     /**
76      * Fired whenever an error is encountered by the tunnel.
77      * 
78      * @event
79      * @param {String} message A human-readable description of the error that
80      *                         occurred.
81      */
82     this.onerror = null;
83
84     /**
85      * Fired once for every complete Guacamole instruction received, in order.
86      * 
87      * @event
88      * @param {String} opcode The Guacamole instruction opcode.
89      * @param {Array} parameters The parameters provided for the instruction,
90      *                           if any.
91      */
92     this.oninstruction = null;
93
94 };
95
96 /**
97  * Guacamole Tunnel implemented over HTTP via XMLHttpRequest.
98  * 
99  * @constructor
100  * @augments Guacamole.Tunnel
101  * @param {String} tunnelURL The URL of the HTTP tunneling service.
102  */
103 Guacamole.HTTPTunnel = function(tunnelURL) {
104
105     /**
106      * Reference to this HTTP tunnel.
107      */
108     var tunnel = this;
109
110     var tunnel_uuid;
111
112     var TUNNEL_CONNECT = tunnelURL + "?connect";
113     var TUNNEL_READ    = tunnelURL + "?read:";
114     var TUNNEL_WRITE   = tunnelURL + "?write:";
115
116     var STATE_IDLE          = 0;
117     var STATE_CONNECTED     = 1;
118     var STATE_DISCONNECTED  = 2;
119
120     var currentState = STATE_IDLE;
121
122     var POLLING_ENABLED     = 1;
123     var POLLING_DISABLED    = 0;
124
125     // Default to polling - will be turned off automatically if not needed
126     var pollingMode = POLLING_ENABLED;
127
128     var sendingMessages = false;
129     var outputMessageBuffer = "";
130
131     this.sendMessage = function() {
132
133         // Do not attempt to send messages if not connected
134         if (currentState != STATE_CONNECTED)
135             return;
136
137         // Do not attempt to send empty messages
138         if (arguments.length == 0)
139             return;
140
141         /**
142          * Converts the given value to a length/string pair for use as an
143          * element in a Guacamole instruction.
144          * 
145          * @param value The value to convert.
146          * @return {String} The converted value. 
147          */
148         function getElement(value) {
149             var string = new String(value);
150             return string.length + "." + string; 
151         }
152
153         // Initialized message with first element
154         var message = getElement(arguments[0]);
155
156         // Append remaining elements
157         for (var i=1; i<arguments.length; i++)
158             message += "," + getElement(arguments[i]);
159
160         // Final terminator
161         message += ";";
162
163         // Add message to buffer
164         outputMessageBuffer += message;
165
166         // Send if not currently sending
167         if (!sendingMessages)
168             sendPendingMessages();
169
170     };
171
172     function sendPendingMessages() {
173
174         if (outputMessageBuffer.length > 0) {
175
176             sendingMessages = true;
177
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");
181
182             // Once response received, send next queued event.
183             message_xmlhttprequest.onreadystatechange = function() {
184                 if (message_xmlhttprequest.readyState == 4) {
185
186                     // If an error occurs during send, handle it
187                     if (message_xmlhttprequest.status != 200)
188                         handleHTTPTunnelError(message_xmlhttprequest);
189
190                     // Otherwise, continue the send loop
191                     else
192                         sendPendingMessages();
193
194                 }
195             }
196
197             message_xmlhttprequest.send(outputMessageBuffer);
198             outputMessageBuffer = ""; // Clear buffer
199
200         }
201         else
202             sendingMessages = false;
203
204     }
205
206     function getHTTPTunnelErrorMessage(xmlhttprequest) {
207
208         var status = xmlhttprequest.status;
209
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";
213
214         return "Unknown error";
215
216     }
217
218     function handleHTTPTunnelError(xmlhttprequest) {
219
220         // Get error message
221         var message = getHTTPTunnelErrorMessage(xmlhttprequest);
222
223         // Call error handler
224         if (tunnel.onerror) tunnel.onerror(message);
225
226         // Finish
227         tunnel.disconnect();
228
229     }
230
231
232     function handleResponse(xmlhttprequest) {
233
234         var interval = null;
235         var nextRequest = null;
236
237         var dataUpdateEvents = 0;
238
239         // The location of the last element's terminator
240         var elementEnd = -1;
241
242         // Where to start the next length search or the next element
243         var startIndex = 0;
244
245         // Parsed elements
246         var elements = new Array();
247
248         function parseResponse() {
249
250             // Do not handle responses if not connected
251             if (currentState != STATE_CONNECTED) {
252                 
253                 // Clean up interval if polling
254                 if (interval != null)
255                     clearInterval(interval);
256                 
257                 return;
258             }
259
260             // Do not parse response yet if not ready
261             if (xmlhttprequest.readyState < 2) return;
262
263             // Attempt to read status
264             var status;
265             try { status = xmlhttprequest.status; }
266
267             // If status could not be read, assume successful.
268             catch (e) { status = 200; }
269
270             // Start next request as soon as possible IF request was successful
271             if (nextRequest == null && status == 200)
272                 nextRequest = makeRequest();
273
274             // Parse stream when data is received and when complete.
275             if (xmlhttprequest.readyState == 3 ||
276                 xmlhttprequest.readyState == 4) {
277
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);
284                 }
285
286                 // If canceled, stop transfer
287                 if (xmlhttprequest.status == 0) {
288                     tunnel.disconnect();
289                     return;
290                 }
291
292                 // Halt on error during request
293                 else if (xmlhttprequest.status != 200) {
294                     handleHTTPTunnelError(xmlhttprequest);
295                     return;
296                 }
297
298                 // Attempt to read in-progress data
299                 var current;
300                 try { current = xmlhttprequest.responseText; }
301
302                 // Do not attempt to parse if data could not be read
303                 catch (e) { return; }
304
305                 // While search is within currently received data
306                 while (elementEnd < current.length) {
307
308                     // If we are waiting for element data
309                     if (elementEnd >= startIndex) {
310
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);
314
315                         // Add element to array
316                         elements.push(element);
317
318                         // If last element, handle instruction
319                         if (terminator == ";") {
320
321                             // Get opcode
322                             var opcode = elements.shift();
323
324                             // Call instruction handler.
325                             if (tunnel.oninstruction != null)
326                                 tunnel.oninstruction(opcode, elements);
327
328                             // Clear elements
329                             elements.length = 0;
330
331                         }
332
333                         // Start searching for length at character after
334                         // element terminator
335                         startIndex = elementEnd + 1;
336
337                     }
338
339                     // Search for end of length
340                     var lengthEnd = current.indexOf(".", startIndex);
341                     if (lengthEnd != -1) {
342
343                         // Parse length
344                         var length = parseInt(current.substring(elementEnd+1, lengthEnd));
345
346                         // If we're done parsing, handle the next response.
347                         if (length == 0) {
348
349                             // Clean up interval if polling
350                             if (interval != null)
351                                 clearInterval(interval);
352                            
353                             // Clean up object
354                             xmlhttprequest.onreadystatechange = null;
355                             xmlhttprequest.abort();
356
357                             // Start handling next request
358                             if (nextRequest)
359                                 handleResponse(nextRequest);
360
361                             // Done parsing
362                             break;
363
364                         }
365
366                         // Calculate start of element
367                         startIndex = lengthEnd + 1;
368
369                         // Calculate location of element terminator
370                         elementEnd = startIndex + length;
371
372                     }
373                     
374                     // If no period yet, continue search when more data
375                     // is received
376                     else {
377                         startIndex = current.length;
378                         break;
379                     }
380
381                 } // end parse loop
382
383             }
384
385         }
386
387         // If response polling enabled, attempt to detect if still
388         // necessary (via wrapping parseResponse())
389         if (pollingMode == POLLING_ENABLED) {
390             xmlhttprequest.onreadystatechange = function() {
391
392                 // If we receive two or more readyState==3 events,
393                 // there is no need to poll.
394                 if (xmlhttprequest.readyState == 3) {
395                     dataUpdateEvents++;
396                     if (dataUpdateEvents >= 2) {
397                         pollingMode = POLLING_DISABLED;
398                         xmlhttprequest.onreadystatechange = parseResponse;
399                     }
400                 }
401
402                 parseResponse();
403             }
404         }
405
406         // Otherwise, just parse
407         else
408             xmlhttprequest.onreadystatechange = parseResponse;
409
410         parseResponse();
411
412     }
413
414
415     function makeRequest() {
416
417         // Download self
418         var xmlhttprequest = new XMLHttpRequest();
419         xmlhttprequest.open("POST", TUNNEL_READ + tunnel_uuid);
420         xmlhttprequest.send(null);
421
422         return xmlhttprequest;
423
424     }
425
426     this.connect = function(data) {
427
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);
433
434         // If failure, throw error
435         if (connect_xmlhttprequest.status != 200) {
436             var message = getHTTPTunnelErrorMessage(connect_xmlhttprequest);
437             throw new Error(message);
438         }
439
440         // Get UUID from response
441         tunnel_uuid = connect_xmlhttprequest.responseText;
442
443         // Start reading data
444         currentState = STATE_CONNECTED;
445         handleResponse(makeRequest());
446
447     };
448
449     this.disconnect = function() {
450         currentState = STATE_DISCONNECTED;
451     };
452
453 };
454
455 Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
456
457
458 /**
459  * Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
460  * 
461  * @constructor
462  * @augments Guacamole.Tunnel
463  * @param {String} tunnelURL The URL of the WebSocket tunneling service.
464  */
465 Guacamole.WebSocketTunnel = function(tunnelURL) {
466
467     /**
468      * Reference to this WebSocket tunnel.
469      */
470     var tunnel = this;
471
472     /**
473      * The WebSocket used by this tunnel.
474      */
475     var socket = null;
476
477     /**
478      * The WebSocket protocol corresponding to the protocol used for the current
479      * location.
480      */
481     var ws_protocol = {
482         "http:":  "ws:",
483         "https:": "wss:"
484     };
485
486     var status_code = {
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."
498     };
499
500     var STATE_IDLE          = 0;
501     var STATE_CONNECTED     = 1;
502     var STATE_DISCONNECTED  = 2;
503
504     var currentState = STATE_IDLE;
505     
506     // Transform current URL to WebSocket URL
507
508     // If not already a websocket URL
509     if (   tunnelURL.substring(0, 3) != "ws:"
510         && tunnelURL.substring(0, 4) != "wss:") {
511
512         var protocol = ws_protocol[window.location.protocol];
513
514         // If absolute URL, convert to absolute WS URL
515         if (tunnelURL.substring(0, 1) == "/")
516             tunnelURL =
517                 protocol
518                 + "//" + window.location.host
519                 + tunnelURL;
520
521         // Otherwise, construct absolute from relative URL
522         else {
523
524             // Get path from pathname
525             var slash = window.location.pathname.lastIndexOf("/");
526             var path  = window.location.pathname.substring(0, slash + 1);
527
528             // Construct absolute URL
529             tunnelURL =
530                 protocol
531                 + "//" + window.location.host
532                 + path
533                 + tunnelURL;
534
535         }
536
537     }
538
539     this.sendMessage = function(elements) {
540
541         // Do not attempt to send messages if not connected
542         if (currentState != STATE_CONNECTED)
543             return;
544
545         // Do not attempt to send empty messages
546         if (arguments.length == 0)
547             return;
548
549         /**
550          * Converts the given value to a length/string pair for use as an
551          * element in a Guacamole instruction.
552          * 
553          * @param value The value to convert.
554          * @return {String} The converted value. 
555          */
556         function getElement(value) {
557             var string = new String(value);
558             return string.length + "." + string; 
559         }
560
561         // Initialized message with first element
562         var message = getElement(arguments[0]);
563
564         // Append remaining elements
565         for (var i=1; i<arguments.length; i++)
566             message += "," + getElement(arguments[i]);
567
568         // Final terminator
569         message += ";";
570
571         socket.send(message);
572
573     };
574
575     this.connect = function(data) {
576
577         // Connect socket
578         socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
579
580         socket.onopen = function(event) {
581             currentState = STATE_CONNECTED;
582         };
583
584         socket.onclose = function(event) {
585
586             // If connection closed abnormally, signal error.
587             if (event.code != 1000 && tunnel.onerror)
588                 tunnel.onerror(status_code[event.code]);
589
590         };
591         
592         socket.onerror = function(event) {
593
594             // Call error handler
595             if (tunnel.onerror) tunnel.onerror(event.data);
596
597         };
598
599         socket.onmessage = function(event) {
600
601             var message = event.data;
602             var startIndex = 0;
603             var elementEnd;
604
605             var elements = [];
606
607             do {
608
609                 // Search for end of length
610                 var lengthEnd = message.indexOf(".", startIndex);
611                 if (lengthEnd != -1) {
612
613                     // Parse length
614                     var length = parseInt(message.substring(elementEnd+1, lengthEnd));
615
616                     // Calculate start of element
617                     startIndex = lengthEnd + 1;
618
619                     // Calculate location of element terminator
620                     elementEnd = startIndex + length;
621
622                 }
623                 
624                 // If no period, incomplete instruction.
625                 else
626                     throw new Error("Incomplete instruction.");
627
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);
631
632                 // Add element to array
633                 elements.push(element);
634
635                 // If last element, handle instruction
636                 if (terminator == ";") {
637
638                     // Get opcode
639                     var opcode = elements.shift();
640
641                     // Call instruction handler.
642                     if (tunnel.oninstruction != null)
643                         tunnel.oninstruction(opcode, elements);
644
645                     // Clear elements
646                     elements.length = 0;
647
648                 }
649
650                 // Start searching for length at character after
651                 // element terminator
652                 startIndex = elementEnd + 1;
653
654             } while (startIndex < message.length);
655
656         };
657
658     };
659
660     this.disconnect = function() {
661         currentState = STATE_DISCONNECTED;
662         socket.close();
663     };
664
665 };
666
667 Guacamole.WebSocketTunnel.prototype = new Guacamole.Tunnel();
668
669
670 /**
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).
676  * 
677  * @constructor
678  * @augments Guacamole.Tunnel
679  * @param {...} tunnel_chain The tunnels to use, in order of priority.
680  */
681 Guacamole.ChainedTunnel = function(tunnel_chain) {
682
683     /**
684      * Reference to this chained tunnel.
685      */
686     var chained_tunnel = this;
687
688     /**
689      * The currently wrapped tunnel, if any.
690      */
691     var current_tunnel = null;
692
693     /**
694      * Data passed in via connect(), to be used for
695      * wrapped calls to other tunnels' connect() functions.
696      */
697     var connect_data;
698
699     /**
700      * Array of all tunnels passed to this ChainedTunnel through the
701      * constructor arguments.
702      */
703     var tunnels = [];
704
705     // Load all tunnels into array
706     for (var i=0; i<arguments.length; i++)
707         tunnels.push(arguments[i]);
708
709     /**
710      * Sets the current tunnel
711      */
712     function attach(tunnel) {
713
714         // Clear handlers of current tunnel, if any
715         if (current_tunnel) {
716             current_tunnel.onerror = null;
717             current_tunnel.oninstruction = null;
718         }
719
720         // Set own functions to tunnel's functions
721         chained_tunnel.disconnect    = tunnel.disconnect;
722         chained_tunnel.sendMessage   = tunnel.sendMessage;
723         
724         // Record current tunnel
725         current_tunnel = tunnel;
726
727         // Wrap own oninstruction within current tunnel
728         current_tunnel.oninstruction = function(opcode, elements) {
729             
730             // Invoke handler
731             chained_tunnel.oninstruction(opcode, elements);
732
733             // Use handler permanently from now on
734             current_tunnel.oninstruction = chained_tunnel.oninstruction;
735
736             // Pass through errors (without trying other tunnels)
737             current_tunnel.onerror = chained_tunnel.onerror;
738             
739         }
740
741         // Attach next tunnel on error
742         current_tunnel.onerror = function(message) {
743
744             // Get next tunnel
745             var next_tunnel = tunnels.shift();
746
747             // If there IS a next tunnel, try using it.
748             if (next_tunnel)
749                 attach(next_tunnel);
750
751             // Otherwise, call error handler
752             else if (chained_tunnel.onerror)
753                 chained_tunnel.onerror(message);
754
755         };
756
757         try {
758             
759             // Attempt connection
760             current_tunnel.connect(connect_data);
761             
762         }
763         catch (e) {
764             
765             // Call error handler of current tunnel on error
766             current_tunnel.onerror(e.message);
767             
768         }
769
770
771     }
772
773     this.connect = function(data) {
774        
775         // Remember connect data
776         connect_data = data;
777
778         // Get first tunnel
779         var next_tunnel = tunnels.shift();
780
781         // Attach first tunnel
782         if (next_tunnel)
783             attach(next_tunnel);
784
785         // If there IS no first tunnel, error
786         else if (chained_tunnel.onerror)
787             chained_tunnel.onerror("No tunnels to try.");
788
789     };
790     
791 };
792
793 Guacamole.ChainedTunnel.prototype = new Guacamole.Tunnel();