[debian-edu-commits] debian-edu/ 02/26: Imported Upstream version 0.8.3
Dominik George
natureshadow-guest at moszumanska.debian.org
Fri Oct 7 19:05:39 UTC 2016
This is an automated email from the git hooks/post-receive script.
natureshadow-guest pushed a commit to branch master
in repository guacamole-client.
commit eba7d87b784083305ee5c292245f11164c5db3b2
Author: Emmanuel Bourg <ebourg at apache.org>
Date: Tue Jan 5 23:41:38 2016 +0100
Imported Upstream version 0.8.3
---
README | 68 +
doc/guacamole-example/COPYING | 661 ++++++++
doc/guacamole-example/pom.xml | 77 +
.../net/example/DummyGuacamoleTunnelServlet.java | 68 +
.../src/main/webapp/META-INF/context.xml | 2 +
.../src/main/webapp/WEB-INF/web.xml | 43 +
doc/guacamole-example/src/main/webapp/dot.gif | Bin 0 -> 72 bytes
.../src/main/webapp/guacamole.css | 23 +
doc/guacamole-example/src/main/webapp/index.html | 98 ++
extensions/guacamole-auth-ldap/LICENSE | 470 ++++++
extensions/guacamole-auth-ldap/README | 101 ++
.../doc/examples/exampleConfigGroup.ldif | 11 +
extensions/guacamole-auth-ldap/pom.xml | 79 +
.../schema/guacConfigGroup.ldif | 9 +
.../schema/guacConfigGroup.schema | 13 +
.../guacamole-auth-ldap/src/main/assembly/dist.xml | 54 +
.../net/auth/ldap/LDAPAuthenticationProvider.java | 273 ++++
.../ldap/properties/LDAPGuacamoleProperties.java | 110 ++
extensions/guacamole-auth-mysql/README | 171 ++
.../guacamole-auth-mysql/doc/example/settings.xml | 21 +
extensions/guacamole-auth-mysql/pom.xml | 131 ++
.../schema/001-create-schema.sql | 207 +++
.../schema/002-create-admin-user.sql | 17 +
.../schema/upgrade/upgrade-pre-0.8.2.sql | 68 +
.../src/main/assembly/dist.xml | 54 +
.../net/auth/mysql/ActiveConnectionMap.java | 515 ++++++
.../net/auth/mysql/ConnectionDirectory.java | 342 ++++
.../net/auth/mysql/ConnectionGroupDirectory.java | 306 ++++
.../auth/mysql/MySQLAuthenticationProvider.java | 197 +++
.../guacamole/net/auth/mysql/MySQLConnection.java | 156 ++
.../net/auth/mysql/MySQLConnectionGroup.java | 193 +++
.../net/auth/mysql/MySQLConnectionRecord.java | 103 ++
.../guacamole/net/auth/mysql/MySQLConstants.java | 279 ++++
.../net/auth/mysql/MySQLGuacamoleSocket.java | 115 ++
.../guacamole/net/auth/mysql/MySQLUser.java | 193 +++
.../guacamole/net/auth/mysql/MySQLUserContext.java | 108 ++
.../guacamole/net/auth/mysql/UserDirectory.java | 721 +++++++++
.../guacamole/net/auth/mysql/package-info.java | 7 +
.../mysql/properties/MySQLGuacamoleProperties.java | 124 ++
.../net/auth/mysql/properties/package-info.java | 7 +
.../auth/mysql/service/ConnectionGroupService.java | 411 +++++
.../net/auth/mysql/service/ConnectionService.java | 490 ++++++
.../mysql/service/PasswordEncryptionService.java | 69 +
.../auth/mysql/service/PermissionCheckService.java | 848 ++++++++++
.../service/SHA256PasswordEncryptionService.java | 90 ++
.../net/auth/mysql/service/SaltService.java | 48 +
.../mysql/service/SecureRandomSaltService.java | 60 +
.../net/auth/mysql/service/UserService.java | 381 +++++
.../net/auth/mysql/service/package-info.java | 7 +
.../src/main/resources/generatorConfig.xml | 114 ++
extensions/guacamole-auth-noauth/README | 117 ++
.../doc/example/noauth-config.xml | 6 +
extensions/guacamole-auth-noauth/pom.xml | 72 +
.../src/main/assembly/dist.xml | 48 +
.../auth/noauth/NoAuthConfigContentHandler.java | 137 ++
.../net/auth/noauth/NoAuthenticationProvider.java | 186 +++
guacamole-common-js/ChangeLog | 61 +
guacamole-common-js/LICENSE | 470 ++++++
guacamole-common-js/README | 78 +
guacamole-common-js/doc/guacamole-osk.dtd | 32 +
guacamole-common-js/pom.xml | 87 +
guacamole-common-js/src/main/resources/audio.js | 228 +++
.../src/main/resources/guacamole.js | 1662 ++++++++++++++++++++
guacamole-common-js/src/main/resources/keyboard.js | 622 ++++++++
guacamole-common-js/src/main/resources/layer.js | 1210 ++++++++++++++
guacamole-common-js/src/main/resources/mouse.js | 836 ++++++++++
.../src/main/resources/oskeyboard.js | 653 ++++++++
guacamole-common-js/src/main/resources/tunnel.js | 832 ++++++++++
guacamole-common-js/static.xml | 13 +
guacamole-common/ChangeLog | 45 +
guacamole-common/LICENSE | 470 ++++++
guacamole-common/README | 76 +
guacamole-common/doc/Doxyfile | 1551 ++++++++++++++++++
.../doc/example/ExampleTunnelServlet.java | 49 +
guacamole-common/pom.xml | 126 ++
.../guacamole/GuacamoleClientException.java | 79 +
.../glyptodon/guacamole/GuacamoleException.java | 78 +
.../GuacamoleResourceNotFoundException.java | 79 +
.../guacamole/GuacamoleSecurityException.java | 78 +
.../guacamole/GuacamoleServerException.java | 79 +
.../glyptodon/guacamole/io/GuacamoleReader.java | 89 ++
.../glyptodon/guacamole/io/GuacamoleWriter.java | 85 +
.../guacamole/io/ReaderGuacamoleReader.java | 276 ++++
.../guacamole/io/WriterGuacamoleWriter.java | 90 ++
.../org/glyptodon/guacamole/io/package-info.java | 6 +
.../glyptodon/guacamole/net/GuacamoleSocket.java | 87 +
.../glyptodon/guacamole/net/GuacamoleTunnel.java | 195 +++
.../guacamole/net/InetGuacamoleSocket.java | 160 ++
.../guacamole/net/SSLGuacamoleSocket.java | 164 ++
.../org/glyptodon/guacamole/net/package-info.java | 7 +
.../java/org/glyptodon/guacamole/package-info.java | 8 +
.../protocol/ConfiguredGuacamoleSocket.java | 206 +++
.../protocol/GuacamoleClientInformation.java | 125 ++
.../guacamole/protocol/GuacamoleConfiguration.java | 125 ++
.../guacamole/protocol/GuacamoleInstruction.java | 127 ++
.../glyptodon/guacamole/protocol/package-info.java | 6 +
.../servlet/GuacamoleHTTPTunnelServlet.java | 452 ++++++
.../guacamole/servlet/GuacamoleSession.java | 125 ++
.../glyptodon/guacamole/servlet/package-info.java | 7 +
guacamole-ext/ChangeLog | 18 +
guacamole-ext/LICENSE | 470 ++++++
guacamole-ext/README | 79 +
guacamole-ext/pom.xml | 127 ++
.../guacamole/net/auth/AbstractConnection.java | 119 ++
.../net/auth/AbstractConnectionGroup.java | 117 ++
.../glyptodon/guacamole/net/auth/AbstractUser.java | 105 ++
.../guacamole/net/auth/AuthenticationProvider.java | 86 +
.../glyptodon/guacamole/net/auth/Connection.java | 131 ++
.../guacamole/net/auth/ConnectionGroup.java | 138 ++
.../guacamole/net/auth/ConnectionRecord.java | 83 +
.../glyptodon/guacamole/net/auth/Credentials.java | 152 ++
.../glyptodon/guacamole/net/auth/Directory.java | 129 ++
.../org/glyptodon/guacamole/net/auth/User.java | 129 ++
.../glyptodon/guacamole/net/auth/UserContext.java | 86 +
.../glyptodon/guacamole/net/auth/package-info.java | 7 +
.../auth/permission/ConnectionGroupPermission.java | 121 ++
.../net/auth/permission/ConnectionPermission.java | 121 ++
.../net/auth/permission/ObjectPermission.java | 87 +
.../guacamole/net/auth/permission/Permission.java | 57 +
.../net/auth/permission/SystemPermission.java | 120 ++
.../net/auth/permission/UserPermission.java | 116 ++
.../net/auth/permission/package-info.java | 7 +
.../auth/simple/SimpleAuthenticationProvider.java | 105 ++
.../net/auth/simple/SimpleConnection.java | 124 ++
.../net/auth/simple/SimpleConnectionDirectory.java | 138 ++
.../net/auth/simple/SimpleConnectionGroup.java | 119 ++
.../simple/SimpleConnectionGroupDirectory.java | 138 ++
.../guacamole/net/auth/simple/SimpleUser.java | 137 ++
.../net/auth/simple/SimpleUserContext.java | 115 ++
.../net/auth/simple/SimpleUserDirectory.java | 109 ++
.../guacamole/net/auth/simple/package-info.java | 8 +
.../net/event/AuthenticationFailureEvent.java | 34 +
.../net/event/AuthenticationSuccessEvent.java | 49 +
.../guacamole/net/event/CredentialEvent.java | 21 +
.../guacamole/net/event/TunnelCloseEvent.java | 66 +
.../guacamole/net/event/TunnelConnectEvent.java | 67 +
.../glyptodon/guacamole/net/event/TunnelEvent.java | 20 +
.../glyptodon/guacamole/net/event/UserEvent.java | 21 +
.../listener/AuthenticationFailureListener.java | 29 +
.../listener/AuthenticationSuccessListener.java | 34 +
.../net/event/listener/TunnelCloseListener.java | 31 +
.../net/event/listener/TunnelConnectListener.java | 32 +
.../guacamole/net/event/listener/package-info.java | 10 +
.../guacamole/net/event/package-info.java | 11 +
.../properties/BooleanGuacamoleProperty.java | 72 +
.../properties/FileGuacamoleProperty.java | 61 +
.../guacamole/properties/GuacamoleHome.java | 87 +
.../guacamole/properties/GuacamoleProperties.java | 220 +++
.../guacamole/properties/GuacamoleProperty.java | 71 +
.../properties/IntegerGuacamoleProperty.java | 67 +
.../properties/StringGuacamoleProperty.java | 54 +
.../guacamole/properties/package-info.java | 7 +
guacamole/COPYING | 661 ++++++++
guacamole/ChangeLog | 75 +
guacamole/README | 70 +
guacamole/doc/example/guacamole.properties | 26 +
guacamole/doc/example/user-mapping.xml | 36 +
guacamole/pom.xml | 139 ++
.../net/basic/BasicFileAuthenticationProvider.java | 157 ++
.../net/basic/AuthenticatingHttpServlet.java | 354 +++++
.../net/basic/BasicGuacamoleTunnelServlet.java | 379 +++++
.../glyptodon/guacamole/net/basic/BasicLogin.java | 48 +
.../glyptodon/guacamole/net/basic/BasicLogout.java | 50 +
.../guacamole/net/basic/GuacamoleClassLoader.java | 169 ++
.../guacamole/net/basic/ProtocolInfo.java | 99 ++
.../guacamole/net/basic/ProtocolParameter.java | 171 ++
.../net/basic/ProtocolParameterOption.java | 76 +
.../net/basic/WebSocketSupportLoader.java | 114 ++
.../guacamole/net/basic/auth/Authorization.java | 251 +++
.../guacamole/net/basic/auth/UserMapping.java | 59 +
.../guacamole/net/basic/auth/package-info.java | 7 +
.../connectiongroups/ConnectionGroupUtility.java | 67 +
.../net/basic/crud/connectiongroups/Create.java | 71 +
.../net/basic/crud/connectiongroups/Delete.java | 56 +
.../connectiongroups/DummyConnectionGroup.java | 39 +
.../net/basic/crud/connectiongroups/List.java | 214 +++
.../net/basic/crud/connectiongroups/Move.java | 62 +
.../net/basic/crud/connectiongroups/Update.java | 66 +
.../basic/crud/connectiongroups/package-info.java | 6 +
.../basic/crud/connections/ConnectionUtility.java | 68 +
.../net/basic/crud/connections/Create.java | 93 ++
.../net/basic/crud/connections/Delete.java | 56 +
.../basic/crud/connections/DummyConnection.java | 33 +
.../guacamole/net/basic/crud/connections/List.java | 338 ++++
.../guacamole/net/basic/crud/connections/Move.java | 62 +
.../net/basic/crud/connections/Update.java | 88 ++
.../net/basic/crud/connections/package-info.java | 6 +
.../guacamole/net/basic/crud/permissions/List.java | 220 +++
.../net/basic/crud/permissions/package-info.java | 6 +
.../guacamole/net/basic/crud/protocols/List.java | 300 ++++
.../net/basic/crud/protocols/package-info.java | 6 +
.../guacamole/net/basic/crud/users/Create.java | 61 +
.../guacamole/net/basic/crud/users/Delete.java | 54 +
.../guacamole/net/basic/crud/users/DummyUser.java | 46 +
.../guacamole/net/basic/crud/users/List.java | 102 ++
.../guacamole/net/basic/crud/users/Update.java | 307 ++++
.../net/basic/crud/users/package-info.java | 6 +
.../net/basic/event/SessionListenerCollection.java | 132 ++
.../guacamole/net/basic/event/package-info.java | 6 +
.../guacamole/net/basic/package-info.java | 7 +
.../properties/AuthenticationProviderProperty.java | 76 +
.../basic/properties/BasicGuacamoleProperties.java | 67 +
.../basic/properties/EventListenersProperty.java | 68 +
.../net/basic/properties/package-info.java | 7 +
.../guacamole/net/basic/xml/DocumentHandler.java | 196 +++
.../guacamole/net/basic/xml/TagHandler.java | 66 +
.../guacamole/net/basic/xml/package-info.java | 7 +
.../net/basic/xml/protocol/OptionTagHandler.java | 61 +
.../net/basic/xml/protocol/ParamTagHandler.java | 112 ++
.../net/basic/xml/protocol/ProtocolTagHandler.java | 77 +
.../net/basic/xml/protocol/package-info.java | 7 +
.../xml/user_mapping/AuthorizeTagHandler.java | 147 ++
.../xml/user_mapping/ConnectionTagHandler.java | 106 ++
.../basic/xml/user_mapping/ParamTagHandler.java | 70 +
.../basic/xml/user_mapping/ProtocolTagHandler.java | 66 +
.../xml/user_mapping/UserMappingTagHandler.java | 74 +
.../net/basic/xml/user_mapping/package-info.java | 6 +
.../sourceforge/guacamole/net/protocols/rdp.xml | 44 +
.../sourceforge/guacamole/net/protocols/ssh.xml | 28 +
.../sourceforge/guacamole/net/protocols/vnc.xml | 23 +
guacamole/src/main/webapp/META-INF/context.xml | 2 +
guacamole/src/main/webapp/WEB-INF/web.xml | 254 +++
guacamole/src/main/webapp/admin.xhtml | 99 ++
guacamole/src/main/webapp/agpl-3.0-standalone.html | 688 ++++++++
guacamole/src/main/webapp/client.xhtml | 151 ++
.../main/webapp/images/action-icons/guac-close.png | Bin 0 -> 704 bytes
.../webapp/images/action-icons/guac-config.png | Bin 0 -> 1063 bytes
.../webapp/images/action-icons/guac-delete.png | Bin 0 -> 611 bytes
.../webapp/images/action-icons/guac-first-page.png | Bin 0 -> 690 bytes
.../webapp/images/action-icons/guac-last-page.png | Bin 0 -> 707 bytes
.../images/action-icons/guac-monitor-add.png | Bin 0 -> 703 bytes
.../webapp/images/action-icons/guac-next-page.png | Bin 0 -> 626 bytes
.../webapp/images/action-icons/guac-prev-page.png | Bin 0 -> 648 bytes
.../webapp/images/action-icons/guac-user-add.png | Bin 0 -> 971 bytes
.../src/main/webapp/images/arrows/arrows-d.png | Bin 0 -> 3182 bytes
.../src/main/webapp/images/arrows/arrows-l.png | Bin 0 -> 2750 bytes
.../src/main/webapp/images/arrows/arrows-r.png | Bin 0 -> 2784 bytes
.../src/main/webapp/images/arrows/arrows-u.png | Bin 0 -> 3185 bytes
.../main/webapp/images/group-icons/guac-closed.png | Bin 0 -> 843 bytes
.../main/webapp/images/group-icons/guac-open.png | Bin 0 -> 717 bytes
guacamole/src/main/webapp/images/guac-mono-192.png | Bin 0 -> 6041 bytes
.../src/main/webapp/images/guacamole-logo-144.png | Bin 0 -> 9167 bytes
.../src/main/webapp/images/guacamole-logo-24.png | Bin 0 -> 1520 bytes
.../src/main/webapp/images/guacamole-logo-64.png | Bin 0 -> 5082 bytes
guacamole/src/main/webapp/images/mouse/blank.cur | Bin 0 -> 326 bytes
guacamole/src/main/webapp/images/mouse/blank.gif | Bin 0 -> 71 bytes
guacamole/src/main/webapp/images/mouse/dot.gif | Bin 0 -> 72 bytes
.../src/main/webapp/images/noguacamole-logo-24.png | Bin 0 -> 1245 bytes
guacamole/src/main/webapp/images/progress.png | Bin 0 -> 473 bytes
.../webapp/images/protocol-icons/guac-monitor.png | Bin 0 -> 691 bytes
.../webapp/images/protocol-icons/guac-plug.png | Bin 0 -> 727 bytes
.../webapp/images/protocol-icons/guac-text.png | Bin 0 -> 792 bytes
.../main/webapp/images/user-icons/guac-user.png | Bin 0 -> 1049 bytes
guacamole/src/main/webapp/index.xhtml | 149 ++
.../main/webapp/layouts/en-us-qwerty-mobile.xml | 312 ++++
guacamole/src/main/webapp/layouts/en-us-qwerty.xml | 496 ++++++
guacamole/src/main/webapp/scripts/admin-ui.js | 1472 +++++++++++++++++
guacamole/src/main/webapp/scripts/client-ui.js | 1046 ++++++++++++
guacamole/src/main/webapp/scripts/guac-ui.js | 1425 +++++++++++++++++
guacamole/src/main/webapp/scripts/history.js | 175 +++
.../src/main/webapp/scripts/lib/blob/LICENSE.md | 30 +
guacamole/src/main/webapp/scripts/lib/blob/blob.js | 178 +++
.../main/webapp/scripts/lib/filesaver/LICENSE.md | 30 +
.../main/webapp/scripts/lib/filesaver/filesaver.js | 216 +++
guacamole/src/main/webapp/scripts/root-ui.js | 516 ++++++
guacamole/src/main/webapp/scripts/service.js | 1398 ++++++++++++++++
guacamole/src/main/webapp/scripts/session.js | 107 ++
guacamole/src/main/webapp/styles/animation.css | 35 +
guacamole/src/main/webapp/styles/client.css | 420 +++++
guacamole/src/main/webapp/styles/keyboard.css | 150 ++
guacamole/src/main/webapp/styles/login.css | 350 +++++
guacamole/src/main/webapp/styles/ui.css | 611 +++++++
pom.xml | 65 +
project-assembly.xml | 24 +
274 files changed, 43001 insertions(+)
diff --git a/README b/README
new file mode 100644
index 0000000..51f03d4
--- /dev/null
+++ b/README
@@ -0,0 +1,68 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-client?
+------------------------------------------------------------
+
+guacamole-client is the superproject containing all Maven-based projects that
+make Guacamole, an HTML5 web application that provides access to your desktop
+using remote desktop protocols.
+
+guacamole-client is used to build the subprojects that make up Guacamole, and
+to provide a common central repository. Each project contained here is
+completely independent of guacamole-client and can be built separately, though
+the others may have to be built first. If all projects are built using
+guacamole-client, Maven will take care of the proper build order.
+
+
+------------------------------------------------------------
+ Compiling and installing Guacamole
+------------------------------------------------------------
+
+Guacamole is built using Maven. Building Guacamole compiles all classes and
+packages them into a deployable .war file. This .war file can be installed
+and deployed under servlet containers like Apache Tomcat or Jetty.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .war file will be
+ created in the guacamole/target/ subdirectory of the current directory.
+
+2) Copy the .war file as directed in the instructions provided with
+ your servlet container.
+
+ Apache Tomcat, Jetty, and other servlet containers have specific and
+ varying locations that .war files must be placed for the web
+ application to be deployed.
+
+ You will likely need to do this as root.
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/doc/guacamole-example/COPYING b/doc/guacamole-example/COPYING
new file mode 100644
index 0000000..dba13ed
--- /dev/null
+++ b/doc/guacamole-example/COPYING
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/doc/guacamole-example/pom.xml b/doc/guacamole-example/pom.xml
new file mode 100644
index 0000000..53cefdf
--- /dev/null
+++ b/doc/guacamole-example/pom.xml
@@ -0,0 +1,77 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-example</artifactId>
+ <packaging>war</packaging>
+ <version>0.8.0</version>
+ <name>guacamole-example</name>
+ <url>http://guac-dev.org/</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Compile using Java 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <!-- Overlay guacamole-common-js (zip) -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-war-plugin</artifactId>
+ <configuration>
+ <overlays>
+ <overlay>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common-js</artifactId>
+ <type>zip</type>
+ </overlay>
+ </overlays>
+ </configuration>
+ </plugin>
+
+ </plugins>
+
+ </build>
+
+ <dependencies>
+
+ <!-- Servlet API -->
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Main Guacamole library -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <version>0.8.0</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Guacamole JavaScript library -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common-js</artifactId>
+ <version>0.7.4</version>
+ <type>zip</type>
+ <scope>runtime</scope>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/doc/guacamole-example/src/main/java/org/glyptodon/guacamole/net/example/DummyGuacamoleTunnelServlet.java b/doc/guacamole-example/src/main/java/org/glyptodon/guacamole/net/example/DummyGuacamoleTunnelServlet.java
new file mode 100644
index 0000000..8f2a1e4
--- /dev/null
+++ b/doc/guacamole-example/src/main/java/org/glyptodon/guacamole/net/example/DummyGuacamoleTunnelServlet.java
@@ -0,0 +1,68 @@
+
+package org.glyptodon.guacamole.net.example;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+import org.glyptodon.guacamole.net.InetGuacamoleSocket;
+import org.glyptodon.guacamole.protocol.ConfiguredGuacamoleSocket;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.glyptodon.guacamole.servlet.GuacamoleHTTPTunnelServlet;
+import org.glyptodon.guacamole.servlet.GuacamoleSession;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+public class DummyGuacamoleTunnelServlet extends GuacamoleHTTPTunnelServlet {
+
+ @Override
+ protected GuacamoleTunnel doConnect(HttpServletRequest request) throws GuacamoleException {
+
+ HttpSession httpSession = request.getSession(true);
+
+ // guacd connection information
+ String hostname = "localhost";
+ int port = 4822;
+
+ // VNC connection information
+ GuacamoleConfiguration config = new GuacamoleConfiguration();
+ config.setProtocol("vnc");
+ config.setParameter("hostname", "localhost");
+ config.setParameter("port", "5901");
+ config.setParameter("password", "potato");
+
+ // Connect to guacd, proxying a connection to the VNC server above
+ GuacamoleSocket socket = new ConfiguredGuacamoleSocket(
+ new InetGuacamoleSocket(hostname, port),
+ config
+ );
+
+ // Create tunnel from now-configured socket
+ GuacamoleTunnel tunnel = new GuacamoleTunnel(socket);
+
+ // Attach tunnel
+ GuacamoleSession session = new GuacamoleSession(httpSession);
+ session.attachTunnel(tunnel);
+
+ return tunnel;
+
+ }
+
+}
diff --git a/doc/guacamole-example/src/main/webapp/META-INF/context.xml b/doc/guacamole-example/src/main/webapp/META-INF/context.xml
new file mode 100644
index 0000000..5bee3dc
--- /dev/null
+++ b/doc/guacamole-example/src/main/webapp/META-INF/context.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Context antiJARLocking="true" path=""/>
diff --git a/doc/guacamole-example/src/main/webapp/WEB-INF/web.xml b/doc/guacamole-example/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..77d4324
--- /dev/null
+++ b/doc/guacamole-example/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+
+ <!-- Basic config -->
+ <welcome-file-list>
+ <welcome-file>index.html</welcome-file>
+ </welcome-file-list>
+ <session-config>
+ <session-timeout>
+ 30
+ </session-timeout>
+ </session-config>
+
+ <!-- Guacamole Tunnel Servlet -->
+ <servlet>
+ <description>Tunnel servlet.</description>
+ <servlet-name>Tunnel</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.example.DummyGuacamoleTunnelServlet</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Tunnel</servlet-name>
+ <url-pattern>/tunnel</url-pattern>
+ </servlet-mapping>
+
+
+</web-app>
diff --git a/doc/guacamole-example/src/main/webapp/dot.gif b/doc/guacamole-example/src/main/webapp/dot.gif
new file mode 100644
index 0000000..9ac8a00
Binary files /dev/null and b/doc/guacamole-example/src/main/webapp/dot.gif differ
diff --git a/doc/guacamole-example/src/main/webapp/guacamole.css b/doc/guacamole-example/src/main/webapp/guacamole.css
new file mode 100644
index 0000000..3be9d96
--- /dev/null
+++ b/doc/guacamole-example/src/main/webapp/guacamole.css
@@ -0,0 +1,23 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+.guac-hide-cursor {
+ cursor: url('dot.gif'),default;
+}
+
diff --git a/doc/guacamole-example/src/main/webapp/index.html b/doc/guacamole-example/src/main/webapp/index.html
new file mode 100644
index 0000000..027de3e
--- /dev/null
+++ b/doc/guacamole-example/src/main/webapp/index.html
@@ -0,0 +1,98 @@
+<!DOCTYPE HTML>
+
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<html>
+
+ <head>
+ <link rel="stylesheet" type="text/css" href="guacamole.css"/>
+ <title>Guacamole (EXAMPLE)</title>
+ </head>
+
+ <body>
+
+ <!-- Display -->
+ <div id="display"></div>
+
+ <!-- Input abstractions -->
+ <script type="text/javascript"
+ src="guacamole-common-js/keyboard.js"></script>
+ <script type="text/javascript"
+ src="guacamole-common-js/mouse.js"></script>
+
+ <!-- Client core scripts -->
+ <script type="text/javascript"
+ src="guacamole-common-js/layer.js"></script>
+ <script type="text/javascript"
+ src="guacamole-common-js/tunnel.js"></script>
+ <script type="text/javascript"
+ src="guacamole-common-js/guacamole.js"></script>
+
+ <!-- Init -->
+ <script type="text/javascript"> /* <![CDATA[ */
+
+ // Get display div from document
+ var display = document.getElementById("display");
+
+ // Instantiate client, using an HTTP tunnel for communications.
+ var guac = new Guacamole.Client(
+ new Guacamole.HTTPTunnel("tunnel")
+ );
+
+ // Add client to display div
+ display.appendChild(guac.getDisplay());
+
+ // Error handler
+ guac.onerror = function(error) {
+ alert(error);
+ };
+
+ // Connect
+ guac.connect();
+
+ // Disconnect on close
+ window.onunload = function() {
+ guac.disconnect();
+ }
+
+ // Mouse
+ var mouse = new Guacamole.Mouse(guac.getDisplay());
+
+ mouse.onmousedown =
+ mouse.onmouseup =
+ mouse.onmousemove = function(mouseState) {
+ guac.sendMouseState(mouseState);
+ };
+
+ // Keyboard
+ var keyboard = new Guacamole.Keyboard(document);
+
+ keyboard.onkeydown = function (keysym) {
+ guac.sendKeyEvent(1, keysym);
+ };
+
+ keyboard.onkeyup = function (keysym) {
+ guac.sendKeyEvent(0, keysym);
+ };
+
+ /* ]]> */ </script>
+
+ </body>
+
+</html>
diff --git a/extensions/guacamole-auth-ldap/LICENSE b/extensions/guacamole-auth-ldap/LICENSE
new file mode 100644
index 0000000..7714141
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/LICENSE
@@ -0,0 +1,470 @@
+ MOZILLA PUBLIC LICENSE
+ Version 1.1
+
+ ---------------
+
+1. Definitions.
+
+ 1.0.1. "Commercial Use" means distribution or otherwise making the
+ Covered Code available to a third party.
+
+ 1.1. "Contributor" means each entity that creates or contributes to
+ the creation of Modifications.
+
+ 1.2. "Contributor Version" means the combination of the Original
+ Code, prior Modifications used by a Contributor, and the Modifications
+ made by that particular Contributor.
+
+ 1.3. "Covered Code" means the Original Code or Modifications or the
+ combination of the Original Code and Modifications, in each case
+ including portions thereof.
+
+ 1.4. "Electronic Distribution Mechanism" means a mechanism generally
+ accepted in the software development community for the electronic
+ transfer of data.
+
+ 1.5. "Executable" means Covered Code in any form other than Source
+ Code.
+
+ 1.6. "Initial Developer" means the individual or entity identified
+ as the Initial Developer in the Source Code notice required by Exhibit
+ A.
+
+ 1.7. "Larger Work" means a work which combines Covered Code or
+ portions thereof with code not governed by the terms of this License.
+
+ 1.8. "License" means this document.
+
+ 1.8.1. "Licensable" means having the right to grant, to the maximum
+ extent possible, whether at the time of the initial grant or
+ subsequently acquired, any and all of the rights conveyed herein.
+
+ 1.9. "Modifications" means any addition to or deletion from the
+ substance or structure of either the Original Code or any previous
+ Modifications. When Covered Code is released as a series of files, a
+ Modification is:
+ A. Any addition to or deletion from the contents of a file
+ containing Original Code or previous Modifications.
+
+ B. Any new file that contains any part of the Original Code or
+ previous Modifications.
+
+ 1.10. "Original Code" means Source Code of computer software code
+ which is described in the Source Code notice required by Exhibit A as
+ Original Code, and which, at the time of its release under this
+ License is not already Covered Code governed by this License.
+
+ 1.10.1. "Patent Claims" means any patent claim(s), now owned or
+ hereafter acquired, including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by grantor.
+
+ 1.11. "Source Code" means the preferred form of the Covered Code for
+ making modifications to it, including all modules it contains, plus
+ any associated interface definition files, scripts used to control
+ compilation and installation of an Executable, or source code
+ differential comparisons against either the Original Code or another
+ well known, available Covered Code of the Contributor's choice. The
+ Source Code can be in a compressed or archival form, provided the
+ appropriate decompression or de-archiving software is widely available
+ for no charge.
+
+ 1.12. "You" (or "Your") means an individual or a legal entity
+ exercising rights under, and complying with all of the terms of, this
+ License or a future version of this License issued under Section 6.1.
+ For legal entities, "You" includes any entity which controls, is
+ controlled by, or is under common control with You. For purposes of
+ this definition, "control" means (a) the power, direct or indirect,
+ to cause the direction or management of such entity, whether by
+ contract or otherwise, or (b) ownership of more than fifty percent
+ (50%) of the outstanding shares or beneficial ownership of such
+ entity.
+
+2. Source Code License.
+
+ 2.1. The Initial Developer Grant.
+ The Initial Developer hereby grants You a world-wide, royalty-free,
+ non-exclusive license, subject to third party intellectual property
+ claims:
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Initial Developer to use, reproduce,
+ modify, display, perform, sublicense and distribute the Original
+ Code (or portions thereof) with or without Modifications, and/or
+ as part of a Larger Work; and
+
+ (b) under Patents Claims infringed by the making, using or
+ selling of Original Code, to make, have made, use, practice,
+ sell, and offer for sale, and/or otherwise dispose of the
+ Original Code (or portions thereof).
+
+ (c) the licenses granted in this Section 2.1(a) and (b) are
+ effective on the date Initial Developer first distributes
+ Original Code under the terms of this License.
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is
+ granted: 1) for code that You delete from the Original Code; 2)
+ separate from the Original Code; or 3) for infringements caused
+ by: i) the modification of the Original Code or ii) the
+ combination of the Original Code with other software or devices.
+
+ 2.2. Contributor Grant.
+ Subject to third party intellectual property claims, each Contributor
+ hereby grants You a world-wide, royalty-free, non-exclusive license
+
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Contributor, to use, reproduce, modify,
+ display, perform, sublicense and distribute the Modifications
+ created by such Contributor (or portions thereof) either on an
+ unmodified basis, with other Modifications, as Covered Code
+ and/or as part of a Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using, or
+ selling of Modifications made by that Contributor either alone
+ and/or in combination with its Contributor Version (or portions
+ of such combination), to make, use, sell, offer for sale, have
+ made, and/or otherwise dispose of: 1) Modifications made by that
+ Contributor (or portions thereof); and 2) the combination of
+ Modifications made by that Contributor with its Contributor
+ Version (or portions of such combination).
+
+ (c) the licenses granted in Sections 2.2(a) and 2.2(b) are
+ effective on the date Contributor first makes Commercial Use of
+ the Covered Code.
+
+ (d) Notwithstanding Section 2.2(b) above, no patent license is
+ granted: 1) for any code that Contributor has deleted from the
+ Contributor Version; 2) separate from the Contributor Version;
+ 3) for infringements caused by: i) third party modifications of
+ Contributor Version or ii) the combination of Modifications made
+ by that Contributor with other software (except as part of the
+ Contributor Version) or other devices; or 4) under Patent Claims
+ infringed by Covered Code in the absence of Modifications made by
+ that Contributor.
+
+3. Distribution Obligations.
+
+ 3.1. Application of License.
+ The Modifications which You create or to which You contribute are
+ governed by the terms of this License, including without limitation
+ Section 2.2. The Source Code version of Covered Code may be
+ distributed only under the terms of this License or a future version
+ of this License released under Section 6.1, and You must include a
+ copy of this License with every copy of the Source Code You
+ distribute. You may not offer or impose any terms on any Source Code
+ version that alters or restricts the applicable version of this
+ License or the recipients' rights hereunder. However, You may include
+ an additional document offering the additional rights described in
+ Section 3.5.
+
+ 3.2. Availability of Source Code.
+ Any Modification which You create or to which You contribute must be
+ made available in Source Code form under the terms of this License
+ either on the same media as an Executable version or via an accepted
+ Electronic Distribution Mechanism to anyone to whom you made an
+ Executable version available; and if made available via Electronic
+ Distribution Mechanism, must remain available for at least twelve (12)
+ months after the date it initially became available, or at least six
+ (6) months after a subsequent version of that particular Modification
+ has been made available to such recipients. You are responsible for
+ ensuring that the Source Code version remains available even if the
+ Electronic Distribution Mechanism is maintained by a third party.
+
+ 3.3. Description of Modifications.
+ You must cause all Covered Code to which You contribute to contain a
+ file documenting the changes You made to create that Covered Code and
+ the date of any change. You must include a prominent statement that
+ the Modification is derived, directly or indirectly, from Original
+ Code provided by the Initial Developer and including the name of the
+ Initial Developer in (a) the Source Code, and (b) in any notice in an
+ Executable version or related documentation in which You describe the
+ origin or ownership of the Covered Code.
+
+ 3.4. Intellectual Property Matters
+ (a) Third Party Claims.
+ If Contributor has knowledge that a license under a third party's
+ intellectual property rights is required to exercise the rights
+ granted by such Contributor under Sections 2.1 or 2.2,
+ Contributor must include a text file with the Source Code
+ distribution titled "LEGAL" which describes the claim and the
+ party making the claim in sufficient detail that a recipient will
+ know whom to contact. If Contributor obtains such knowledge after
+ the Modification is made available as described in Section 3.2,
+ Contributor shall promptly modify the LEGAL file in all copies
+ Contributor makes available thereafter and shall take other steps
+ (such as notifying appropriate mailing lists or newsgroups)
+ reasonably calculated to inform those who received the Covered
+ Code that new knowledge has been obtained.
+
+ (b) Contributor APIs.
+ If Contributor's Modifications include an application programming
+ interface and Contributor has knowledge of patent licenses which
+ are reasonably necessary to implement that API, Contributor must
+ also include this information in the LEGAL file.
+
+ (c) Representations.
+ Contributor represents that, except as disclosed pursuant to
+ Section 3.4(a) above, Contributor believes that Contributor's
+ Modifications are Contributor's original creation(s) and/or
+ Contributor has sufficient rights to grant the rights conveyed by
+ this License.
+
+ 3.5. Required Notices.
+ You must duplicate the notice in Exhibit A in each file of the Source
+ Code. If it is not possible to put such notice in a particular Source
+ Code file due to its structure, then You must include such notice in a
+ location (such as a relevant directory) where a user would be likely
+ to look for such a notice. If You created one or more Modification(s)
+ You may add your name as a Contributor to the notice described in
+ Exhibit A. You must also duplicate this License in any documentation
+ for the Source Code where You describe recipients' rights or ownership
+ rights relating to Covered Code. You may choose to offer, and to
+ charge a fee for, warranty, support, indemnity or liability
+ obligations to one or more recipients of Covered Code. However, You
+ may do so only on Your own behalf, and not on behalf of the Initial
+ Developer or any Contributor. You must make it absolutely clear than
+ any such warranty, support, indemnity or liability obligation is
+ offered by You alone, and You hereby agree to indemnify the Initial
+ Developer and every Contributor for any liability incurred by the
+ Initial Developer or such Contributor as a result of warranty,
+ support, indemnity or liability terms You offer.
+
+ 3.6. Distribution of Executable Versions.
+ You may distribute Covered Code in Executable form only if the
+ requirements of Section 3.1-3.5 have been met for that Covered Code,
+ and if You include a notice stating that the Source Code version of
+ the Covered Code is available under the terms of this License,
+ including a description of how and where You have fulfilled the
+ obligations of Section 3.2. The notice must be conspicuously included
+ in any notice in an Executable version, related documentation or
+ collateral in which You describe recipients' rights relating to the
+ Covered Code. You may distribute the Executable version of Covered
+ Code or ownership rights under a license of Your choice, which may
+ contain terms different from this License, provided that You are in
+ compliance with the terms of this License and that the license for the
+ Executable version does not attempt to limit or alter the recipient's
+ rights in the Source Code version from the rights set forth in this
+ License. If You distribute the Executable version under a different
+ license You must make it absolutely clear that any terms which differ
+ from this License are offered by You alone, not by the Initial
+ Developer or any Contributor. You hereby agree to indemnify the
+ Initial Developer and every Contributor for any liability incurred by
+ the Initial Developer or such Contributor as a result of any such
+ terms You offer.
+
+ 3.7. Larger Works.
+ You may create a Larger Work by combining Covered Code with other code
+ not governed by the terms of this License and distribute the Larger
+ Work as a single product. In such a case, You must make sure the
+ requirements of this License are fulfilled for the Covered Code.
+
+4. Inability to Comply Due to Statute or Regulation.
+
+ If it is impossible for You to comply with any of the terms of this
+ License with respect to some or all of the Covered Code due to
+ statute, judicial order, or regulation then You must: (a) comply with
+ the terms of this License to the maximum extent possible; and (b)
+ describe the limitations and the code they affect. Such description
+ must be included in the LEGAL file described in Section 3.4 and must
+ be included with all distributions of the Source Code. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Application of this License.
+
+ This License applies to code to which the Initial Developer has
+ attached the notice in Exhibit A and to related Covered Code.
+
+6. Versions of the License.
+
+ 6.1. New Versions.
+ Netscape Communications Corporation ("Netscape") may publish revised
+ and/or new versions of the License from time to time. Each version
+ will be given a distinguishing version number.
+
+ 6.2. Effect of New Versions.
+ Once Covered Code has been published under a particular version of the
+ License, You may always continue to use it under the terms of that
+ version. You may also choose to use such Covered Code under the terms
+ of any subsequent version of the License published by Netscape. No one
+ other than Netscape has the right to modify the terms applicable to
+ Covered Code created under this License.
+
+ 6.3. Derivative Works.
+ If You create or use a modified version of this License (which you may
+ only do in order to apply it to code which is not already Covered Code
+ governed by this License), You must (a) rename Your license so that
+ the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
+ "MPL", "NPL" or any confusingly similar phrase do not appear in your
+ license (except to note that your license differs from this License)
+ and (b) otherwise make it clear that Your version of the license
+ contains terms which differ from the Mozilla Public License and
+ Netscape Public License. (Filling in the name of the Initial
+ Developer, Original Code or Contributor in the notice described in
+ Exhibit A shall not of themselves be deemed to be modifications of
+ this License.)
+
+7. DISCLAIMER OF WARRANTY.
+
+ COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+ WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
+ DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
+ THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
+ IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
+ YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
+ COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
+ OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
+ ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+8. TERMINATION.
+
+ 8.1. This License and the rights granted hereunder will terminate
+ automatically if You fail to comply with terms herein and fail to cure
+ such breach within 30 days of becoming aware of the breach. All
+ sublicenses to the Covered Code which are properly granted shall
+ survive any termination of this License. Provisions which, by their
+ nature, must remain in effect beyond the termination of this License
+ shall survive.
+
+ 8.2. If You initiate litigation by asserting a patent infringement
+ claim (excluding declatory judgment actions) against Initial Developer
+ or a Contributor (the Initial Developer or Contributor against whom
+ You file such action is referred to as "Participant") alleging that:
+
+ (a) such Participant's Contributor Version directly or indirectly
+ infringes any patent, then any and all rights granted by such
+ Participant to You under Sections 2.1 and/or 2.2 of this License
+ shall, upon 60 days notice from Participant terminate prospectively,
+ unless if within 60 days after receipt of notice You either: (i)
+ agree in writing to pay Participant a mutually agreeable reasonable
+ royalty for Your past and future use of Modifications made by such
+ Participant, or (ii) withdraw Your litigation claim with respect to
+ the Contributor Version against such Participant. If within 60 days
+ of notice, a reasonable royalty and payment arrangement are not
+ mutually agreed upon in writing by the parties or the litigation claim
+ is not withdrawn, the rights granted by Participant to You under
+ Sections 2.1 and/or 2.2 automatically terminate at the expiration of
+ the 60 day notice period specified above.
+
+ (b) any software, hardware, or device, other than such Participant's
+ Contributor Version, directly or indirectly infringes any patent, then
+ any rights granted to You by such Participant under Sections 2.1(b)
+ and 2.2(b) are revoked effective as of the date You first made, used,
+ sold, distributed, or had made, Modifications made by that
+ Participant.
+
+ 8.3. If You assert a patent infringement claim against Participant
+ alleging that such Participant's Contributor Version directly or
+ indirectly infringes any patent where such claim is resolved (such as
+ by license or settlement) prior to the initiation of patent
+ infringement litigation, then the reasonable value of the licenses
+ granted by such Participant under Sections 2.1 or 2.2 shall be taken
+ into account in determining the amount or value of any payment or
+ license.
+
+ 8.4. In the event of termination under Sections 8.1 or 8.2 above,
+ all end user license agreements (excluding distributors and resellers)
+ which have been validly granted by You or any distributor hereunder
+ prior to termination shall survive termination.
+
+9. LIMITATION OF LIABILITY.
+
+ UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
+ (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
+ DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
+ OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
+ ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
+ CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
+ WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
+ COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
+ INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
+ LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
+ RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
+ PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
+ EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
+ THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+10. U.S. GOVERNMENT END USERS.
+
+ The Covered Code is a "commercial item," as that term is defined in
+ 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
+ software" and "commercial computer software documentation," as such
+ terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
+ C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
+ all U.S. Government End Users acquire Covered Code with only those
+ rights set forth herein.
+
+11. MISCELLANEOUS.
+
+ This License represents the complete agreement concerning subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. This License shall be governed by
+ California law provisions (except to the extent applicable law, if
+ any, provides otherwise), excluding its conflict-of-law provisions.
+ With respect to disputes in which at least one party is a citizen of,
+ or an entity chartered or registered to do business in the United
+ States of America, any litigation relating to this License shall be
+ subject to the jurisdiction of the Federal Courts of the Northern
+ District of California, with venue lying in Santa Clara County,
+ California, with the losing party responsible for costs, including
+ without limitation, court costs and reasonable attorneys' fees and
+ expenses. The application of the United Nations Convention on
+ Contracts for the International Sale of Goods is expressly excluded.
+ Any law or regulation which provides that the language of a contract
+ shall be construed against the drafter shall not apply to this
+ License.
+
+12. RESPONSIBILITY FOR CLAIMS.
+
+ As between Initial Developer and the Contributors, each party is
+ responsible for claims and damages arising, directly or indirectly,
+ out of its utilization of rights under this License and You agree to
+ work with Initial Developer and Contributors to distribute such
+ responsibility on an equitable basis. Nothing herein is intended or
+ shall be deemed to constitute any admission of liability.
+
+13. MULTIPLE-LICENSED CODE.
+
+ Initial Developer may designate portions of the Covered Code as
+ "Multiple-Licensed". "Multiple-Licensed" means that the Initial
+ Developer permits you to utilize portions of the Covered Code under
+ Your choice of the NPL or the alternative licenses, if any, specified
+ by the Initial Developer in the file described in Exhibit A.
+
+EXHIBIT A -Mozilla Public License.
+
+ ``The contents of this file are subject to the Mozilla Public License
+ Version 1.1 (the "License"); you may not use this file except in
+ compliance with the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS"
+ basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ License for the specific language governing rights and limitations
+ under the License.
+
+ The Original Code is ______________________________________.
+
+ The Initial Developer of the Original Code is ________________________.
+ Portions created by ______________________ are Copyright (C) ______
+ _______________________. All Rights Reserved.
+
+ Contributor(s): ______________________________________.
+
+ Alternatively, the contents of this file may be used under the terms
+ of the _____ license (the "[___] License"), in which case the
+ provisions of [______] License are applicable instead of those
+ above. If you wish to allow use of your version of this file only
+ under the terms of the [____] License and not to allow others to use
+ your version of this file under the MPL, indicate your decision by
+ deleting the provisions above and replace them with the notice and
+ other provisions required by the [___] License. If you do not delete
+ the provisions above, a recipient may use your version of this file
+ under either the MPL or the [___] License."
+
+ [NOTE: The text of this Exhibit A may differ slightly from the text of
+ the notices in the Source Code files of the Original Code. You should
+ use the text of this Exhibit A rather than the text found in the
+ Original Code Source Code for Your Modifications.]
+
diff --git a/extensions/guacamole-auth-ldap/README b/extensions/guacamole-auth-ldap/README
new file mode 100644
index 0000000..223cbf7
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/README
@@ -0,0 +1,101 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-auth-ldap?
+------------------------------------------------------------
+
+guacamole-auth-ldap is a Java library for use with the Guacamole web
+application to provide LDAP based authentication.
+
+guacamole-auth-ldap provides an authentication provider which can be
+set in guacamole.properties to allow LDAP authentication of Guacamole
+users. Additional properties are required to configure the LDAP
+connection and search parameters.
+
+Schema files are provided to create the required object classes in your
+LDAP directory.
+
+
+------------------------------------------------------------
+ Compiling and installing guacamole-auth-ldap
+------------------------------------------------------------
+
+guacamole-auth-ldap is built using Maven. Building guacamole-auth-ldap
+compiles all classes and packages them into a redistributable .jar file. This
+.jar file can be installed in the library directory configured in
+guacamole.properties such that the authentication provider is available.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .jar file will be
+ created in the target/ subdirectory of the current directory.
+
+2) Copy the .jar file into the library directory specified in your
+ guacamole.properties
+
+ You will likely need to do this as root.
+
+ If you do not have a library directory configured in your
+ guacamole.properties, you will need to specify one. The directory
+ is specified using the "lib-directory" property.
+
+3) Set up your LDAP server to authenticate Guacamole users
+
+ Schema files are provided in the doc directory for creating
+ the "guacConfig" object class required.
+
+ You must add guacConfig objects to your LDAP directory. Each
+ guacConfig represents a connection configuration, which is made
+ up of a protocol and any number of protocol-specific parameters.
+
+4) Configure guacamole.properties for LDAP
+
+ There are additional properties required by the LDAP authentication
+ provider which must be added/changed in your guacamole.properties:
+
+ # Use LDAP authentication
+ auth-provider: net.sourceforge.guacamole.net.auth.ldap.LDAPAuthenticationProvider
+
+ # Configuration for LDAP connection
+ ldap-hostname: LDAP_SERVER_HOSTNAME
+ ldap-port: 389
+
+ # The attribute which uniquely identifies users
+ ldap-username-attribute: uid
+
+ # The base DN which, when appended to the user identifier attribute,
+ # produces the full DN of the user being authenticated.
+ ldap-user-base-dn: ou=people,dc=example,dc=net
+
+ # The base DN within which all guacConfig objects can be found.
+ ldap-config-base-dn: dc=example,dc=net
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/extensions/guacamole-auth-ldap/doc/examples/exampleConfigGroup.ldif b/extensions/guacamole-auth-ldap/doc/examples/exampleConfigGroup.ldif
new file mode 100644
index 0000000..d1508cd
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/doc/examples/exampleConfigGroup.ldif
@@ -0,0 +1,11 @@
+
+dn: cn=Example Config,dc=guac-dev,dc=org
+objectClass: guacConfigGroup
+objectClass: groupOfNames
+cn: Example Config
+guacConfigProtocol: vnc
+guacConfigParameter: hostname=localhost
+guacConfigParameter: port=5900
+guacConfigParameter: password=secret
+member: cn=user1,dc=example,dc=com
+member: cn=user2,dc=example,dc=com
diff --git a/extensions/guacamole-auth-ldap/pom.xml b/extensions/guacamole-auth-ldap/pom.xml
new file mode 100644
index 0000000..046c895
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/pom.xml
@@ -0,0 +1,79 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-auth-ldap</artifactId>
+ <packaging>jar</packaging>
+ <version>0.8.0</version>
+ <name>guacamole-auth-ldap</name>
+ <url>http://guac-dev.org/</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Written for 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <!-- Assembly plugin - for easy distribution -->
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2-beta-5</version>
+ <configuration>
+ <finalName>${project.artifactId}-${project.version}</finalName>
+ <appendAssemblyId>false</appendAssemblyId>
+ <descriptors>
+ <descriptor>src/main/assembly/dist.xml</descriptor>
+ </descriptors>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-dist-archive</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <!-- Guacamole Java API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+
+ <!-- Guacamole Extension API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-ext</artifactId>
+ <version>0.8.1</version>
+ </dependency>
+
+ <!-- JLDAP -->
+ <dependency>
+ <groupId>com.novell.ldap</groupId>
+ <artifactId>jldap</artifactId>
+ <version>4.3</version>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/extensions/guacamole-auth-ldap/schema/guacConfigGroup.ldif b/extensions/guacamole-auth-ldap/schema/guacConfigGroup.ldif
new file mode 100644
index 0000000..4cac36c
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/schema/guacConfigGroup.ldif
@@ -0,0 +1,9 @@
+dn: cn=guacConfigGroup,cn=schema,cn=config
+objectClass: olcSchemaConfig
+cn: guacConfigGroup
+olcAttributeTypes: {0}( 1.3.6.1.4.1.38971.1.1.1 NAME 'guacConfigProtocol' SYNTAX 1.3.6.1.4.1.1466
+ .115.121.1.15 )
+olcAttributeTypes: {1}( 1.3.6.1.4.1.38971.1.1.2 NAME 'guacConfigParameter' SYNTAX 1.3.6.1.4.1.146
+ 6.115.121.1.15 )
+olcObjectClasses: {0}( 1.3.6.1.4.1.38971.1.2.1 NAME 'guacConfigGroup' DESC 'Guacamole config
+ uration group' SUP groupOfNames MUST guacConfigProtocol MAY guacConfigParameter )
diff --git a/extensions/guacamole-auth-ldap/schema/guacConfigGroup.schema b/extensions/guacamole-auth-ldap/schema/guacConfigGroup.schema
new file mode 100644
index 0000000..33542f9
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/schema/guacConfigGroup.schema
@@ -0,0 +1,13 @@
+
+attributetype ( 1.3.6.1.4.1.38971.1.1.1 NAME 'guacConfigProtocol'
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
+
+attributetype ( 1.3.6.1.4.1.38971.1.1.2 NAME 'guacConfigParameter'
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
+
+objectClass ( 1.3.6.1.4.1.38971.1.2.1 NAME 'guacConfigGroup'
+ DESC 'Guacamole configuration group'
+ SUP groupOfNames
+ MUST protocol
+ MAY parameter )
+
diff --git a/extensions/guacamole-auth-ldap/src/main/assembly/dist.xml b/extensions/guacamole-auth-ldap/src/main/assembly/dist.xml
new file mode 100644
index 0000000..0628ad6
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/src/main/assembly/dist.xml
@@ -0,0 +1,54 @@
+<assembly
+ xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+
+ <id>dist</id>
+ <baseDirectory>${project.artifactId}-${project.version}</baseDirectory>
+
+ <!-- Output tar.gz -->
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+
+ <!-- Include docs and schema -->
+ <fileSets>
+
+ <!-- Include docs -->
+ <fileSet>
+ <outputDirectory>/</outputDirectory>
+ <directory>doc</directory>
+ </fileSet>
+
+ <!-- Include schema -->
+ <fileSet>
+ <outputDirectory>/schema</outputDirectory>
+ <directory>schema</directory>
+ </fileSet>
+
+ </fileSets>
+
+ <!-- Include self and all dependencies except guacamole-common
+ and guacamole-ext -->
+ <dependencySets>
+ <dependencySet>
+
+ <outputDirectory>/lib</outputDirectory>
+ <scope>runtime</scope>
+ <unpack>false</unpack>
+ <useProjectArtifact>true</useProjectArtifact>
+ <useTransitiveFiltering>true</useTransitiveFiltering>
+
+ <excludes>
+
+ <!-- Do not include guacamole-common -->
+ <exclude>org.glyptodon.guacamole:guacamole-common</exclude>
+
+ <!-- Do not include guacamole-ext -->
+ <exclude>org.glyptodon.guacamole:guacamole-ext</exclude>
+
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+
+</assembly>
diff --git a/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java b/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java
new file mode 100644
index 0000000..5fe6ef9
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java
@@ -0,0 +1,273 @@
+
+package net.sourceforge.guacamole.net.auth.ldap;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-ldap.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.novell.ldap.LDAPAttribute;
+import com.novell.ldap.LDAPConnection;
+import com.novell.ldap.LDAPEntry;
+import com.novell.ldap.LDAPException;
+import com.novell.ldap.LDAPSearchResults;
+import java.io.UnsupportedEncodingException;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.TreeMap;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import net.sourceforge.guacamole.net.auth.ldap.properties.LDAPGuacamoleProperties;
+import org.glyptodon.guacamole.net.auth.simple.SimpleAuthenticationProvider;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Allows users to be authenticated against an LDAP server. Each user may have
+ * any number of authorized configurations. Authorized configurations may be
+ * shared.
+ *
+ * @author Michael Jumper
+ */
+public class LDAPAuthenticationProvider extends SimpleAuthenticationProvider {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(LDAPAuthenticationProvider.class);
+
+ // Courtesy of OWASP: https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java
+ private static String escapeLDAPSearchFilter(String filter) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < filter.length(); i++) {
+ char curChar = filter.charAt(i);
+ switch (curChar) {
+ case '\\':
+ sb.append("\\5c");
+ break;
+ case '*':
+ sb.append("\\2a");
+ break;
+ case '(':
+ sb.append("\\28");
+ break;
+ case ')':
+ sb.append("\\29");
+ break;
+ case '\u0000':
+ sb.append("\\00");
+ break;
+ default:
+ sb.append(curChar);
+ }
+ }
+ return sb.toString();
+ }
+
+ // Courtesy of OWASP: https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java
+ private static String escapeDN(String name) {
+ StringBuilder sb = new StringBuilder();
+ if ((name.length() > 0) && ((name.charAt(0) == ' ') || (name.charAt(0) == '#'))) {
+ sb.append('\\'); // add the leading backslash if needed
+ }
+ for (int i = 0; i < name.length(); i++) {
+ char curChar = name.charAt(i);
+ switch (curChar) {
+ case '\\':
+ sb.append("\\\\");
+ break;
+ case ',':
+ sb.append("\\,");
+ break;
+ case '+':
+ sb.append("\\+");
+ break;
+ case '"':
+ sb.append("\\\"");
+ break;
+ case '<':
+ sb.append("\\<");
+ break;
+ case '>':
+ sb.append("\\>");
+ break;
+ case ';':
+ sb.append("\\;");
+ break;
+ default:
+ sb.append(curChar);
+ }
+ }
+ if ((name.length() > 1) && (name.charAt(name.length() - 1) == ' ')) {
+ sb.insert(sb.length() - 1, '\\'); // add the trailing backslash if needed
+ }
+ return sb.toString();
+ }
+
+
+ @Override
+ public Map<String, GuacamoleConfiguration> getAuthorizedConfigurations(Credentials credentials) throws GuacamoleException {
+
+ try {
+
+ // Require username
+ if (credentials.getUsername() == null) {
+ logger.info("Anonymous bind is not currently allowed by the LDAP authentication provider.");
+ return null;
+ }
+
+ // Require password, and do not allow anonymous binding
+ if (credentials.getPassword() == null
+ || credentials.getPassword().length() == 0) {
+ logger.info("Anonymous bind is not currently allowed by the LDAP authentication provider.");
+ return null;
+ }
+
+ // Connect to LDAP server
+ LDAPConnection ldapConnection = new LDAPConnection();
+ ldapConnection.connect(
+ GuacamoleProperties.getRequiredProperty(LDAPGuacamoleProperties.LDAP_HOSTNAME),
+ GuacamoleProperties.getRequiredProperty(LDAPGuacamoleProperties.LDAP_PORT)
+ );
+
+ // Get username attribute
+ String username_attribute = GuacamoleProperties.getRequiredProperty(
+ LDAPGuacamoleProperties.LDAP_USERNAME_ATTRIBUTE
+ );
+
+ // Get user base DN
+ String user_base_dn = GuacamoleProperties.getRequiredProperty(
+ LDAPGuacamoleProperties.LDAP_USER_BASE_DN
+ );
+
+ // Construct user DN
+ String user_dn =
+ escapeDN(username_attribute) + "=" + escapeDN(credentials.getUsername())
+ + "," + user_base_dn;
+
+ // Bind as user
+ try {
+ ldapConnection.bind(
+ LDAPConnection.LDAP_V3,
+ user_dn,
+ credentials.getPassword().getBytes("UTF-8")
+ );
+ }
+ catch (UnsupportedEncodingException e) {
+ throw new GuacamoleException(e);
+ }
+
+ // Get config base DN
+ String config_base_dn = GuacamoleProperties.getRequiredProperty(
+ LDAPGuacamoleProperties.LDAP_CONFIG_BASE_DN
+ );
+
+ // Find all guac configs for this user
+ LDAPSearchResults results = ldapConnection.search(
+ config_base_dn,
+ LDAPConnection.SCOPE_SUB,
+ "(&(objectClass=guacConfigGroup)(member=" + escapeLDAPSearchFilter(user_dn) + "))",
+ null,
+ false
+ );
+
+ // Add all configs
+ Map<String, GuacamoleConfiguration> configs = new TreeMap<String, GuacamoleConfiguration>();
+ while (results.hasMore()) {
+
+ LDAPEntry entry = results.next();
+
+ // New empty configuration
+ GuacamoleConfiguration config = new GuacamoleConfiguration();
+
+ // Get CN
+ LDAPAttribute cn = entry.getAttribute("cn");
+ if (cn == null)
+ throw new GuacamoleException("guacConfigGroup without cn");
+
+ // Get protocol
+ LDAPAttribute protocol = entry.getAttribute("guacConfigProtocol");
+ if (protocol == null)
+ throw new GuacamoleException("guacConfigGroup without guacConfigProtocol");
+
+ // Set protocol
+ config.setProtocol(protocol.getStringValue());
+
+ // Get parameters, if any
+ LDAPAttribute parameterAttribute = entry.getAttribute("guacConfigParameter");
+ if (parameterAttribute != null) {
+
+ // For each parameter
+ Enumeration<String> parameters = parameterAttribute.getStringValues();
+ while (parameters.hasMoreElements()) {
+
+ String parameter = parameters.nextElement();
+
+ // Parse parameter
+ int equals = parameter.indexOf('=');
+ if (equals != -1) {
+
+ // Parse name
+ String name = parameter.substring(0, equals);
+ String value = parameter.substring(equals+1);
+
+ config.setParameter(name, value);
+
+ }
+
+ }
+
+ }
+
+ // Store config by CN
+ configs.put(cn.getStringValue(), config);
+
+ }
+
+ // Disconnect
+ ldapConnection.disconnect();
+ return configs;
+
+ }
+ catch (LDAPException e) {
+ throw new GuacamoleException(e);
+ }
+
+
+ }
+
+}
+
diff --git a/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/properties/LDAPGuacamoleProperties.java b/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/properties/LDAPGuacamoleProperties.java
new file mode 100644
index 0000000..a523da8
--- /dev/null
+++ b/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/properties/LDAPGuacamoleProperties.java
@@ -0,0 +1,110 @@
+
+package net.sourceforge.guacamole.net.auth.ldap.properties;
+
+import org.glyptodon.guacamole.properties.IntegerGuacamoleProperty;
+import org.glyptodon.guacamole.properties.StringGuacamoleProperty;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-ldap.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Provides properties required for use of the LDAP authentication provider.
+ * These properties will be read from guacamole.properties when the LDAP
+ * authentication provider is used.
+ *
+ * @author Michael Jumper
+ */
+public class LDAPGuacamoleProperties {
+
+ /**
+ * This class should not be instantiated.
+ */
+ private LDAPGuacamoleProperties() {}
+
+ /**
+ * The base DN to search for Guacamole configurations.
+ */
+ public static final StringGuacamoleProperty LDAP_CONFIG_BASE_DN = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "ldap-config-base-dn"; }
+
+ };
+
+ /**
+ * The base DN of users. All users must be direct children of this DN,
+ * varying only by LDAP_USERNAME_ATTRIBUTE.
+ */
+ public static final StringGuacamoleProperty LDAP_USER_BASE_DN = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "ldap-user-base-dn"; }
+
+ };
+
+ /**
+ * The attribute which identifies users. This attribute must be part of
+ * each user's DN such that the concatenation of this attribute and
+ * LDAP_USER_BASE_DN equals the users full DN.
+ */
+ public static final StringGuacamoleProperty LDAP_USERNAME_ATTRIBUTE = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "ldap-username-attribute"; }
+
+ };
+
+ /**
+ * The port on the LDAP server to connect to when authenticating users.
+ */
+ public static final IntegerGuacamoleProperty LDAP_PORT = new IntegerGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "ldap-port"; }
+
+ };
+
+ /**
+ * The hostname of the LDAP server to connect to when authenticating users.
+ */
+ public static final StringGuacamoleProperty LDAP_HOSTNAME = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "ldap-hostname"; }
+
+ };
+
+}
diff --git a/extensions/guacamole-auth-mysql/README b/extensions/guacamole-auth-mysql/README
new file mode 100644
index 0000000..5543c12
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/README
@@ -0,0 +1,171 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-auth-mysql?
+------------------------------------------------------------
+
+guacamole-auth-ldap is a Java library for use with the Guacamole web
+application to provide MySQL based authentication.
+
+guacamole-auth-mysql provides an authentication provider which can be
+set in guacamole.properties to allow MySQL authentication of Guacamole
+users. Additional properties are required to configure the mysql
+connection parameters.
+
+A schema file are provided to create the required tables in your
+mysql database.
+
+
+------------------------------------------------------------
+ Compiling and installing guacamole-auth-mysql
+------------------------------------------------------------
+
+guacamole-auth-mysql is built using Maven. Building guacamole-auth-mysql
+compiles all classes and packages them into a redistributable .jar file. This
+.jar file can be installed in the library directory configured in
+guacamole.properties such that the authentication provider is available.
+
+1) Set up a MySQL database with the Guacamole schema.
+
+ When guacamole-auth-mysql is compiling, it needs to generate source
+ based on a database schema. Because the source generator uses a
+ connection to an actual database to do this, you must have a MySQL
+ database running with the Guacamole schema set up.
+
+ First, create a database. For the sake of these instructions, we will
+ call the database "guacamole", and will run all scripts as the root user:
+
+ $ mysql -u root -p
+ Enter password:
+ mysql> CREATE DATABASE guacamole;
+ Query OK, 1 row affected (0.00 sec)
+
+ mysql> exit
+ Bye
+
+ The schema files are in the schema/ subdirectory of the source. If run
+ in order, they will create the schema and a default user:
+
+ $ cat schema/*.sql | mysql -u root -p guacamole
+
+2) Set up your ~/.m2/settings.xml
+
+ Once the database is set up, Maven will need to have the credentials
+ required to connect to it and query the schema. This information is
+ specified in properties inside your ~/.m2/settings.xml file. If this
+ file does not exist yet, simply create it.
+
+ For ease of compilation, we've included an example settings.xml
+ defining the required properties in doc/example/settings.xml. You can
+ simply copy this file into ~/.m2 and edit as necessary.
+
+ If you wish to write the file yourself, the file should look like this in
+ general:
+
+ <settings>
+ <profiles>
+ ...profiles...
+ </profiles>
+ </settings>
+
+ We need to add a profile which defines the required properties by
+ placing a section like the following within the "profiles" section of your
+ settings.xml:
+
+ <profile>
+ <id>guacamole-mybatis</id>
+ <properties>
+ <guacamole.database.catalog>DATABASE</guacamole.database.catalog>
+ <guacamole.database.user>USERNAME</guacamole.database.user>
+ <guacamole.database.password>PASSWORD</guacamole.database.password>
+ </properties>
+ </profile>
+
+ Obviously, the DATABASE, USERNAME, and PASSWORD placeholders above must
+ be replaced with the appropriate values for your system.
+
+ Finally, to make the profile available to the build, it must be activated.
+ Place a section like the following at the bottom of your settings.xml,
+ right after the profiles section:
+
+ <activeProfiles>
+ <activeProfile>guacamole-mybatis</activeProfile>
+ </activeProfiles>
+
+ Maven's documentation has more details on writing the settings.xml file
+ if you have different needs or the above directions are not clear.
+
+3) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .jar file will be
+ created in the target/ subdirectory of the current directory.
+
+ If this process fails, check the build errors, and verify that the
+ contents of your settings.xml file is correct.
+
+4) Extract the .tar.gz file now present in the target/ directory, and
+ place the .jar files in the extracted lib/ subdirectory in the library
+ directory specified in guacamole.properties.
+
+ You will likely need to do this as root.
+
+ If you do not have a library directory configured in your
+ guacamole.properties, you will need to specify one. The directory
+ is specified using the "lib-directory" property.
+
+5) Set up your MySQL database to authenticate Guacamole users
+
+ A schema file is provided in the schema directory for creating
+ the guacamole authentication tables in your MySQL database.
+
+ Additionally, a script is provided to create a default admin user
+ with username 'guacadmin' and password 'guacadmin'. This user can
+ be used to set up any other connections and users.
+
+6) Configure guacamole.properties for MySQL
+
+ There are additional properties required by the MySQL JDBC driver
+ which must be added/changed in your guacamole.properties:
+
+ # Configuration for MySQL connection
+ mysql-hostname: mysql.host.name
+ mysql-port: 3306
+ mysql-database: guacamole.database.name
+ mysql-username: user
+ mysql-password: pass
+
+ Optionally, the authentication provider can be configured
+ not to allow multiple users to use the same connection
+ at the same time:
+
+ mysql-disallow-simultaneous-connections: true
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/extensions/guacamole-auth-mysql/doc/example/settings.xml b/extensions/guacamole-auth-mysql/doc/example/settings.xml
new file mode 100644
index 0000000..d0fb6d5
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/doc/example/settings.xml
@@ -0,0 +1,21 @@
+<settings>
+
+ <!-- Profile defining the properties required for a MyBatis build -->
+ <profiles>
+ <profile>
+ <id>guacamole-mybatis</id>
+ <properties>
+ <guacamole.database.catalog>SCHEMA</guacamole.database.catalog>
+ <guacamole.database.schema>DATABASE</guacamole.database.schema>
+ <guacamole.database.user>USER</guacamole.database.user>
+ <guacamole.database.password>PASS</guacamole.database.password>
+ </properties>
+ </profile>
+ </profiles>
+
+ <!-- Activate by default -->
+ <activeProfiles>
+ <activeProfile>guacamole-mybatis</activeProfile>
+ </activeProfiles>
+
+</settings>
diff --git a/extensions/guacamole-auth-mysql/pom.xml b/extensions/guacamole-auth-mysql/pom.xml
new file mode 100644
index 0000000..00dc729
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/pom.xml
@@ -0,0 +1,131 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-auth-mysql</artifactId>
+ <packaging>jar</packaging>
+ <version>0.8.2</version>
+ <name>guacamole-auth-mysql</name>
+ <url>http://guac-dev.org/</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Written for 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <!-- Assembly plugin - for easy distribution -->
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2-beta-5</version>
+ <configuration>
+ <finalName>${project.artifactId}-${project.version}</finalName>
+ <appendAssemblyId>false</appendAssemblyId>
+ <descriptors>
+ <descriptor>src/main/assembly/dist.xml</descriptor>
+ </descriptors>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-dist-archive</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <!-- MyBatis Generator plugin -->
+ <plugin>
+ <groupId>org.mybatis.generator</groupId>
+ <artifactId>mybatis-generator-maven-plugin</artifactId>
+ <version>1.3.2</version>
+
+ <executions>
+ <execution>
+ <id>Generate MyBatis Artifacts</id>
+ <goals>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+
+ <!-- MySQL Connector -->
+ <dependencies>
+ <dependency>
+ <groupId>mysql</groupId>
+ <artifactId>mysql-connector-java</artifactId>
+ <version>5.1.23</version>
+ </dependency>
+ </dependencies>
+
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <!-- Guacamole Java API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+
+ <!-- Guacamole Extension API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-ext</artifactId>
+ <version>0.8.1</version>
+ </dependency>
+
+ <!-- SLF4J - logging -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-jcl</artifactId>
+ <version>1.6.1</version>
+ <scope>runtime</scope>
+ </dependency>
+
+ <!-- MyBatis -->
+ <dependency>
+ <groupId>org.mybatis</groupId>
+ <artifactId>mybatis</artifactId>
+ <version>3.1.1</version>
+ </dependency>
+
+ <!-- MyBatis Guice -->
+ <dependency>
+ <groupId>org.mybatis</groupId>
+ <artifactId>mybatis-guice</artifactId>
+ <version>3.2</version>
+ </dependency>
+
+ <!-- Google Collections -->
+ <dependency>
+ <groupId>com.google.collections</groupId>
+ <artifactId>google-collections</artifactId>
+ <version>1.0</version>
+ </dependency>
+ </dependencies>
+
+</project>
diff --git a/extensions/guacamole-auth-mysql/schema/001-create-schema.sql b/extensions/guacamole-auth-mysql/schema/001-create-schema.sql
new file mode 100644
index 0000000..7fb6b63
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/schema/001-create-schema.sql
@@ -0,0 +1,207 @@
+
+--
+-- Table of connection groups. Each connection group has a name.
+--
+
+CREATE TABLE `guacamole_connection_group` (
+
+ `connection_group_id` int(11) NOT NULL AUTO_INCREMENT,
+ `parent_id` int(11),
+ `connection_group_name` varchar(128) NOT NULL,
+ `type` enum('ORGANIZATIONAL',
+ 'BALANCING') NOT NULL DEFAULT 'ORGANIZATIONAL',
+
+ PRIMARY KEY (`connection_group_id`),
+ UNIQUE KEY `connection_group_name_parent` (`connection_group_name`, `parent_id`),
+
+ CONSTRAINT `guacamole_connection_group_ibfk_1`
+ FOREIGN KEY (`parent_id`)
+ REFERENCES `guacamole_connection_group` (`connection_group_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of connections. Each connection has a name, protocol, and
+-- associated set of parameters.
+-- A connection may belong to a connection group.
+--
+
+CREATE TABLE `guacamole_connection` (
+
+ `connection_id` int(11) NOT NULL AUTO_INCREMENT,
+ `connection_name` varchar(128) NOT NULL,
+ `parent_id` int(11),
+ `protocol` varchar(32) NOT NULL,
+
+ PRIMARY KEY (`connection_id`),
+ UNIQUE KEY `connection_name_parent` (`connection_name`, `parent_id`),
+
+ CONSTRAINT `guacamole_connection_ibfk_1`
+ FOREIGN KEY (`parent_id`)
+ REFERENCES `guacamole_connection_group` (`connection_group_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of users. Each user has a unique username and a hashed password
+-- with corresponding salt.
+--
+
+CREATE TABLE `guacamole_user` (
+
+ `user_id` int(11) NOT NULL AUTO_INCREMENT,
+ `username` varchar(128) NOT NULL,
+ `password_hash` binary(32) NOT NULL,
+ `password_salt` binary(32) NOT NULL,
+
+ PRIMARY KEY (`user_id`),
+ UNIQUE KEY `username` (`username`)
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of connection parameters. Each parameter is simply a name/value pair
+-- associated with a connection.
+--
+
+CREATE TABLE `guacamole_connection_parameter` (
+
+ `connection_id` int(11) NOT NULL,
+ `parameter_name` varchar(128) NOT NULL,
+ `parameter_value` varchar(4096) NOT NULL,
+
+ PRIMARY KEY (`connection_id`,`parameter_name`),
+
+ CONSTRAINT `guacamole_connection_parameter_ibfk_1`
+ FOREIGN KEY (`connection_id`)
+ REFERENCES `guacamole_connection` (`connection_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of connection permissions. Each connection permission grants a user
+-- specific access to a connection.
+--
+
+CREATE TABLE `guacamole_connection_permission` (
+
+ `user_id` int(11) NOT NULL,
+ `connection_id` int(11) NOT NULL,
+ `permission` enum('READ',
+ 'UPDATE',
+ 'DELETE',
+ 'ADMINISTER') NOT NULL,
+
+ PRIMARY KEY (`user_id`,`connection_id`,`permission`),
+
+ CONSTRAINT `guacamole_connection_permission_ibfk_1`
+ FOREIGN KEY (`connection_id`)
+ REFERENCES `guacamole_connection` (`connection_id`) ON DELETE CASCADE,
+
+ CONSTRAINT `guacamole_connection_permission_ibfk_2`
+ FOREIGN KEY (`user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of connection group permissions. Each group permission grants a user
+-- specific access to a connection group.
+--
+
+CREATE TABLE `guacamole_connection_group_permission` (
+
+ `user_id` int(11) NOT NULL,
+ `connection_group_id` int(11) NOT NULL,
+ `permission` enum('READ',
+ 'UPDATE',
+ 'DELETE',
+ 'ADMINISTER') NOT NULL,
+
+ PRIMARY KEY (`user_id`,`connection_group_id`,`permission`),
+
+ CONSTRAINT `guacamole_connection_group_permission_ibfk_1`
+ FOREIGN KEY (`connection_group_id`)
+ REFERENCES `guacamole_connection_group` (`connection_group_id`) ON DELETE CASCADE,
+
+ CONSTRAINT `guacamole_connection_group_permission_ibfk_2`
+ FOREIGN KEY (`user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of system permissions. Each system permission grants a user a
+-- system-level privilege of some kind.
+--
+
+CREATE TABLE `guacamole_system_permission` (
+
+ `user_id` int(11) NOT NULL,
+ `permission` enum('CREATE_CONNECTION',
+ 'CREATE_CONNECTION_GROUP',
+ 'CREATE_USER',
+ 'ADMINISTER') NOT NULL,
+
+ PRIMARY KEY (`user_id`,`permission`),
+
+ CONSTRAINT `guacamole_system_permission_ibfk_1`
+ FOREIGN KEY (`user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of user permissions. Each user permission grants a user access to
+-- another user (the "affected" user) for a specific type of operation.
+--
+
+CREATE TABLE `guacamole_user_permission` (
+
+ `user_id` int(11) NOT NULL,
+ `affected_user_id` int(11) NOT NULL,
+ `permission` enum('READ',
+ 'UPDATE',
+ 'DELETE',
+ 'ADMINISTER') NOT NULL,
+
+ PRIMARY KEY (`user_id`,`affected_user_id`,`permission`),
+
+ CONSTRAINT `guacamole_user_permission_ibfk_1`
+ FOREIGN KEY (`affected_user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE,
+
+ CONSTRAINT `guacamole_user_permission_ibfk_2`
+ FOREIGN KEY (`user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Table of connection history records. Each record defines a specific user's
+-- session, including the connection used, the start time, and the end time
+-- (if any).
+--
+
+CREATE TABLE `guacamole_connection_history` (
+
+ `history_id` int(11) NOT NULL AUTO_INCREMENT,
+ `user_id` int(11) NOT NULL,
+ `connection_id` int(11) NOT NULL,
+ `start_date` datetime NOT NULL,
+ `end_date` datetime DEFAULT NULL,
+
+ PRIMARY KEY (`history_id`),
+ KEY `user_id` (`user_id`),
+ KEY `connection_id` (`connection_id`),
+
+ CONSTRAINT `guacamole_connection_history_ibfk_1`
+ FOREIGN KEY (`user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE,
+
+ CONSTRAINT `guacamole_connection_history_ibfk_2`
+ FOREIGN KEY (`connection_id`)
+ REFERENCES `guacamole_connection` (`connection_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
diff --git a/extensions/guacamole-auth-mysql/schema/002-create-admin-user.sql b/extensions/guacamole-auth-mysql/schema/002-create-admin-user.sql
new file mode 100644
index 0000000..824ddf6
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/schema/002-create-admin-user.sql
@@ -0,0 +1,17 @@
+
+-- Create default user "guacadmin" with password "guacadmin"
+insert into guacamole_user values(1, 'guacadmin',
+ x'CA458A7D494E3BE824F5E1E175A1556C0F8EEF2C2D7DF3633BEC4A29C4411960', -- 'guacadmin'
+ x'FE24ADC5E11E2B25288D1704ABE67A79E342ECC26064CE69C5B3177795A82264');
+
+-- Grant this user create permissions
+insert into guacamole_system_permission values(1, 'CREATE_CONNECTION');
+insert into guacamole_system_permission values(1, 'CREATE_CONNECTION_GROUP');
+insert into guacamole_system_permission values(1, 'CREATE_USER');
+insert into guacamole_system_permission values(1, 'ADMINISTER');
+
+-- Grant admin permission to read/update/administer self
+insert into guacamole_user_permission values(1, 1, 'READ');
+insert into guacamole_user_permission values(1, 1, 'UPDATE');
+insert into guacamole_user_permission values(1, 1, 'ADMINISTER');
+
diff --git a/extensions/guacamole-auth-mysql/schema/upgrade/upgrade-pre-0.8.2.sql b/extensions/guacamole-auth-mysql/schema/upgrade/upgrade-pre-0.8.2.sql
new file mode 100644
index 0000000..160f3f7
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/schema/upgrade/upgrade-pre-0.8.2.sql
@@ -0,0 +1,68 @@
+
+--
+-- Table of connection groups. Each connection group has a name.
+--
+
+CREATE TABLE `guacamole_connection_group` (
+
+ `connection_group_id` int(11) NOT NULL AUTO_INCREMENT,
+ `parent_id` int(11),
+ `connection_group_name` varchar(128) NOT NULL,
+ `type` enum('ORGANIZATIONAL',
+ 'BALANCING') NOT NULL DEFAULT 'ORGANIZATIONAL',
+
+
+ PRIMARY KEY (`connection_group_id`),
+ UNIQUE KEY `connection_group_name_parent` (`connection_group_name`, `parent_id`),
+
+ CONSTRAINT `guacamole_connection_group_ibfk_1`
+ FOREIGN KEY (`parent_id`)
+ REFERENCES `guacamole_connection_group` (`connection_group_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+
+--
+-- Changes to connection table to support grouping.
+--
+
+ALTER TABLE `guacamole_connection` ADD COLUMN `parent_id` int(11) AFTER `connection_name`;
+
+ALTER TABLE `guacamole_connection` DROP INDEX `connection_name`;
+ALTER TABLE `guacamole_connection` ADD UNIQUE KEY `connection_name_parent` (`connection_name`, `parent_id`);
+
+ALTER TABLE `guacamole_connection` ADD CONSTRAINT `guacamole_connection_ibfk_1`
+ FOREIGN KEY (`parent_id`)
+ REFERENCES `guacamole_connection_group` (`connection_group_id`) ON DELETE CASCADE;
+
+--
+-- Table of connection group permissions. Each group permission grants a user
+-- specific access to a connection group.
+--
+
+CREATE TABLE `guacamole_connection_group_permission` (
+
+ `user_id` int(11) NOT NULL,
+ `connection_group_id` int(11) NOT NULL,
+ `permission` enum('READ',
+ 'UPDATE',
+ 'DELETE',
+ 'ADMINISTER') NOT NULL,
+
+ PRIMARY KEY (`user_id`,`connection_group_id`,`permission`),
+
+ CONSTRAINT `guacamole_connection_group_permission_ibfk_1`
+ FOREIGN KEY (`connection_group_id`)
+ REFERENCES `guacamole_connection_group` (`connection_group_id`) ON DELETE CASCADE,
+
+ CONSTRAINT `guacamole_connection_group_permission_ibfk_2`
+ FOREIGN KEY (`user_id`)
+ REFERENCES `guacamole_user` (`user_id`) ON DELETE CASCADE
+
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+ALTER TABLE `guacamole_system_permission` MODIFY `permission`
+ enum('CREATE_CONNECTION',
+ 'CREATE_CONNECTION_GROUP',
+ 'CREATE_USER',
+ 'ADMINISTER') NOT NULL;
diff --git a/extensions/guacamole-auth-mysql/src/main/assembly/dist.xml b/extensions/guacamole-auth-mysql/src/main/assembly/dist.xml
new file mode 100644
index 0000000..0628ad6
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/assembly/dist.xml
@@ -0,0 +1,54 @@
+<assembly
+ xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+
+ <id>dist</id>
+ <baseDirectory>${project.artifactId}-${project.version}</baseDirectory>
+
+ <!-- Output tar.gz -->
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+
+ <!-- Include docs and schema -->
+ <fileSets>
+
+ <!-- Include docs -->
+ <fileSet>
+ <outputDirectory>/</outputDirectory>
+ <directory>doc</directory>
+ </fileSet>
+
+ <!-- Include schema -->
+ <fileSet>
+ <outputDirectory>/schema</outputDirectory>
+ <directory>schema</directory>
+ </fileSet>
+
+ </fileSets>
+
+ <!-- Include self and all dependencies except guacamole-common
+ and guacamole-ext -->
+ <dependencySets>
+ <dependencySet>
+
+ <outputDirectory>/lib</outputDirectory>
+ <scope>runtime</scope>
+ <unpack>false</unpack>
+ <useProjectArtifact>true</useProjectArtifact>
+ <useTransitiveFiltering>true</useTransitiveFiltering>
+
+ <excludes>
+
+ <!-- Do not include guacamole-common -->
+ <exclude>org.glyptodon.guacamole:guacamole-common</exclude>
+
+ <!-- Do not include guacamole-ext -->
+ <exclude>org.glyptodon.guacamole:guacamole-ext</exclude>
+
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+
+</assembly>
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ActiveConnectionMap.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ActiveConnectionMap.java
new file mode 100644
index 0000000..06965eb
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ActiveConnectionMap.java
@@ -0,0 +1,515 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import org.glyptodon.guacamole.GuacamoleException;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionHistoryMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionHistory;
+
+/**
+ * Represents the map of currently active Connections to the count of the number
+ * of current users. Whenever a socket is opened, the connection count should be
+ * incremented, and whenever a socket is closed, the connection count should be
+ * decremented.
+ *
+ * @author James Muehlner
+ */
+public class ActiveConnectionMap {
+
+ /**
+ * Represents the count of users currently using a MySQL connection.
+ */
+ public class Connection {
+
+ /**
+ * The ID of the MySQL connection that this Connection represents.
+ */
+ private int connectionID;
+
+ /**
+ * The number of users currently using this connection.
+ */
+ private int currentUserCount;
+
+ /**
+ * Returns the ID of the MySQL connection that this Connection
+ * represents.
+ *
+ * @return the ID of the MySQL connection that this Connection
+ * represents.
+ */
+ public int getConnectionID() {
+ return connectionID;
+ }
+
+ /**
+ * Returns the number of users currently using this connection.
+ *
+ * @return the number of users currently using this connection.
+ */
+ public int getCurrentUserCount() {
+ return currentUserCount;
+ }
+
+ /**
+ * Set the current user count for this connection.
+ *
+ * @param currentUserCount The new user count for this Connection.
+ */
+ public void setCurrentUserCount(int currentUserCount) {
+ this.currentUserCount = currentUserCount;
+ }
+
+ /**
+ * Create a new Connection for the given connectionID with a zero
+ * current user count.
+ *
+ * @param connectionID The ID of the MySQL connection that this
+ * Connection represents.
+ */
+ public Connection(int connectionID) {
+ this.connectionID = connectionID;
+ this.currentUserCount = 0;
+ }
+ }
+
+ /*
+ * Represents a user connected to a connection or BALANCING connection group.
+ */
+ public class ConnectionUser {
+ /**
+ * The ID of the connection or connection group that this ConnectionUser refers to.
+ */
+ private int identifier;
+
+ /**
+ * The user that this ConnectionUser refers to.
+ */
+ private int userID;
+
+ /**
+ * Returns ID of the connection or connection group that this ConnectionUser refers to.
+ * @return ID of the connection or connection group that this ConnectionUser refers to.
+ */
+ public int getIdentifier() {
+ return identifier;
+ }
+
+ /**
+ * Returns the user ID that this ConnectionUser refers to.
+ * @return the user ID that this ConnectionUser refers to.
+ */
+ public int getUserID() {
+ return userID;
+ }
+
+ /**
+ * Create a ConnectionUser with the given connection or connection group
+ * ID and user ID.
+ *
+ * @param identifier The connection or connection group ID that this
+ * ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ */
+ public ConnectionUser(int identifier, int userID) {
+ this.identifier = identifier;
+ this.userID = userID;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+
+ // Only another ConnectionUser can equal this ConnectionUser
+ if(!(other instanceof ConnectionUser))
+ return false;
+
+ ConnectionUser otherConnectionGroupUser =
+ (ConnectionUser)other;
+
+ /*
+ * Two ConnectionGroupUsers are equal iff they represent the exact
+ * same pairing of connection or connection group and user.
+ */
+ return this.identifier == otherConnectionGroupUser.identifier
+ && this.userID == otherConnectionGroupUser.userID;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 3;
+ hash = 23 * hash + this.identifier;
+ hash = 23 * hash + this.userID;
+ return hash;
+ }
+ }
+
+ /**
+ * DAO for accessing connection history.
+ */
+ @Inject
+ private ConnectionHistoryMapper connectionHistoryDAO;
+
+ /**
+ * Map of all the connections that are currently active to the
+ * count of current users.
+ */
+ private Map<Integer, Connection> activeConnectionMap =
+ new HashMap<Integer, Connection>();
+
+ /**
+ * Map of all the connection group users to the count of current usages.
+ */
+ private Map<ConnectionUser, Integer> activeConnectionGroupUserMap =
+ new HashMap<ConnectionUser, Integer>();
+
+ /**
+ * Map of all the connection users to the count of current usages.
+ */
+ private Map<ConnectionUser, Integer> activeConnectionUserMap =
+ new HashMap<ConnectionUser, Integer>();
+
+ /**
+ * Returns the number of connections opened by the given user using
+ * the given ConnectionGroup.
+ *
+ * @param connectionGroupID The connection group ID that this
+ * ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ *
+ * @return The number of connections opened by the given user to the given
+ * ConnectionGroup.
+ */
+ public int getConnectionGroupUserCount(int connectionGroupID, int userID) {
+ Integer count = activeConnectionGroupUserMap.get
+ (new ConnectionUser(connectionGroupID, userID));
+
+ // No ConnectionUser found means this combination was never used
+ if(count == null)
+ return 0;
+
+ return count;
+ }
+
+ /**
+ * Checks if the given user is currently connected to the given BALANCING
+ * connection group.
+ *
+ * @param connectionGroupID The connection group ID that this
+ * ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ *
+ * @return True if the given user is currently connected to the given
+ * BALANCING connection group, false otherwise.
+ */
+ public boolean isConnectionGroupUserActive(int connectionGroupID, int userID) {
+ Integer count = activeConnectionGroupUserMap.get
+ (new ConnectionUser(connectionGroupID, userID));
+
+ // The connection group is in use if the ConnectionUser count > 0
+ return count != null && count > 0;
+ }
+
+ /**
+ * Increment the count of the number of connections opened by the given user
+ * to the given ConnectionGroup.
+ *
+ * @param connectionGroupID The connection group ID that this
+ * ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ */
+ private void incrementConnectionGroupUserCount(int connectionGroupID, int userID) {
+ int currentCount = getConnectionGroupUserCount(connectionGroupID, userID);
+
+ activeConnectionGroupUserMap.put
+ (new ConnectionUser(connectionGroupID, userID), currentCount + 1);
+ }
+
+ /**
+ * Decrement the count of the number of connections opened by the given user
+ * to the given ConnectionGroup.
+ *
+ * @param connectionGroupID The connection group ID that this
+ * ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ */
+ private void decrementConnectionGroupUserCount(int connectionGroupID, int userID) {
+ int currentCount = getConnectionGroupUserCount(connectionGroupID, userID);
+
+ activeConnectionGroupUserMap.put
+ (new ConnectionUser(connectionGroupID, userID), currentCount - 1);
+ }
+
+ /**
+ * Returns the number of connections opened by the given user using
+ * the given Connection.
+ *
+ * @param connectionID The connection ID that this ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ *
+ * @return The number of connections opened by the given user to the given
+ * connection.
+ */
+ public int getConnectionUserCount(int connectionID, int userID) {
+ Integer count = activeConnectionUserMap.get
+ (new ConnectionUser(connectionID, userID));
+
+ // No ConnectionUser found means this combination was never used
+ if(count == null)
+ return 0;
+
+ return count;
+ }
+
+ /**
+ * Checks if the given user is currently connected to the given connection.
+ *
+ * @param connectionID The connection ID that this ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ *
+ * @return True if the given user is currently connected to the given
+ * connection, false otherwise.
+ */
+ public boolean isConnectionUserActive(int connectionID, int userID) {
+ Integer count = activeConnectionUserMap.get
+ (new ConnectionUser(connectionID, userID));
+
+ // The connection is in use if the ConnectionUser count > 0
+ return count != null && count > 0;
+ }
+
+ /**
+ * Increment the count of the number of connections opened by the given user
+ * to the given Connection.
+ *
+ * @param connectionID The connection ID that this ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ */
+ private void incrementConnectionUserCount(int connectionID, int userID) {
+ int currentCount = getConnectionGroupUserCount(connectionID, userID);
+
+ activeConnectionUserMap.put
+ (new ConnectionUser(connectionID, userID), currentCount + 1);
+ }
+
+ /**
+ * Decrement the count of the number of connections opened by the given user
+ * to the given Connection.
+ *
+ * @param connectionID The connection ID that this ConnectionUser refers to.
+ * @param userID The user ID that this ConnectionUser refers to.
+ */
+ private void decrementConnectionUserCount(int connectionID, int userID) {
+ int currentCount = getConnectionGroupUserCount(connectionID, userID);
+
+ activeConnectionUserMap.put
+ (new ConnectionUser(connectionID, userID), currentCount - 1);
+ }
+
+ /**
+ * Returns the ID of the connection with the lowest number of current
+ * active users, if found.
+ *
+ * @param connectionIDs The subset of connection IDs to find the least
+ * used connection within.
+ *
+ * @return The ID of the connection with the lowest number of current
+ * active users, if found.
+ */
+ public Integer getLeastUsedConnection(Collection<Integer> connectionIDs) {
+
+ if(connectionIDs.isEmpty())
+ return null;
+
+ int minUserCount = Integer.MAX_VALUE;
+ Integer minConnectionID = null;
+
+ for(Integer connectionID : connectionIDs) {
+ Connection connection = activeConnectionMap.get(connectionID);
+
+ /*
+ * If the connection is not found in the map, it has not been used,
+ * and therefore will be count 0.
+ */
+ if(connection == null) {
+ minUserCount = 0;
+ minConnectionID = connectionID;
+ }
+ // If this is the least active connection
+ else if(connection.getCurrentUserCount() < minUserCount) {
+ minUserCount = connection.getCurrentUserCount();
+ minConnectionID = connection.getConnectionID();
+ }
+ }
+
+ return minConnectionID;
+ }
+
+ /**
+ * Returns the count of currently active users for the given connectionID.
+ * @return the count of currently active users for the given connectionID.
+ */
+ public int getCurrentUserCount(int connectionID) {
+ Connection connection = activeConnectionMap.get(connectionID);
+
+ if(connection == null)
+ return 0;
+
+ return connection.getCurrentUserCount();
+ }
+
+ /**
+ * Decrement the current user count for this Connection.
+ *
+ * @param connectionID The ID of the MySQL connection that this
+ * Connection represents.
+ *
+ * @throws GuacamoleException If the connection is not found.
+ */
+ private void decrementUserCount(int connectionID)
+ throws GuacamoleException {
+ Connection connection = activeConnectionMap.get(connectionID);
+
+ if(connection == null)
+ throw new GuacamoleException
+ ("Connection to decrement does not exist.");
+
+ // Decrement the current user count
+ connection.setCurrentUserCount(connection.getCurrentUserCount() - 1);
+ }
+
+ /**
+ * Increment the current user count for this Connection.
+ *
+ * @param connectionID The ID of the MySQL connection that this
+ * Connection represents.
+ *
+ * @throws GuacamoleException If the connection is not found.
+ */
+ private void incrementUserCount(int connectionID) {
+ Connection connection = activeConnectionMap.get(connectionID);
+
+ // If the Connection does not exist, it should be created
+ if(connection == null) {
+ connection = new Connection(connectionID);
+ activeConnectionMap.put(connectionID, connection);
+ }
+
+ // Increment the current user count
+ connection.setCurrentUserCount(connection.getCurrentUserCount() + 1);
+ }
+
+ /**
+ * Check if a connection is currently in use.
+ * @param connectionID The connection to check the status of.
+ * @return true if the connection is currently in use.
+ */
+ public boolean isActive(int connectionID) {
+ return getCurrentUserCount(connectionID) > 0;
+ }
+
+ /**
+ * Set a connection as open.
+ * @param connectionID The ID of the connection that is being opened.
+ * @param userID The ID of the user who is opening the connection.
+ * @param connectionGroupID The ID of the BALANCING connection group that is
+ * being connected to; null if not used.
+ * @return The ID of the history record created for this open connection.
+ */
+ public int openConnection(int connectionID, int userID, Integer connectionGroupID) {
+
+ // Create the connection history record
+ ConnectionHistory connectionHistory = new ConnectionHistory();
+ connectionHistory.setConnection_id(connectionID);
+ connectionHistory.setUser_id(userID);
+ connectionHistory.setStart_date(new Date());
+ connectionHistoryDAO.insert(connectionHistory);
+
+ // Increment the user count
+ incrementUserCount(connectionID);
+
+ // Increment the connection user count
+ incrementConnectionUserCount(connectionID, userID);
+
+ // If this is a connection to a BALANCING ConnectionGroup, increment the count
+ if(connectionGroupID != null)
+ incrementConnectionGroupUserCount(connectionGroupID, userID);
+
+ return connectionHistory.getHistory_id();
+ }
+
+ /**
+ * Set a connection as closed.
+ * @param historyID The ID of the history record about the open connection.
+ * @param connectionGroupID The ID of the BALANCING connection group that is
+ * being connected to; null if not used.
+ * @throws GuacamoleException If the open connection history is not found.
+ */
+ public void closeConnection(int historyID, Integer connectionGroupID)
+ throws GuacamoleException {
+
+ // Get the existing history record
+ ConnectionHistory connectionHistory =
+ connectionHistoryDAO.selectByPrimaryKey(historyID);
+
+ if(connectionHistory == null)
+ throw new GuacamoleException("History record not found.");
+
+ // Get the connection and user IDs
+ int connectionID = connectionHistory.getConnection_id();
+ int userID = connectionHistory.getUser_id();
+
+ // Update the connection history record to mark that it is now closed
+ connectionHistory.setEnd_date(new Date());
+ connectionHistoryDAO.updateByPrimaryKey(connectionHistory);
+
+ // Decrement the user count.
+ decrementUserCount(connectionID);
+
+ // Decrement the connection user count
+ decrementConnectionUserCount(connectionID, userID);
+
+ // If this is a connection to a BALANCING ConnectionGroup, decrement the count
+ if(connectionGroupID != null)
+ decrementConnectionGroupUserCount(connectionGroupID, userID);
+ }
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ConnectionDirectory.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ConnectionDirectory.java
new file mode 100644
index 0000000..232cdd1
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ConnectionDirectory.java
@@ -0,0 +1,342 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.Directory;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionParameterMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionParameter;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionParameterExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionGroupService;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionService;
+import net.sourceforge.guacamole.net.auth.mysql.service.PermissionCheckService;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.mybatis.guice.transactional.Transactional;
+
+/**
+ * A MySQL-based implementation of the connection directory.
+ *
+ * @author James Muehlner
+ */
+public class ConnectionDirectory implements Directory<String, Connection>{
+
+ /**
+ * The ID of the user who this connection directory belongs to.
+ * Access is based on his/her permission settings.
+ */
+ private int user_id;
+
+ /**
+ * The ID of the parent connection group.
+ */
+ private Integer parentID;
+
+ /**
+ * Service for checking permissions.
+ */
+ @Inject
+ private PermissionCheckService permissionCheckService;
+
+ /**
+ * Service managing connections.
+ */
+ @Inject
+ private ConnectionService connectionService;
+
+ /**
+ * Service managing connection groups.
+ */
+ @Inject
+ private ConnectionGroupService connectionGroupService;
+
+ /**
+ * Service for manipulating connection permissions in the database.
+ */
+ @Inject
+ private ConnectionPermissionMapper connectionPermissionDAO;
+
+ /**
+ * Service for manipulating connection parameters in the database.
+ */
+ @Inject
+ private ConnectionParameterMapper connectionParameterDAO;
+
+ /**
+ * Set the user and parentID for this directory.
+ *
+ * @param user_id The ID of the user owning this connection directory.
+ * @param parentID The ID of the parent connection group.
+ */
+ public void init(int user_id, Integer parentID) {
+ this.parentID = parentID;
+ this.user_id = user_id;
+ }
+
+ @Transactional
+ @Override
+ public Connection get(String identifier) throws GuacamoleException {
+
+ // Get connection
+ MySQLConnection connection =
+ connectionService.retrieveConnection(identifier, user_id);
+
+ if(connection == null)
+ return null;
+
+ // Verify permission to use the parent connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (connection.getParentID(), user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify access is granted
+ permissionCheckService.verifyConnectionAccess(
+ this.user_id,
+ connection.getConnectionID(),
+ MySQLConstants.CONNECTION_READ);
+
+ // Return connection
+ return connection;
+
+ }
+
+ @Transactional
+ @Override
+ public Set<String> getIdentifiers() throws GuacamoleException {
+
+ // Verify permission to use the connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (parentID, user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ return permissionCheckService.retrieveConnectionIdentifiers(user_id,
+ parentID, MySQLConstants.CONNECTION_READ);
+ }
+
+ @Transactional
+ @Override
+ public void add(Connection object) throws GuacamoleException {
+
+ String name = object.getName().trim();
+ if(name.isEmpty())
+ throw new GuacamoleClientException("The connection name cannot be blank.");
+
+ // Verify permission to create
+ permissionCheckService.verifySystemAccess(this.user_id,
+ MySQLConstants.SYSTEM_CONNECTION_CREATE);
+
+ // Verify permission to edit the connection group
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ this.parentID, MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify permission to use the connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (parentID, user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify that no connection already exists with this name.
+ MySQLConnection previousConnection =
+ connectionService.retrieveConnection(name, parentID, user_id);
+ if(previousConnection != null)
+ throw new GuacamoleClientException("That connection name is already in use.");
+
+ // Create connection
+ MySQLConnection connection = connectionService.createConnection(
+ name, object.getConfiguration().getProtocol(), user_id, parentID);
+
+ // Add connection parameters
+ createConfigurationValues(connection.getConnectionID(),
+ object.getConfiguration());
+
+ // Finally, give the current user full access to the newly created
+ // connection.
+ ConnectionPermissionKey newConnectionPermission = new ConnectionPermissionKey();
+ newConnectionPermission.setUser_id(this.user_id);
+ newConnectionPermission.setConnection_id(connection.getConnectionID());
+
+ // Read permission
+ newConnectionPermission.setPermission(MySQLConstants.CONNECTION_READ);
+ connectionPermissionDAO.insert(newConnectionPermission);
+
+ // Update permission
+ newConnectionPermission.setPermission(MySQLConstants.CONNECTION_UPDATE);
+ connectionPermissionDAO.insert(newConnectionPermission);
+
+ // Delete permission
+ newConnectionPermission.setPermission(MySQLConstants.CONNECTION_DELETE);
+ connectionPermissionDAO.insert(newConnectionPermission);
+
+ // Administer permission
+ newConnectionPermission.setPermission(MySQLConstants.CONNECTION_ADMINISTER);
+ connectionPermissionDAO.insert(newConnectionPermission);
+
+ }
+
+ /**
+ * Inserts all parameter values from the given configuration into the
+ * database, associating them with the connection having the givenID.
+ *
+ * @param connection_id The ID of the connection to associate all
+ * parameters with.
+ * @param config The GuacamoleConfiguration to read parameters from.
+ */
+ private void createConfigurationValues(int connection_id,
+ GuacamoleConfiguration config) {
+
+ // Insert new parameters for each parameter in the config
+ for (String name : config.getParameterNames()) {
+
+ // Create a ConnectionParameter based on the current parameter
+ ConnectionParameter parameter = new ConnectionParameter();
+ parameter.setConnection_id(connection_id);
+ parameter.setParameter_name(name);
+ parameter.setParameter_value(config.getParameter(name));
+
+ // Insert connection parameter
+ connectionParameterDAO.insert(parameter);
+ }
+
+ }
+
+ @Transactional
+ @Override
+ public void update(Connection object) throws GuacamoleException {
+
+ // If connection not actually from this auth provider, we can't handle
+ // the update
+ if (!(object instanceof MySQLConnection))
+ throw new GuacamoleException("Connection not from database.");
+
+ MySQLConnection mySQLConnection = (MySQLConnection) object;
+
+ // Verify permission to update
+ permissionCheckService.verifyConnectionAccess(this.user_id,
+ mySQLConnection.getConnectionID(),
+ MySQLConstants.CONNECTION_UPDATE);
+
+ // Perform update
+ connectionService.updateConnection(mySQLConnection);
+
+ // Delete old connection parameters
+ ConnectionParameterExample parameterExample = new ConnectionParameterExample();
+ parameterExample.createCriteria().andConnection_idEqualTo(mySQLConnection.getConnectionID());
+ connectionParameterDAO.deleteByExample(parameterExample);
+
+ // Add connection parameters
+ createConfigurationValues(mySQLConnection.getConnectionID(),
+ object.getConfiguration());
+
+ }
+
+ @Transactional
+ @Override
+ public void remove(String identifier) throws GuacamoleException {
+
+ // Get connection
+ MySQLConnection mySQLConnection =
+ connectionService.retrieveConnection(identifier, user_id);
+
+ if(mySQLConnection == null)
+ throw new GuacamoleException("Connection not found.");
+
+ // Verify permission to use the parent connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (mySQLConnection.getParentID(), user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify permission to delete
+ permissionCheckService.verifyConnectionAccess(this.user_id,
+ mySQLConnection.getConnectionID(),
+ MySQLConstants.CONNECTION_DELETE);
+
+ // Delete the connection itself
+ connectionService.deleteConnection(mySQLConnection.getConnectionID());
+
+ }
+
+ @Override
+ public void move(String identifier, Directory<String, Connection> directory)
+ throws GuacamoleException {
+
+ if(!(directory instanceof ConnectionDirectory))
+ throw new GuacamoleClientException("Directory not from database");
+
+ Integer toConnectionGroupID = ((ConnectionDirectory)directory).parentID;
+
+ // Get connection
+ MySQLConnection mySQLConnection =
+ connectionService.retrieveConnection(identifier, user_id);
+
+ if(mySQLConnection == null)
+ throw new GuacamoleClientException("Connection not found.");
+
+ // Verify permission to update the connection
+ permissionCheckService.verifyConnectionAccess(this.user_id,
+ mySQLConnection.getConnectionID(),
+ MySQLConstants.CONNECTION_UPDATE);
+
+ // Verify permission to use the from connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (mySQLConnection.getParentID(), user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify permission to update the from connection group
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ mySQLConnection.getParentID(), MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify permission to use the to connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (toConnectionGroupID, user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify permission to update the to connection group
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ toConnectionGroupID, MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify that no connection already exists with this name.
+ MySQLConnection previousConnection =
+ connectionService.retrieveConnection(mySQLConnection.getName(),
+ toConnectionGroupID, user_id);
+ if(previousConnection != null)
+ throw new GuacamoleClientException("That connection name is already in use.");
+
+ // Update the connection
+ mySQLConnection.setParentID(toConnectionGroupID);
+ connectionService.updateConnection(mySQLConnection);
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ConnectionGroupDirectory.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ConnectionGroupDirectory.java
new file mode 100644
index 0000000..fdcb862
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/ConnectionGroupDirectory.java
@@ -0,0 +1,306 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup.Type;
+import org.glyptodon.guacamole.net.auth.Directory;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionGroupPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionGroupService;
+import net.sourceforge.guacamole.net.auth.mysql.service.PermissionCheckService;
+import org.mybatis.guice.transactional.Transactional;
+
+/**
+ * A MySQL-based implementation of the connection group directory.
+ *
+ * @author James Muehlner
+ */
+public class ConnectionGroupDirectory implements Directory<String, ConnectionGroup>{
+
+ /**
+ * The ID of the user who this connection directory belongs to.
+ * Access is based on his/her permission settings.
+ */
+ private int user_id;
+
+ /**
+ * The ID of the parent connection group.
+ */
+ private Integer parentID;
+
+ /**
+ * Service for checking permissions.
+ */
+ @Inject
+ private PermissionCheckService permissionCheckService;
+
+ /**
+ * Service managing connection groups.
+ */
+ @Inject
+ private ConnectionGroupService connectionGroupService;
+
+ /**
+ * Service for manipulating connection group permissions in the database.
+ */
+ @Inject
+ private ConnectionGroupPermissionMapper connectionGroupPermissionDAO;
+
+ /**
+ * Set the user and parentID for this directory.
+ *
+ * @param user_id The ID of the user owning this connection group directory.
+ * @param parentID The ID of the parent connection group.
+ */
+ public void init(int user_id, Integer parentID) {
+ this.parentID = parentID;
+ this.user_id = user_id;
+ }
+
+ @Transactional
+ @Override
+ public ConnectionGroup get(String identifier) throws GuacamoleException {
+
+ // Get connection
+ MySQLConnectionGroup connectionGroup =
+ connectionGroupService.retrieveConnectionGroup(identifier, user_id);
+
+ if(connectionGroup == null)
+ return null;
+
+ // Verify permission to use the parent connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (connectionGroup.getParentID(), user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify access is granted
+ permissionCheckService.verifyConnectionGroupAccess(
+ this.user_id,
+ connectionGroup.getConnectionGroupID(),
+ MySQLConstants.CONNECTION_GROUP_READ);
+
+ // Return connection group
+ return connectionGroup;
+
+ }
+
+ @Transactional
+ @Override
+ public Set<String> getIdentifiers() throws GuacamoleException {
+
+ // Verify permission to use the connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (parentID, user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ return permissionCheckService.retrieveConnectionGroupIdentifiers(user_id,
+ parentID, MySQLConstants.CONNECTION_GROUP_READ);
+ }
+
+ @Transactional
+ @Override
+ public void add(ConnectionGroup object) throws GuacamoleException {
+
+ String name = object.getName().trim();
+ if(name.isEmpty())
+ throw new GuacamoleClientException("The connection group name cannot be blank.");
+
+ Type type = object.getType();
+
+ String mySQLType = MySQLConstants.getConnectionGroupTypeConstant(type);
+
+ // Verify permission to create
+ permissionCheckService.verifySystemAccess(this.user_id,
+ MySQLConstants.SYSTEM_CONNECTION_GROUP_CREATE);
+
+ // Verify permission to edit the parent connection group
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ this.parentID, MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify permission to use the parent connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (parentID, user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify that no connection already exists with this name.
+ MySQLConnectionGroup previousConnectionGroup =
+ connectionGroupService.retrieveConnectionGroup(name, parentID, user_id);
+ if(previousConnectionGroup != null)
+ throw new GuacamoleClientException("That connection group name is already in use.");
+
+ // Create connection group
+ MySQLConnectionGroup connectionGroup = connectionGroupService
+ .createConnectionGroup(name, user_id, parentID, mySQLType);
+
+ // Finally, give the current user full access to the newly created
+ // connection group.
+ ConnectionGroupPermissionKey newConnectionGroupPermission = new ConnectionGroupPermissionKey();
+ newConnectionGroupPermission.setUser_id(this.user_id);
+ newConnectionGroupPermission.setConnection_group_id(connectionGroup.getConnectionGroupID());
+
+ // Read permission
+ newConnectionGroupPermission.setPermission(MySQLConstants.CONNECTION_GROUP_READ);
+ connectionGroupPermissionDAO.insert(newConnectionGroupPermission);
+
+ // Update permission
+ newConnectionGroupPermission.setPermission(MySQLConstants.CONNECTION_GROUP_UPDATE);
+ connectionGroupPermissionDAO.insert(newConnectionGroupPermission);
+
+ // Delete permission
+ newConnectionGroupPermission.setPermission(MySQLConstants.CONNECTION_GROUP_DELETE);
+ connectionGroupPermissionDAO.insert(newConnectionGroupPermission);
+
+ // Administer permission
+ newConnectionGroupPermission.setPermission(MySQLConstants.CONNECTION_GROUP_ADMINISTER);
+ connectionGroupPermissionDAO.insert(newConnectionGroupPermission);
+
+ }
+
+ @Transactional
+ @Override
+ public void update(ConnectionGroup object) throws GuacamoleException {
+
+ // If connection not actually from this auth provider, we can't handle
+ // the update
+ if (!(object instanceof MySQLConnectionGroup))
+ throw new GuacamoleException("Connection not from database.");
+
+ MySQLConnectionGroup mySQLConnectionGroup = (MySQLConnectionGroup) object;
+
+ // Verify permission to update
+ permissionCheckService.verifyConnectionAccess(this.user_id,
+ mySQLConnectionGroup.getConnectionGroupID(),
+ MySQLConstants.CONNECTION_UPDATE);
+
+ // Perform update
+ connectionGroupService.updateConnectionGroup(mySQLConnectionGroup);
+ }
+
+ @Transactional
+ @Override
+ public void remove(String identifier) throws GuacamoleException {
+
+ // Get connection
+ MySQLConnectionGroup mySQLConnectionGroup =
+ connectionGroupService.retrieveConnectionGroup(identifier, user_id);
+
+ if(mySQLConnectionGroup == null)
+ throw new GuacamoleException("Connection group not found.");
+
+ // Verify permission to use the parent connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (mySQLConnectionGroup.getParentID(), user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify permission to delete
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ mySQLConnectionGroup.getConnectionGroupID(),
+ MySQLConstants.CONNECTION_GROUP_DELETE);
+
+ // Delete the connection group itself
+ connectionGroupService.deleteConnectionGroup
+ (mySQLConnectionGroup.getConnectionGroupID());
+
+ }
+
+ @Override
+ public void move(String identifier, Directory<String, ConnectionGroup> directory)
+ throws GuacamoleException {
+
+ if(MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER.equals(identifier))
+ throw new GuacamoleClientException("The root connection group cannot be moved.");
+
+ if(!(directory instanceof ConnectionGroupDirectory))
+ throw new GuacamoleClientException("Directory not from database");
+
+ Integer toConnectionGroupID = ((ConnectionGroupDirectory)directory).parentID;
+
+ // Get connection group
+ MySQLConnectionGroup mySQLConnectionGroup =
+ connectionGroupService.retrieveConnectionGroup(identifier, user_id);
+
+ if(mySQLConnectionGroup == null)
+ throw new GuacamoleClientException("Connection group not found.");
+
+ // Verify permission to update the connection
+ permissionCheckService.verifyConnectionAccess(this.user_id,
+ mySQLConnectionGroup.getConnectionGroupID(),
+ MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify permission to use the from connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (mySQLConnectionGroup.getParentID(), user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify permission to update the from connection group
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ mySQLConnectionGroup.getParentID(), MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify permission to use the to connection group for organizational purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (toConnectionGroupID, user_id, MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+
+ // Verify permission to update the to connection group
+ permissionCheckService.verifyConnectionGroupAccess(this.user_id,
+ toConnectionGroupID, MySQLConstants.CONNECTION_GROUP_UPDATE);
+
+ // Verify that no connection already exists with this name.
+ MySQLConnectionGroup previousConnectionGroup =
+ connectionGroupService.retrieveConnectionGroup(mySQLConnectionGroup.getName(),
+ toConnectionGroupID, user_id);
+ if(previousConnectionGroup != null)
+ throw new GuacamoleClientException("That connection group name is already in use.");
+
+ // Verify that moving this connectionGroup would not cause a cycle
+ Integer relativeParentID = toConnectionGroupID;
+ while(relativeParentID != null) {
+ if(relativeParentID == mySQLConnectionGroup.getConnectionGroupID())
+ throw new GuacamoleClientException("Connection group cycle detected.");
+
+ MySQLConnectionGroup relativeParentGroup = connectionGroupService.
+ retrieveConnectionGroup(relativeParentID, user_id);
+
+ relativeParentID = relativeParentGroup.getParentID();
+ }
+
+ // Update the connection
+ mySQLConnectionGroup.setParentID(toConnectionGroupID);
+ connectionGroupService.updateConnectionGroup(mySQLConnectionGroup);
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLAuthenticationProvider.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLAuthenticationProvider.java
new file mode 100644
index 0000000..6877ca3
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLAuthenticationProvider.java
@@ -0,0 +1,197 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Binder;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Module;
+import com.google.inject.name.Names;
+import java.util.Properties;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.AuthenticationProvider;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionGroupMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionGroupPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionHistoryMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionParameterMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.SystemPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.UserMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.UserPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.properties.MySQLGuacamoleProperties;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionGroupService;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionService;
+import net.sourceforge.guacamole.net.auth.mysql.service.PasswordEncryptionService;
+import net.sourceforge.guacamole.net.auth.mysql.service.PermissionCheckService;
+import net.sourceforge.guacamole.net.auth.mysql.service.SHA256PasswordEncryptionService;
+import net.sourceforge.guacamole.net.auth.mysql.service.SaltService;
+import net.sourceforge.guacamole.net.auth.mysql.service.SecureRandomSaltService;
+import net.sourceforge.guacamole.net.auth.mysql.service.UserService;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
+import org.mybatis.guice.MyBatisModule;
+import org.mybatis.guice.datasource.builtin.PooledDataSourceProvider;
+import org.mybatis.guice.datasource.helper.JdbcHelper;
+
+/**
+ * Provides a MySQL based implementation of the AuthenticationProvider
+ * functionality.
+ *
+ * @author James Muehlner
+ */
+public class MySQLAuthenticationProvider implements AuthenticationProvider {
+
+ /**
+ * Set of all active connections.
+ */
+ private ActiveConnectionMap activeConnectionMap = new ActiveConnectionMap();
+
+ /**
+ * Injector which will manage the object graph of this authentication
+ * provider.
+ */
+ private Injector injector;
+
+ @Override
+ public UserContext getUserContext(Credentials credentials) throws GuacamoleException {
+
+ // Get user service
+ UserService userService = injector.getInstance(UserService.class);
+
+ // Get user
+ MySQLUser authenticatedUser = userService.retrieveUser(credentials);
+ if (authenticatedUser != null) {
+ MySQLUserContext context = injector.getInstance(MySQLUserContext.class);
+ context.init(authenticatedUser.getUserID());
+ return context;
+ }
+
+ // Otherwise, unauthorized
+ return null;
+
+ }
+
+ /**
+ * Creates a new MySQLAuthenticationProvider that reads and writes
+ * authentication data to a MySQL database defined by properties in
+ * guacamole.properties.
+ *
+ * @throws GuacamoleException If a required property is missing, or
+ * an error occurs while parsing a property.
+ */
+ public MySQLAuthenticationProvider() throws GuacamoleException {
+
+ final Properties myBatisProperties = new Properties();
+ final Properties driverProperties = new Properties();
+
+ // Set the mysql properties for MyBatis.
+ myBatisProperties.setProperty("mybatis.environment.id", "guacamole");
+ myBatisProperties.setProperty("JDBC.host", GuacamoleProperties.getRequiredProperty(MySQLGuacamoleProperties.MYSQL_HOSTNAME));
+ myBatisProperties.setProperty("JDBC.port", String.valueOf(GuacamoleProperties.getRequiredProperty(MySQLGuacamoleProperties.MYSQL_PORT)));
+ myBatisProperties.setProperty("JDBC.schema", GuacamoleProperties.getRequiredProperty(MySQLGuacamoleProperties.MYSQL_DATABASE));
+ myBatisProperties.setProperty("JDBC.username", GuacamoleProperties.getRequiredProperty(MySQLGuacamoleProperties.MYSQL_USERNAME));
+ myBatisProperties.setProperty("JDBC.password", GuacamoleProperties.getRequiredProperty(MySQLGuacamoleProperties.MYSQL_PASSWORD));
+ myBatisProperties.setProperty("JDBC.autoCommit", "false");
+ driverProperties.setProperty("characterEncoding","UTF-8");
+
+ // Set up Guice injector.
+ injector = Guice.createInjector(
+ JdbcHelper.MySQL,
+
+ new Module() {
+ @Override
+ public void configure(Binder binder) {
+ Names.bindProperties(binder, myBatisProperties);
+ binder.bind(Properties.class)
+ .annotatedWith(Names.named("JDBC.driverProperties"))
+ .toInstance(driverProperties);
+ }
+ },
+
+ new MyBatisModule() {
+ @Override
+ protected void initialize() {
+
+ // Datasource
+ bindDataSourceProviderType(PooledDataSourceProvider.class);
+
+ // Transaction factory
+ bindTransactionFactoryType(JdbcTransactionFactory.class);
+
+ // Add MyBatis mappers
+ addMapperClass(ConnectionHistoryMapper.class);
+ addMapperClass(ConnectionMapper.class);
+ addMapperClass(ConnectionGroupMapper.class);
+ addMapperClass(ConnectionGroupPermissionMapper.class);
+ addMapperClass(ConnectionParameterMapper.class);
+ addMapperClass(ConnectionPermissionMapper.class);
+ addMapperClass(SystemPermissionMapper.class);
+ addMapperClass(UserMapper.class);
+ addMapperClass(UserPermissionMapper.class);
+
+ // Bind interfaces
+ bind(MySQLUserContext.class);
+ bind(UserDirectory.class);
+ bind(MySQLUser.class);
+ bind(SaltService.class).to(SecureRandomSaltService.class);
+ bind(PasswordEncryptionService.class).to(SHA256PasswordEncryptionService.class);
+ bind(PermissionCheckService.class);
+ bind(ConnectionService.class);
+ bind(ConnectionGroupService.class);
+ bind(UserService.class);
+ bind(ActiveConnectionMap.class).toInstance(activeConnectionMap);
+
+ }
+ } // end of mybatis module
+
+ );
+ } // end of constructor
+
+ @Override
+ public UserContext updateUserContext(UserContext context,
+ Credentials credentials) throws GuacamoleException {
+
+ // No need to update the context
+ return context;
+
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnection.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnection.java
new file mode 100644
index 0000000..96258aa
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnection.java
@@ -0,0 +1,156 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.auth.AbstractConnection;
+import org.glyptodon.guacamole.net.auth.ConnectionRecord;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionService;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+/**
+ * A MySQL based implementation of the Connection object.
+ * @author James Muehlner
+ */
+public class MySQLConnection extends AbstractConnection {
+
+ /**
+ * The ID associated with this connection in the database.
+ */
+ private Integer connectionID;
+
+ /**
+ * The ID of the parent connection group for this connection.
+ */
+ private Integer parentID;
+
+ /**
+ * The ID of the user who queried or created this connection.
+ */
+ private int userID;
+
+ /**
+ * History of this connection.
+ */
+ private List<ConnectionRecord> history = new ArrayList<ConnectionRecord>();
+
+ /**
+ * Service for managing connections.
+ */
+ @Inject
+ private ConnectionService connectionService;
+
+ /**
+ * Create a default, empty connection.
+ */
+ public MySQLConnection() {
+ }
+
+ /**
+ * Get the ID of the corresponding connection record.
+ * @return The ID of the corresponding connection, if any.
+ */
+ public Integer getConnectionID() {
+ return connectionID;
+ }
+
+ /**
+ * Sets the ID of the corresponding connection record.
+ * @param connectionID The ID to assign to this connection.
+ */
+ public void setConnectionID(Integer connectionID) {
+ this.connectionID = connectionID;
+ }
+
+ /**
+ * Get the ID of the parent connection group for this connection, if any.
+ * @return The ID of the parent connection group for this connection, if any.
+ */
+ public Integer getParentID() {
+ return parentID;
+ }
+
+ /**
+ * Sets the ID of the parent connection group for this connection.
+ * @param connectionID The ID of the parent connection group for this connection.
+ */
+ public void setParentID(Integer parentID) {
+ this.parentID = parentID;
+ }
+
+ /**
+ * Initialize from explicit values.
+ *
+ * @param connectionID The ID of the associated database record, if any.
+ * @param parentID The D of the parent connection group for this connection, if any.
+ * @param identifier The unique identifier associated with this connection.
+ * @param config The GuacamoleConfiguration associated with this connection.
+ * @param history All ConnectionRecords associated with this connection.
+ * @param userID The IID of the user who queried this connection.
+ */
+ public void init(Integer connectionID, Integer parentID, String name,
+ String identifier, GuacamoleConfiguration config,
+ List<? extends ConnectionRecord> history, int userID) {
+
+ this.connectionID = connectionID;
+ this.parentID = parentID;
+ setName(name);
+ setIdentifier(identifier);
+ setConfiguration(config);
+ this.history.addAll(history);
+ this.userID = userID;
+
+ }
+
+ @Override
+ public GuacamoleSocket connect(GuacamoleClientInformation info) throws GuacamoleException {
+ return connectionService.connect(this, info, userID, null);
+ }
+
+ @Override
+ public List<? extends ConnectionRecord> getHistory() throws GuacamoleException {
+ return Collections.unmodifiableList(history);
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnectionGroup.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnectionGroup.java
new file mode 100644
index 0000000..bba1ef1
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnectionGroup.java
@@ -0,0 +1,193 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.auth.AbstractConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionGroupService;
+import net.sourceforge.guacamole.net.auth.mysql.service.PermissionCheckService;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+
+/**
+ * A MySQL based implementation of the ConnectionGroup object.
+ * @author James Muehlner
+ */
+public class MySQLConnectionGroup extends AbstractConnectionGroup {
+
+ /**
+ * The ID associated with this connection group in the database.
+ */
+ private Integer connectionGroupID;
+
+ /**
+ * The ID of the parent connection group for this connection group.
+ */
+ private Integer parentID;
+
+ /**
+ * The ID of the user who queried or created this connection group.
+ */
+ private int userID;
+
+ /**
+ * A Directory of connections that have this connection group as a parent.
+ */
+ private ConnectionDirectory connectionDirectory = null;
+
+ /**
+ * A Directory of connection groups that have this connection group as a parent.
+ */
+ private ConnectionGroupDirectory connectionGroupDirectory = null;
+
+ /**
+ * Service managing connection groups.
+ */
+ @Inject
+ private ConnectionGroupService connectionGroupService;
+
+ /**
+ * Service for checking permissions.
+ */
+ @Inject
+ private PermissionCheckService permissionCheckService;
+
+ /**
+ * Service for creating new ConnectionDirectory objects.
+ */
+ @Inject Provider<ConnectionDirectory> connectionDirectoryProvider;
+
+ /**
+ * Service for creating new ConnectionGroupDirectory objects.
+ */
+ @Inject Provider<ConnectionGroupDirectory> connectionGroupDirectoryProvider;
+
+ /**
+ * Create a default, empty connection group.
+ */
+ public MySQLConnectionGroup() {
+ }
+
+ /**
+ * Get the ID of the corresponding connection group record.
+ * @return The ID of the corresponding connection group, if any.
+ */
+ public Integer getConnectionGroupID() {
+ return connectionGroupID;
+ }
+
+ /**
+ * Sets the ID of the corresponding connection group record.
+ * @param connectionID The ID to assign to this connection group.
+ */
+ public void setConnectionID(Integer connectionGroupID) {
+ this.connectionGroupID = connectionGroupID;
+ }
+
+ /**
+ * Get the ID of the parent connection group for this connection group, if any.
+ * @return The ID of the parent connection group for this connection group, if any.
+ */
+ public Integer getParentID() {
+ return parentID;
+ }
+
+ /**
+ * Sets the ID of the parent connection group for this connection group.
+ * @param connectionID The ID of the parent connection group for this connection group.
+ */
+ public void setParentID(Integer parentID) {
+ this.parentID = parentID;
+ }
+
+ /**
+ * Initialize from explicit values.
+ *
+ * @param connectionGroupID The ID of the associated database record, if any.
+ * @param parentID The ID of the parent connection group for this connection group, if any.
+ * @param identifier The unique identifier associated with this connection group.
+ * @param type The type of this connection group.
+ * @param userID The IID of the user who queried this connection.
+ */
+ public void init(Integer connectionGroupID, Integer parentID, String name,
+ String identifier, ConnectionGroup.Type type, int userID) {
+ this.connectionGroupID = connectionGroupID;
+ this.parentID = parentID;
+ setName(name);
+ setIdentifier(identifier);
+ setType(type);
+ this.userID = userID;
+
+ connectionDirectory = connectionDirectoryProvider.get();
+ connectionDirectory.init(userID, connectionGroupID);
+
+ connectionGroupDirectory = connectionGroupDirectoryProvider.get();
+ connectionGroupDirectory.init(userID, connectionGroupID);
+ }
+
+ @Override
+ public GuacamoleSocket connect(GuacamoleClientInformation info) throws GuacamoleException {
+
+ // Verify permission to use the connection group for balancing purposes
+ permissionCheckService.verifyConnectionGroupUsageAccess
+ (this.connectionGroupID, this.userID, MySQLConstants.CONNECTION_GROUP_BALANCING);
+
+ // Verify permission to delete
+ permissionCheckService.verifyConnectionGroupAccess(this.userID,
+ this.connectionGroupID,
+ MySQLConstants.CONNECTION_GROUP_READ);
+
+ return connectionGroupService.connect(this, info, userID);
+ }
+
+ @Override
+ public Directory<String, Connection> getConnectionDirectory() throws GuacamoleException {
+ return connectionDirectory;
+ }
+
+ @Override
+ public Directory<String, ConnectionGroup> getConnectionGroupDirectory() throws GuacamoleException {
+ return connectionGroupDirectory;
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnectionRecord.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnectionRecord.java
new file mode 100644
index 0000000..c7903ad
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConnectionRecord.java
@@ -0,0 +1,103 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Date;
+import org.glyptodon.guacamole.net.auth.ConnectionRecord;
+
+/**
+ * A ConnectionRecord which is based on data stored in MySQL.
+ *
+ * @author James Muehlner
+ */
+public class MySQLConnectionRecord implements ConnectionRecord {
+
+ /**
+ * The start date of the ConnectionRecord.
+ */
+ private Date startDate;
+
+ /**
+ * The end date of the ConnectionRecord.
+ */
+ private Date endDate;
+
+ /**
+ * The name of the user that is associated with this ConnectionRecord.
+ */
+ private String username;
+
+ /**
+ * Initialize this MySQLConnectionRecord with the start/end dates,
+ * and the name of the user it represents.
+ *
+ * @param startDate The start date of the connection history.
+ * @param endDate The end date of the connection history.
+ * @param username The name of the user that used the connection.
+ */
+ public MySQLConnectionRecord(Date startDate, Date endDate,
+ String username) {
+ if (startDate != null) this.startDate = new Date(startDate.getTime());
+ if (endDate != null) this.endDate = new Date(endDate.getTime());
+ this.username = username;
+ }
+
+ @Override
+ public Date getStartDate() {
+ if (startDate == null) return null;
+ return new Date(startDate.getTime());
+ }
+
+ @Override
+ public Date getEndDate() {
+ if (endDate == null) return null;
+ return new Date(endDate.getTime());
+ }
+
+ @Override
+ public String getUsername() {
+ return username;
+ }
+
+ @Override
+ public boolean isActive() {
+ // If the end date hasn't been stored yet, the connection is still open.
+ return endDate == null;
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConstants.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConstants.java
new file mode 100644
index 0000000..144936a
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLConstants.java
@@ -0,0 +1,279 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A set of constants that are useful for the MySQL-based authentication provider.
+ * @author James Muehlner
+ */
+public final class MySQLConstants {
+
+ /**
+ * This class should not be instantiated.
+ */
+ private MySQLConstants() {}
+
+ /**
+ * The string stored in the database to represent READ access to a user.
+ */
+ public static final String USER_READ = "READ";
+
+ /**
+ * The string stored in the database to represent UPDATE access to a user.
+ */
+ public static final String USER_UPDATE = "UPDATE";
+
+ /**
+ * The string stored in the database to represent DELETE access to a user.
+ */
+ public static final String USER_DELETE = "DELETE";
+
+ /**
+ * The string stored in the database to represent ADMINISTER access to a
+ * user.
+ */
+ public static final String USER_ADMINISTER = "ADMINISTER";
+
+ /**
+ * The string stored in the database to represent READ access to a
+ * connection.
+ */
+ public static final String CONNECTION_READ = "READ";
+
+ /**
+ * The string stored in the database to represent UPDATE access to a
+ * connection.
+ */
+ public static final String CONNECTION_UPDATE = "UPDATE";
+
+ /**
+ * The string stored in the database to represent DELETE access to a
+ * connection.
+ */
+ public static final String CONNECTION_DELETE = "DELETE";
+
+ /**
+ * The string stored in the database to represent ADMINISTER access to a
+ * connection.
+ */
+ public static final String CONNECTION_ADMINISTER = "ADMINISTER";
+
+ /**
+ * The string stored in the database to represent READ access to a
+ * connection.
+ */
+ public static final String CONNECTION_GROUP_READ = "READ";
+
+ /**
+ * The string stored in the database to represent UPDATE access to a
+ * connection group.
+ */
+ public static final String CONNECTION_GROUP_UPDATE = "UPDATE";
+
+ /**
+ * The string stored in the database to represent DELETE access to a
+ * connection group.
+ */
+ public static final String CONNECTION_GROUP_DELETE = "DELETE";
+
+ /**
+ * The string stored in the database to represent ADMINISTER access to a
+ * connection group.
+ */
+ public static final String CONNECTION_GROUP_ADMINISTER = "ADMINISTER";
+
+ /**
+ * The string stored in the database to represent a BALANCING
+ * connection group.
+ */
+ public static final String CONNECTION_GROUP_BALANCING = "BALANCING";
+
+ /**
+ * The string stored in the database to represent an ORGANIZATIONAL
+ * connection group.
+ */
+ public static final String CONNECTION_GROUP_ORGANIZATIONAL =
+ "ORGANIZATIONAL";
+
+ /**
+ * The identifier used to mark the root connection group.
+ */
+ public static final String CONNECTION_GROUP_ROOT_IDENTIFIER = "ROOT";
+
+ /**
+ * The string stored in the database to represent permission to create
+ * users.
+ */
+ public static final String SYSTEM_USER_CREATE = "CREATE_USER";
+
+ /**
+ * The string stored in the database to represent permission to create
+ * connections.
+ */
+ public static final String SYSTEM_CONNECTION_CREATE = "CREATE_CONNECTION";
+
+ /**
+ * The string stored in the database to represent permission to create
+ * connection groups.
+ */
+ public static final String SYSTEM_CONNECTION_GROUP_CREATE = "CREATE_CONNECTION_GROUP";
+
+ /**
+ * The string stored in the database to represent permission to administer
+ * the system as a whole.
+ */
+ public static final String SYSTEM_ADMINISTER = "ADMINISTER";
+
+ /**
+ * Given the type of a permission affecting a user, returns the MySQL
+ * constant representing that permission type.
+ *
+ * @param type The type of permission to look up.
+ * @return The MySQL constant corresponding to the given permission type.
+ */
+ public static String getUserConstant(ObjectPermission.Type type) {
+
+ // Convert permission type to MySQL constant
+ switch (type) {
+ case READ: return USER_READ;
+ case UPDATE: return USER_UPDATE;
+ case ADMINISTER: return USER_ADMINISTER;
+ case DELETE: return USER_DELETE;
+ }
+
+ // If we get here, permission support was not properly implemented
+ throw new UnsupportedOperationException(
+ "Unsupported permission type: " + type);
+
+ }
+
+ /**
+ * Given the type of a permission affecting a connection, returns the MySQL
+ * constant representing that permission type.
+ *
+ * @param type The type of permission to look up.
+ * @return The MySQL constant corresponding to the given permission type.
+ */
+ public static String getConnectionConstant(ObjectPermission.Type type) {
+
+ // Convert permission type to MySQL constant
+ switch (type) {
+ case READ: return CONNECTION_READ;
+ case UPDATE: return CONNECTION_UPDATE;
+ case ADMINISTER: return CONNECTION_ADMINISTER;
+ case DELETE: return CONNECTION_DELETE;
+ }
+
+ // If we get here, permission support was not properly implemented
+ throw new UnsupportedOperationException(
+ "Unsupported permission type: " + type);
+
+ }
+
+ /**
+ * Given the type of a permission affecting a connection group,
+ * returns the MySQL constant representing that permission type.
+ *
+ * @param type The type of permission to look up.
+ * @return The MySQL constant corresponding to the given permission type.
+ */
+ public static String getConnectionGroupConstant(ObjectPermission.Type type) {
+
+ // Convert permission type to MySQL constant
+ switch (type) {
+ case READ: return CONNECTION_GROUP_READ;
+ case UPDATE: return CONNECTION_GROUP_UPDATE;
+ case ADMINISTER: return CONNECTION_GROUP_ADMINISTER;
+ case DELETE: return CONNECTION_GROUP_DELETE;
+ }
+
+ // If we get here, permission support was not properly implemented
+ throw new UnsupportedOperationException(
+ "Unsupported permission type: " + type);
+
+ }
+
+ /**
+ * Given the type of a connection group, returns the MySQL constant
+ * representing that type.
+ *
+ * @param type The connection group type to look up.
+ * @return The MySQL constant corresponding to the given type.
+ */
+ public static String getConnectionGroupTypeConstant(ConnectionGroup.Type type) {
+
+ // Convert permission type to MySQL constant
+ switch (type) {
+ case ORGANIZATIONAL: return CONNECTION_GROUP_ORGANIZATIONAL;
+ case BALANCING: return CONNECTION_GROUP_BALANCING;
+ }
+
+ // If we get here, permission support was not properly implemented
+ throw new UnsupportedOperationException(
+ "Unsupported connection group type: " + type);
+
+ }
+
+ /**
+ * Given the type of a permission affecting the system, returns the MySQL
+ * constant representing that permission type.
+ *
+ * @param type The type of permission to look up.
+ * @return The MySQL constant corresponding to the given permission type.
+ */
+ public static String getSystemConstant(SystemPermission.Type type) {
+
+ // Convert permission type to MySQL constant
+ switch (type) {
+ case CREATE_USER: return SYSTEM_USER_CREATE;
+ case CREATE_CONNECTION: return SYSTEM_CONNECTION_CREATE;
+ case CREATE_CONNECTION_GROUP: return SYSTEM_CONNECTION_GROUP_CREATE;
+ case ADMINISTER: return SYSTEM_ADMINISTER;
+ }
+
+ // If we get here, permission support was not properly implemented
+ throw new UnsupportedOperationException(
+ "Unsupported permission type: " + type);
+
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLGuacamoleSocket.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLGuacamoleSocket.java
new file mode 100644
index 0000000..340160f
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLGuacamoleSocket.java
@@ -0,0 +1,115 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+
+/**
+ * A MySQL specific wrapper around a ConfiguredGuacamoleSocket.
+ * @author James Muehlner
+ */
+public class MySQLGuacamoleSocket implements GuacamoleSocket {
+
+ /**
+ * Injected ActiveConnectionMap which will contain all active connections.
+ */
+ @Inject
+ private ActiveConnectionMap activeConnectionSet;
+
+ /**
+ * The wrapped socket.
+ */
+ private GuacamoleSocket socket;
+
+ /**
+ * The ID of the history record associated with this instance of the
+ * connection.
+ */
+ private int historyID;
+
+ /**
+ * The ID of the balancing connection group that is being connected to;
+ * null if not used.
+ */
+ private Integer connectionGroupID;
+
+ /**
+ * Initialize this MySQLGuacamoleSocket with the provided GuacamoleSocket.
+ *
+ * @param socket The ConfiguredGuacamoleSocket to wrap.
+ * @param historyID The ID of the history record associated with this
+ * instance of the connection.
+ * @param connectionGroupID The ID of the balancing connection group that is
+ * being connected to; null if not used.
+ */
+ public void init(GuacamoleSocket socket, int connectionID, int userID,
+ int historyID, Integer connectionGroupID) {
+ this.socket = socket;
+ this.historyID = historyID;
+ this.connectionGroupID = connectionGroupID;
+ }
+
+ @Override
+ public GuacamoleReader getReader() {
+ return socket.getReader();
+ }
+
+ @Override
+ public GuacamoleWriter getWriter() {
+ return socket.getWriter();
+ }
+
+ @Override
+ public void close() throws GuacamoleException {
+
+ // Close socket
+ socket.close();
+
+ // Mark this connection as inactive
+ activeConnectionSet.closeConnection(historyID, connectionGroupID);
+ }
+
+ @Override
+ public boolean isOpen() {
+ return socket.isOpen();
+ }
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLUser.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLUser.java
new file mode 100644
index 0000000..37f8f07
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLUser.java
@@ -0,0 +1,193 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+package net.sourceforge.guacamole.net.auth.mysql;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.AbstractUser;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+
+/**
+ * A MySQL based implementation of the User object.
+ * @author James Muehlner
+ */
+public class MySQLUser extends AbstractUser {
+
+ /**
+ * The ID of this user in the database, if any.
+ */
+ private Integer userID;
+
+ /**
+ * The set of current permissions a user has.
+ */
+ private Set<Permission> permissions = new HashSet<Permission>();
+
+ /**
+ * Any newly added permissions that have yet to be committed.
+ */
+ private Set<Permission> newPermissions = new HashSet<Permission>();
+
+ /**
+ * Any newly deleted permissions that have yet to be deleted.
+ */
+ private Set<Permission> removedPermissions = new HashSet<Permission>();
+
+ /**
+ * Creates a new, empty MySQLUser.
+ */
+ public MySQLUser() {
+ }
+
+ /**
+ * Initializes a new MySQLUser having the given username.
+ *
+ * @param name The name to assign to this MySQLUser.
+ */
+ public void init(String name) {
+ init(null, name, null, Collections.EMPTY_SET);
+ }
+
+ /**
+ * Initializes a new MySQLUser, copying all data from the given user
+ * object.
+ *
+ * @param user The user object to copy.
+ * @throws GuacamoleException If an error occurs while reading the user
+ * data in the given object.
+ */
+ public void init(User user) throws GuacamoleException {
+ init(null, user.getUsername(), user.getPassword(), user.getPermissions());
+ }
+
+ /**
+ * Initializes a new MySQLUser initialized from the given data from the
+ * database.
+ *
+ * @param userID The ID of the user in the database, if any.
+ * @param username The username of this user.
+ * @param password The password to assign to this user.
+ * @param permissions The permissions to assign to this user, as
+ * retrieved from the database.
+ */
+ public void init(Integer userID, String username, String password,
+ Set<Permission> permissions) {
+ this.userID = userID;
+ setUsername(username);
+ setPassword(password);
+ this.permissions.addAll(permissions);
+ }
+
+ /**
+ * Get the current set of permissions this user has.
+ * @return the current set of permissions.
+ */
+ public Set<Permission> getCurrentPermissions() {
+ return permissions;
+ }
+
+ /**
+ * Get any new permissions that have yet to be inserted.
+ * @return the new set of permissions.
+ */
+ public Set<Permission> getNewPermissions() {
+ return newPermissions;
+ }
+
+ /**
+ * Get any permissions that have not yet been deleted.
+ * @return the permissions that need to be deleted.
+ */
+ public Set<Permission> getRemovedPermissions() {
+ return removedPermissions;
+ }
+
+ /**
+ * Reset the new and removed permission sets after they are
+ * no longer needed.
+ */
+ public void resetPermissions() {
+ newPermissions.clear();
+ removedPermissions.clear();
+ }
+
+ /**
+ * Returns the ID of this user in the database, if it exists.
+ *
+ * @return The ID of this user in the database, or null if this user
+ * was not retrieved from the database.
+ */
+ public Integer getUserID() {
+ return userID;
+ }
+
+ /**
+ * Sets the ID of this user to the given value.
+ *
+ * @param userID The ID to assign to this user.
+ */
+ public void setUserID(Integer userID) {
+ this.userID = userID;
+ }
+
+ @Override
+ public Set<Permission> getPermissions() throws GuacamoleException {
+ return Collections.unmodifiableSet(permissions);
+ }
+
+ @Override
+ public boolean hasPermission(Permission permission) throws GuacamoleException {
+ return permissions.contains(permission);
+ }
+
+ @Override
+ public void addPermission(Permission permission) throws GuacamoleException {
+ permissions.add(permission);
+ newPermissions.add(permission);
+ removedPermissions.remove(permission);
+ }
+
+ @Override
+ public void removePermission(Permission permission) throws GuacamoleException {
+ permissions.remove(permission);
+ newPermissions.remove(permission);
+ removedPermissions.add(permission);
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLUserContext.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLUserContext.java
new file mode 100644
index 0000000..8323148
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/MySQLUserContext.java
@@ -0,0 +1,108 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import net.sourceforge.guacamole.net.auth.mysql.service.UserService;
+
+/**
+ * The MySQL representation of a UserContext.
+ * @author James Muehlner
+ */
+public class MySQLUserContext implements UserContext {
+
+ /**
+ * The ID of the user owning this context. The permissions of this user
+ * dictate the access given via the user and connection directories.
+ */
+ private int user_id;
+
+ /**
+ * User directory restricted by the permissions of the user associated
+ * with this context.
+ */
+ @Inject
+ private UserDirectory userDirectory;
+
+ /**
+ * The root connection group.
+ */
+ @Inject
+ private MySQLConnectionGroup rootConnectionGroup;
+
+ /**
+ * Service for accessing users.
+ */
+ @Inject
+ private UserService userService;
+
+ /**
+ * Initializes the user and directories associated with this context.
+ *
+ * @param user_id The ID of the user owning this context.
+ */
+ public void init(int user_id) {
+ this.user_id = user_id;
+ userDirectory.init(user_id);
+ rootConnectionGroup.init(null, null,
+ MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER,
+ MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER,
+ ConnectionGroup.Type.ORGANIZATIONAL, user_id);
+ }
+
+ @Override
+ public User self() {
+ return userService.retrieveUser(user_id);
+ }
+
+ @Override
+ public Directory<String, User> getUserDirectory() throws GuacamoleException {
+ return userDirectory;
+ }
+
+ @Override
+ public ConnectionGroup getRootConnectionGroup() throws GuacamoleException {
+ return rootConnectionGroup;
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/UserDirectory.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/UserDirectory.java
new file mode 100644
index 0000000..a37742e
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/UserDirectory.java
@@ -0,0 +1,721 @@
+
+package net.sourceforge.guacamole.net.auth.mysql;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import com.google.inject.Inject;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionGroupPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.SystemPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.UserPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.model.SystemPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.SystemPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.model.UserPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.UserPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionGroupService;
+import net.sourceforge.guacamole.net.auth.mysql.service.ConnectionService;
+import net.sourceforge.guacamole.net.auth.mysql.service.PermissionCheckService;
+import net.sourceforge.guacamole.net.auth.mysql.service.UserService;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionGroupPermission;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+import org.glyptodon.guacamole.net.auth.permission.UserPermission;
+import org.mybatis.guice.transactional.Transactional;
+
+/**
+ * A MySQL based implementation of the User Directory.
+ * @author James Muehlner
+ */
+public class UserDirectory implements Directory<String, User> {
+
+ /**
+ * The ID of the user who this user directory belongs to.
+ * Access is based on his/her permission settings.
+ */
+ private int user_id;
+
+ /**
+ * Service for accessing users.
+ */
+ @Inject
+ private UserService userService;
+
+ /**
+ * Service for accessing connections.
+ */
+ @Inject
+ private ConnectionService connectionService;
+
+ /**
+ * Service for accessing connection groups.
+ */
+ @Inject
+ private ConnectionGroupService connectionGroupService;
+
+ /**
+ * DAO for accessing user permissions, which will be injected.
+ */
+ @Inject
+ private UserPermissionMapper userPermissionDAO;
+
+ /**
+ * DAO for accessing connection permissions, which will be injected.
+ */
+ @Inject
+ private ConnectionPermissionMapper connectionPermissionDAO;
+
+ /**
+ * DAO for accessing connection group permissions, which will be injected.
+ */
+ @Inject
+ private ConnectionGroupPermissionMapper connectionGroupPermissionDAO;
+
+ /**
+ * DAO for accessing system permissions, which will be injected.
+ */
+ @Inject
+ private SystemPermissionMapper systemPermissionDAO;
+
+ /**
+ * Service for checking various permissions, which will be injected.
+ */
+ @Inject
+ private PermissionCheckService permissionCheckService;
+
+ /**
+ * Set the user for this directory.
+ *
+ * @param user_id The ID of the user whose permissions define the visibility
+ * of other users in this directory.
+ */
+ public void init(int user_id) {
+ this.user_id = user_id;
+ }
+
+ @Transactional
+ @Override
+ public org.glyptodon.guacamole.net.auth.User get(String identifier)
+ throws GuacamoleException {
+
+ // Get user
+ MySQLUser user = userService.retrieveUser(identifier);
+
+ // Verify access is granted
+ permissionCheckService.verifyUserAccess(this.user_id,
+ user.getUserID(),
+ MySQLConstants.USER_READ);
+
+ // Return user
+ return userService.retrieveUser(identifier);
+
+ }
+
+ @Transactional
+ @Override
+ public Set<String> getIdentifiers() throws GuacamoleException {
+ return permissionCheckService.retrieveUsernames(user_id,
+ MySQLConstants.USER_READ);
+ }
+
+ @Override
+ @Transactional
+ public void add(org.glyptodon.guacamole.net.auth.User object)
+ throws GuacamoleException {
+
+ String username = object.getUsername().trim();
+ if(username.isEmpty())
+ throw new GuacamoleClientException("The username cannot be blank.");
+
+ // Verify current user has permission to create users
+ permissionCheckService.verifySystemAccess(this.user_id,
+ MySQLConstants.SYSTEM_USER_CREATE);
+ Preconditions.checkNotNull(object);
+
+ // Verify that no user already exists with this username.
+ MySQLUser previousUser = userService.retrieveUser(username);
+ if(previousUser != null)
+ throw new GuacamoleClientException("That username is already in use.");
+
+ // Create new user
+ MySQLUser user = userService.createUser(username, object.getPassword());
+
+ // Create permissions of new user in database
+ createPermissions(user.getUserID(), object.getPermissions());
+
+ // Give the current user full access to the newly created user.
+ UserPermissionKey newUserPermission = new UserPermissionKey();
+ newUserPermission.setUser_id(this.user_id);
+ newUserPermission.setAffected_user_id(user.getUserID());
+
+ // READ permission on new user
+ newUserPermission.setPermission(MySQLConstants.USER_READ);
+ userPermissionDAO.insert(newUserPermission);
+
+ // UPDATE permission on new user
+ newUserPermission.setPermission(MySQLConstants.USER_UPDATE);
+ userPermissionDAO.insert(newUserPermission);
+
+ // DELETE permission on new user
+ newUserPermission.setPermission(MySQLConstants.USER_DELETE);
+ userPermissionDAO.insert(newUserPermission);
+
+ // ADMINISTER permission on new user
+ newUserPermission.setPermission(MySQLConstants.USER_ADMINISTER);
+ userPermissionDAO.insert(newUserPermission);
+
+ }
+
+ /**
+ * Add the given permissions to the given user.
+ *
+ * @param user_id The ID of the user whose permissions should be updated.
+ * @param permissions The permissions to add.
+ * @throws GuacamoleException If an error occurs while updating the
+ * permissions of the given user.
+ */
+ private void createPermissions(int user_id, Set<Permission> permissions) throws GuacamoleException {
+
+ // Partition given permissions by permission type
+ List<UserPermission> newUserPermissions = new ArrayList<UserPermission>();
+ List<ConnectionPermission> newConnectionPermissions = new ArrayList<ConnectionPermission>();
+ List<ConnectionGroupPermission> newConnectionGroupPermissions = new ArrayList<ConnectionGroupPermission>();
+ List<SystemPermission> newSystemPermissions = new ArrayList<SystemPermission>();
+
+ for (Permission permission : permissions) {
+
+ if (permission instanceof UserPermission)
+ newUserPermissions.add((UserPermission) permission);
+
+ else if (permission instanceof ConnectionPermission)
+ newConnectionPermissions.add((ConnectionPermission) permission);
+
+ else if (permission instanceof ConnectionGroupPermission)
+ newConnectionGroupPermissions.add((ConnectionGroupPermission) permission);
+
+ else if (permission instanceof SystemPermission)
+ newSystemPermissions.add((SystemPermission) permission);
+ }
+
+ // Create the new permissions
+ createUserPermissions(user_id, newUserPermissions);
+ createConnectionPermissions(user_id, newConnectionPermissions);
+ createConnectionGroupPermissions(user_id, newConnectionGroupPermissions);
+ createSystemPermissions(user_id, newSystemPermissions);
+
+ }
+
+
+
+ /**
+ * Remove the given permissions from the given user.
+ *
+ * @param user_id The ID of the user whose permissions should be updated.
+ * @param permissions The permissions to remove.
+ * @throws GuacamoleException If an error occurs while updating the
+ * permissions of the given user.
+ */
+ private void removePermissions(int user_id, Set<Permission> permissions)
+ throws GuacamoleException {
+
+ // Partition given permissions by permission type
+ List<UserPermission> removedUserPermissions = new ArrayList<UserPermission>();
+ List<ConnectionPermission> removedConnectionPermissions = new ArrayList<ConnectionPermission>();
+ List<ConnectionGroupPermission> removedConnectionGroupPermissions = new ArrayList<ConnectionGroupPermission>();
+ List<SystemPermission> removedSystemPermissions = new ArrayList<SystemPermission>();
+
+ for (Permission permission : permissions) {
+
+ if (permission instanceof UserPermission)
+ removedUserPermissions.add((UserPermission) permission);
+
+ else if (permission instanceof ConnectionPermission)
+ removedConnectionPermissions.add((ConnectionPermission) permission);
+
+ else if (permission instanceof ConnectionGroupPermission)
+ removedConnectionGroupPermissions.add((ConnectionGroupPermission) permission);
+
+ else if (permission instanceof SystemPermission)
+ removedSystemPermissions.add((SystemPermission) permission);
+ }
+
+ // Delete the removed permissions.
+ deleteUserPermissions(user_id, removedUserPermissions);
+ deleteConnectionPermissions(user_id, removedConnectionPermissions);
+ deleteConnectionGroupPermissions(user_id, removedConnectionGroupPermissions);
+ deleteSystemPermissions(user_id, removedSystemPermissions);
+
+ }
+
+ /**
+ * Create the given user permissions for the given user.
+ *
+ * @param user_id The ID of the user to change the permissions of.
+ * @param permissions The new permissions the given user should have when
+ * this operation completes.
+ * @throws GuacamoleException If permission to alter the access permissions
+ * of affected objects is denied.
+ */
+ private void createUserPermissions(int user_id,
+ Collection<UserPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Get list of administerable user IDs
+ List<Integer> administerableUserIDs =
+ permissionCheckService.retrieveUserIDs(this.user_id,
+ MySQLConstants.USER_ADMINISTER);
+
+ // Get set of usernames corresponding to administerable users
+ Map<String, Integer> administerableUsers =
+ userService.translateUsernames(administerableUserIDs);
+
+ // Insert all given permissions
+ for (UserPermission permission : permissions) {
+
+ // Get original ID
+ Integer affected_id =
+ administerableUsers.get(permission.getObjectIdentifier());
+
+ // Verify that the user actually has permission to administrate
+ // every one of these users
+ if (affected_id == null)
+ throw new GuacamoleSecurityException(
+ "User #" + this.user_id
+ + " does not have permission to administrate user "
+ + permission.getObjectIdentifier());
+
+ // Create new permission
+ UserPermissionKey newPermission = new UserPermissionKey();
+ newPermission.setUser_id(user_id);
+ newPermission.setPermission(MySQLConstants.getUserConstant(permission.getType()));
+ newPermission.setAffected_user_id(affected_id);
+ userPermissionDAO.insert(newPermission);
+
+ }
+
+ }
+
+ /**
+ * Delete permissions having to do with users for a given user.
+ *
+ * @param user_id The ID of the user to change the permissions of.
+ * @param permissions The permissions the given user should no longer have
+ * when this operation completes.
+ * @throws GuacamoleException If permission to alter the access permissions
+ * of affected objects is denied.
+ */
+ private void deleteUserPermissions(int user_id,
+ Collection<UserPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Get list of administerable user IDs
+ List<Integer> administerableUserIDs =
+ permissionCheckService.retrieveUserIDs(this.user_id,
+ MySQLConstants.USER_ADMINISTER);
+
+ // Get set of usernames corresponding to administerable users
+ Map<String, Integer> administerableUsers =
+ userService.translateUsernames(administerableUserIDs);
+
+ // Delete requested permissions
+ for (UserPermission permission : permissions) {
+
+ // Get original ID
+ Integer affected_id =
+ administerableUsers.get(permission.getObjectIdentifier());
+
+ // Verify that the user actually has permission to administrate
+ // every one of these users
+ if (affected_id == null)
+ throw new GuacamoleSecurityException(
+ "User #" + this.user_id
+ + " does not have permission to administrate user "
+ + permission.getObjectIdentifier());
+
+ // Delete requested permission
+ UserPermissionExample userPermissionExample = new UserPermissionExample();
+ userPermissionExample.createCriteria()
+ .andUser_idEqualTo(user_id)
+ .andPermissionEqualTo(MySQLConstants.getUserConstant(permission.getType()))
+ .andAffected_user_idEqualTo(affected_id);
+ userPermissionDAO.deleteByExample(userPermissionExample);
+
+ }
+
+ }
+
+ /**
+ * Create any new permissions having to do with connections for a given
+ * user.
+ *
+ * @param user_id The ID of the user to assign or remove permissions from.
+ * @param permissions The new permissions the user should have after this
+ * operation completes.
+ * @throws GuacamoleException If permission to alter the access permissions
+ * of affected objects is deniedD
+ */
+ private void createConnectionPermissions(int user_id,
+ Collection<ConnectionPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Get list of administerable connection IDs
+ Set<Integer> administerableConnectionIDs = Sets.<Integer>newHashSet(
+ permissionCheckService.retrieveConnectionIDs(this.user_id,
+ MySQLConstants.CONNECTION_ADMINISTER));
+
+ // Insert all given permissions
+ for (ConnectionPermission permission : permissions) {
+
+ // Get original ID
+ Integer connection_id = Integer.valueOf(permission.getObjectIdentifier());
+
+ // Throw exception if permission to administer this connection
+ // is not granted
+ if (!administerableConnectionIDs.contains(connection_id))
+ throw new GuacamoleSecurityException(
+ "User #" + this.user_id
+ + " does not have permission to administrate connection "
+ + permission.getObjectIdentifier());
+
+
+ // Create new permission
+ ConnectionPermissionKey newPermission = new ConnectionPermissionKey();
+ newPermission.setUser_id(user_id);
+ newPermission.setPermission(MySQLConstants.getConnectionConstant(permission.getType()));
+ newPermission.setConnection_id(connection_id);
+ connectionPermissionDAO.insert(newPermission);
+
+ }
+ }
+
+ /**
+ * Create any new permissions having to do with connection groups
+ * for a given user.
+ *
+ * @param user_id The ID of the user to assign or remove permissions from.
+ * @param permissions The new permissions the user should have after this
+ * operation completes.
+ * @throws GuacamoleException If permission to alter the access permissions
+ * of affected objects is deniedD
+ */
+ private void createConnectionGroupPermissions(int user_id,
+ Collection<ConnectionGroupPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Get list of administerable connection group IDs
+ Set<Integer> administerableConnectionGroupIDs = Sets.<Integer>newHashSet(
+ permissionCheckService.retrieveConnectionGroupIDs(this.user_id,
+ MySQLConstants.CONNECTION_GROUP_ADMINISTER));
+
+ // Insert all given permissions
+ for (ConnectionGroupPermission permission : permissions) {
+
+ // Get original ID
+ Integer connection_group_id = Integer.valueOf(permission.getObjectIdentifier());
+
+ // Throw exception if permission to administer this connection group
+ // is not granted
+ if (!administerableConnectionGroupIDs.contains(connection_group_id))
+ throw new GuacamoleSecurityException(
+ "User #" + this.user_id
+ + " does not have permission to administrate connection group"
+ + permission.getObjectIdentifier());
+
+
+ // Create new permission
+ ConnectionGroupPermissionKey newPermission = new ConnectionGroupPermissionKey();
+ newPermission.setUser_id(user_id);
+ newPermission.setPermission(MySQLConstants.getConnectionGroupConstant(permission.getType()));
+ newPermission.setConnection_group_id(connection_group_id);
+ connectionGroupPermissionDAO.insert(newPermission);
+
+ }
+ }
+
+ /**
+ * Delete permissions having to do with connections for a given user.
+ *
+ * @param user_id The ID of the user to change the permissions of.
+ * @param permissions The permissions the given user should no longer have
+ * when this operation completes.
+ * @throws GuacamoleException If permission to alter the access permissions
+ * of affected objects is denied.
+ */
+ private void deleteConnectionPermissions(int user_id,
+ Collection<ConnectionPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Get list of administerable connection IDs
+ Set<Integer> administerableConnectionIDs = Sets.<Integer>newHashSet(
+ permissionCheckService.retrieveConnectionIDs(this.user_id,
+ MySQLConstants.CONNECTION_ADMINISTER));
+
+ // Delete requested permissions
+ for (ConnectionPermission permission : permissions) {
+
+ // Get original ID
+ Integer connection_id = Integer.valueOf(permission.getObjectIdentifier());
+
+ // Verify that the user actually has permission to administrate
+ // every one of these connections
+ if (!administerableConnectionIDs.contains(connection_id))
+ throw new GuacamoleSecurityException(
+ "User #" + this.user_id
+ + " does not have permission to administrate connection "
+ + permission.getObjectIdentifier());
+
+ ConnectionPermissionExample connectionPermissionExample = new ConnectionPermissionExample();
+ connectionPermissionExample.createCriteria()
+ .andUser_idEqualTo(user_id)
+ .andPermissionEqualTo(MySQLConstants.getConnectionConstant(permission.getType()))
+ .andConnection_idEqualTo(connection_id);
+ connectionPermissionDAO.deleteByExample(connectionPermissionExample);
+
+ }
+
+ }
+
+ /**
+ * Delete permissions having to do with connection groups for a given user.
+ *
+ * @param user_id The ID of the user to change the permissions of.
+ * @param permissions The permissions the given user should no longer have
+ * when this operation completes.
+ * @throws GuacamoleException If permission to alter the access permissions
+ * of affected objects is denied.
+ */
+ private void deleteConnectionGroupPermissions(int user_id,
+ Collection<ConnectionGroupPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Get list of administerable connection group IDs
+ Set<Integer> administerableConnectionGroupIDs = Sets.<Integer>newHashSet(
+ permissionCheckService.retrieveConnectionGroupIDs(this.user_id,
+ MySQLConstants.CONNECTION_GROUP_ADMINISTER));
+
+ // Delete requested permissions
+ for (ConnectionGroupPermission permission : permissions) {
+
+ // Get original ID
+ Integer connection_group_id = Integer.valueOf(permission.getObjectIdentifier());
+
+ // Verify that the user actually has permission to administrate
+ // every one of these connection groups
+ if (!administerableConnectionGroupIDs.contains(connection_group_id))
+ throw new GuacamoleSecurityException(
+ "User #" + this.user_id
+ + " does not have permission to administrate connection group"
+ + permission.getObjectIdentifier());
+
+ ConnectionGroupPermissionExample connectionGroupPermissionExample = new ConnectionGroupPermissionExample();
+ connectionGroupPermissionExample.createCriteria()
+ .andUser_idEqualTo(user_id)
+ .andPermissionEqualTo(MySQLConstants.getConnectionGroupConstant(permission.getType()))
+ .andConnection_group_idEqualTo(connection_group_id);
+ connectionGroupPermissionDAO.deleteByExample(connectionGroupPermissionExample);
+
+ }
+
+ }
+
+ /**
+ * Create any new system permissions for a given user. All permissions in
+ * the given list will be inserted.
+ *
+ * @param user_id The ID of the user whose permissions should be updated.
+ * @param permissions The new system permissions that the given user should
+ * have when this operation completes.
+ * @throws GuacamoleException If permission to administer system permissions
+ * is denied.
+ */
+ private void createSystemPermissions(int user_id,
+ Collection<SystemPermission> permissions) throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if(permissions.isEmpty())
+ return;
+
+ // Only a system administrator can add system permissions.
+ permissionCheckService.verifySystemAccess(
+ this.user_id, SystemPermission.Type.ADMINISTER.name());
+
+ // Insert all requested permissions
+ for (SystemPermission permission : permissions) {
+
+ // Insert permission
+ SystemPermissionKey newSystemPermission = new SystemPermissionKey();
+ newSystemPermission.setUser_id(user_id);
+ newSystemPermission.setPermission(MySQLConstants.getSystemConstant(permission.getType()));
+ systemPermissionDAO.insert(newSystemPermission);
+
+ }
+
+ }
+
+ /**
+ * Delete system permissions for a given user. All permissions in
+ * the given list will be removed from the user.
+ *
+ * @param user_id The ID of the user whose permissions should be updated.
+ * @param permissions The permissions the given user should no longer have
+ * when this operation completes.
+ * @throws GuacamoleException If the permissions specified could not be
+ * removed due to system restrictions.
+ */
+ private void deleteSystemPermissions(int user_id,
+ Collection<SystemPermission> permissions)
+ throws GuacamoleException {
+
+ // If no permissions given, stop now
+ if (permissions.isEmpty())
+ return;
+
+ // Prevent self-de-adminifying
+ if (user_id == this.user_id)
+ throw new GuacamoleClientException("Removing your own administrative permissions is not allowed.");
+
+ // Build list of requested system permissions
+ List<String> systemPermissionTypes = new ArrayList<String>();
+ for (SystemPermission permission : permissions)
+ systemPermissionTypes.add(MySQLConstants.getSystemConstant(permission.getType()));
+
+ // Delete the requested system permissions for this user
+ SystemPermissionExample systemPermissionExample = new SystemPermissionExample();
+ systemPermissionExample.createCriteria().andUser_idEqualTo(user_id)
+ .andPermissionIn(systemPermissionTypes);
+ systemPermissionDAO.deleteByExample(systemPermissionExample);
+
+ }
+
+ @Override
+ @Transactional
+ public void update(org.glyptodon.guacamole.net.auth.User object)
+ throws GuacamoleException {
+
+ // If user not actually from this auth provider, we can't handle updated
+ // permissions.
+ if (!(object instanceof MySQLUser))
+ throw new GuacamoleException("User not from database.");
+
+ MySQLUser mySQLUser = (MySQLUser) object;
+
+ // Validate permission to update this user is granted
+ permissionCheckService.verifyUserAccess(this.user_id,
+ mySQLUser.getUserID(),
+ MySQLConstants.USER_UPDATE);
+
+ // Update the user in the database
+ userService.updateUser(mySQLUser);
+
+ // Update permissions in database
+ createPermissions(mySQLUser.getUserID(), mySQLUser.getNewPermissions());
+ removePermissions(mySQLUser.getUserID(), mySQLUser.getRemovedPermissions());
+
+ // The appropriate permissions have been inserted and deleted, so
+ // reset the new and removed permission sets.
+ mySQLUser.resetPermissions();
+
+ }
+
+ @Override
+ @Transactional
+ public void remove(String identifier) throws GuacamoleException {
+
+ // Get user pending deletion
+ MySQLUser user = userService.retrieveUser(identifier);
+
+ // Prevent self-deletion
+ if (user.getUserID() == this.user_id)
+ throw new GuacamoleClientException("Deleting your own user is not allowed.");
+
+ // Validate current user has permission to remove the specified user
+ permissionCheckService.verifyUserAccess(this.user_id,
+ user.getUserID(),
+ MySQLConstants.USER_DELETE);
+
+ // Delete specified user
+ userService.deleteUser(user.getUserID());
+
+ }
+
+ @Override
+ public void move(String identifier, Directory<String, User> groupIdentifier)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/package-info.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/package-info.java
new file mode 100644
index 0000000..81f802b
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Base classes which support the MySQL authentication provider, including
+ * the authentication provider itself.
+ */
+package net.sourceforge.guacamole.net.auth.mysql;
+
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/properties/MySQLGuacamoleProperties.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/properties/MySQLGuacamoleProperties.java
new file mode 100644
index 0000000..6f457a1
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/properties/MySQLGuacamoleProperties.java
@@ -0,0 +1,124 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+package net.sourceforge.guacamole.net.auth.mysql.properties;
+
+import org.glyptodon.guacamole.properties.BooleanGuacamoleProperty;
+import org.glyptodon.guacamole.properties.IntegerGuacamoleProperty;
+import org.glyptodon.guacamole.properties.StringGuacamoleProperty;
+
+/**
+ * Properties used by the MySQL Authentication plugin.
+ * @author James Muehlner
+ */
+public class MySQLGuacamoleProperties {
+
+ /**
+ * This class should not be instantiated.
+ */
+ private MySQLGuacamoleProperties() {}
+
+ /**
+ * The URL of the MySQL server hosting the guacamole authentication tables.
+ */
+ public static final StringGuacamoleProperty MYSQL_HOSTNAME = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-hostname"; }
+
+ };
+
+ /**
+ * The port of the MySQL server hosting the guacamole authentication tables.
+ */
+ public static final IntegerGuacamoleProperty MYSQL_PORT = new IntegerGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-port"; }
+
+ };
+
+ /**
+ * The name of the MySQL database containing the guacamole authentication tables.
+ */
+ public static final StringGuacamoleProperty MYSQL_DATABASE = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-database"; }
+
+ };
+
+ /**
+ * The username used to authenticate to the MySQL database containing the guacamole authentication tables.
+ */
+ public static final StringGuacamoleProperty MYSQL_USERNAME = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-username"; }
+
+ };
+
+ /**
+ * The password used to authenticate to the MySQL database containing the guacamole authentication tables.
+ */
+ public static final StringGuacamoleProperty MYSQL_PASSWORD = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-password"; }
+
+ };
+
+ /**
+ * Whether or not multiple users accessing the same connection at the same time should be disallowed.
+ */
+ public static final BooleanGuacamoleProperty MYSQL_DISALLOW_SIMULTANEOUS_CONNECTIONS = new BooleanGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-disallow-simultaneous-connections"; }
+
+ };
+
+ /**
+ * Whether or not the same user accessing the same connection or connection group at the same time should be disallowed.
+ */
+ public static final BooleanGuacamoleProperty MYSQL_DISALLOW_DUPLICATE_CONNECTIONS = new BooleanGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "mysql-disallow-duplicate-connections"; }
+
+ };
+
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/properties/package-info.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/properties/package-info.java
new file mode 100644
index 0000000..d327a33
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/properties/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Properties which control the configuration of the MySQL authentication
+ * provider.
+ */
+package net.sourceforge.guacamole.net.auth.mysql.properties;
+
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/ConnectionGroupService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/ConnectionGroupService.java
new file mode 100644
index 0000000..f4954cb
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/ConnectionGroupService.java
@@ -0,0 +1,411 @@
+
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import net.sourceforge.guacamole.net.auth.mysql.ActiveConnectionMap;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConnection;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConnectionGroup;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConstants;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionGroupMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroup;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupExample.Criteria;
+import net.sourceforge.guacamole.net.auth.mysql.properties.MySQLGuacamoleProperties;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+
+/**
+ * Service which provides convenience methods for creating, retrieving, and
+ * manipulating connection groups.
+ *
+ * @author James Muehlner
+ */
+public class ConnectionGroupService {
+
+ /**
+ * Service for managing connections.
+ */
+ @Inject
+ private ConnectionService connectionService;
+
+ /**
+ * DAO for accessing connection groups.
+ */
+ @Inject
+ private ConnectionGroupMapper connectionGroupDAO;
+
+ /**
+ * Provider which creates MySQLConnectionGroups.
+ */
+ @Inject
+ private Provider<MySQLConnectionGroup> mysqlConnectionGroupProvider;
+
+ /**
+ * The map of all active connections.
+ */
+ @Inject
+ private ActiveConnectionMap activeConnectionMap;
+
+
+ /**
+ * Retrieves the connection group having the given
+ * name from the database.
+ *
+ * @param name The name of the connection to return.
+ * @param parentID The ID of the parent connection group.
+ * @param userID The ID of the user who queried this connection group.
+ * @return The connection having the given name, or null if no such
+ * connection group could be found.
+ */
+ public MySQLConnectionGroup retrieveConnectionGroup(String name, Integer parentID,
+ int userID) {
+
+ // Create criteria
+ ConnectionGroupExample example = new ConnectionGroupExample();
+ Criteria criteria = example.createCriteria().andConnection_group_nameEqualTo(name);
+ if(parentID != null)
+ criteria.andParent_idEqualTo(parentID);
+ else
+ criteria.andParent_idIsNull();
+
+ // Query connection group by name and parentID
+ List<ConnectionGroup> connectionGroups =
+ connectionGroupDAO.selectByExample(example);
+
+ // If no connection group found, return null
+ if(connectionGroups.isEmpty())
+ return null;
+
+ // Otherwise, return found connection
+ return toMySQLConnectionGroup(connectionGroups.get(0), userID);
+
+ }
+
+ /**
+ * Retrieves the connection group having the given unique identifier
+ * from the database.
+ *
+ * @param uniqueIdentifier The unique identifier of the connection group to retrieve.
+ * @param userID The ID of the user who queried this connection group.
+ * @return The connection group having the given unique identifier,
+ * or null if no such connection group was found.
+ */
+ public MySQLConnectionGroup retrieveConnectionGroup(String uniqueIdentifier,
+ int userID) throws GuacamoleException {
+
+ // The unique identifier for a MySQLConnectionGroup is the database ID
+ Integer connectionGroupID = null;
+
+ // Try to parse the connectionID if it's not the root group
+ if(!MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER.equals(uniqueIdentifier)) {
+ try {
+ connectionGroupID = Integer.parseInt(uniqueIdentifier);
+ } catch(NumberFormatException e) {
+ throw new GuacamoleException("Invalid connection group ID.");
+ }
+ }
+
+ return retrieveConnectionGroup(connectionGroupID, userID);
+ }
+
+ /**
+ * Retrieves the connection group having the given ID from the database.
+ *
+ * @param id The ID of the connection group to retrieve.
+ * @param userID The ID of the user who queried this connection.
+ * @return The connection group having the given ID, or null if no such
+ * connection was found.
+ */
+ public MySQLConnectionGroup retrieveConnectionGroup(Integer id, int userID) {
+
+ // This is the root connection group, so just create it here
+ if(id == null) {
+ MySQLConnectionGroup connectionGroup = mysqlConnectionGroupProvider.get();
+ connectionGroup.init(null, null,
+ MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER,
+ MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER,
+ org.glyptodon.guacamole.net.auth.ConnectionGroup.Type.ORGANIZATIONAL,
+ userID);
+
+ return connectionGroup;
+ }
+
+ // Query connection by ID
+ ConnectionGroup connectionGroup = connectionGroupDAO.selectByPrimaryKey(id);
+
+ // If no connection found, return null
+ if(connectionGroup == null)
+ return null;
+
+ // Otherwise, return found connection
+ return toMySQLConnectionGroup(connectionGroup, userID);
+ }
+
+
+ /**
+ * Connect to the connection within the given group with the lowest number
+ * of currently active users.
+ *
+ * @param connection The group to load balance across.
+ * @param info The information to use when performing the connection
+ * handshake.
+ * @param userID The ID of the user who is connecting to the socket.
+ * @return The connected socket.
+ * @throws GuacamoleException If an error occurs while connecting the
+ * socket.
+ */
+ public GuacamoleSocket connect(MySQLConnectionGroup group,
+ GuacamoleClientInformation info, int userID) throws GuacamoleException {
+
+ // Get all connections in the group.
+ List<Integer> connectionIDs = connectionService.getAllConnectionIDs
+ (group.getConnectionGroupID());
+
+ // Get the least used connection.
+ Integer leastUsedConnectionID =
+ activeConnectionMap.getLeastUsedConnection(connectionIDs);
+
+ if(leastUsedConnectionID == null)
+ throw new GuacamoleException("No connections found in group.");
+
+ if(GuacamoleProperties.getProperty(
+ MySQLGuacamoleProperties.MYSQL_DISALLOW_SIMULTANEOUS_CONNECTIONS, false)
+ && activeConnectionMap.isActive(leastUsedConnectionID))
+ throw new GuacamoleClientException
+ ("Cannot connect. All connections are in use.");
+
+ if(GuacamoleProperties.getProperty(
+ MySQLGuacamoleProperties.MYSQL_DISALLOW_DUPLICATE_CONNECTIONS, true)
+ && activeConnectionMap.isConnectionGroupUserActive(group.getConnectionGroupID(), userID))
+ throw new GuacamoleClientException
+ ("Cannot connect. Connection group already in use by this user.");
+
+ // Get the connection
+ MySQLConnection connection = connectionService
+ .retrieveConnection(leastUsedConnectionID, userID);
+
+ // Connect to the connection
+ return connectionService.connect(connection, info, userID, group.getConnectionGroupID());
+ }
+
+ /**
+ * Returns a list of the IDs of all connection groups with a given parent ID.
+ * @param parentID The ID of the parent for all the queried connection groups.
+ * @return a list of the IDs of all connection groups with a given parent ID.
+ */
+ public List<Integer> getAllConnectionGroupIDs(Integer parentID) {
+
+ // Create criteria
+ ConnectionGroupExample example = new ConnectionGroupExample();
+ Criteria criteria = example.createCriteria();
+
+ if(parentID != null)
+ criteria.andParent_idEqualTo(parentID);
+ else
+ criteria.andParent_idIsNull();
+
+ // Query the connections
+ List<ConnectionGroup> connectionGroups = connectionGroupDAO.selectByExample(example);
+
+ // List of IDs of connections with the given parent
+ List<Integer> connectionGroupIDs = new ArrayList<Integer>();
+
+ for(ConnectionGroup connectionGroup : connectionGroups) {
+ connectionGroupIDs.add(connectionGroup.getConnection_group_id());
+ }
+
+ return connectionGroupIDs;
+ }
+
+ /**
+ * Get the identifiers of all the connection groups defined in the system
+ * with a certain parentID.
+ *
+ * @return A Set of identifiers of all the connection groups defined
+ * in the system with the given parentID.
+ */
+ public Set<String> getAllConnectionGroupIdentifiers(Integer parentID) {
+
+ // Set of all present connection identifiers
+ Set<String> identifiers = new HashSet<String>();
+
+ // Set up Criteria
+ ConnectionGroupExample example = new ConnectionGroupExample();
+ Criteria criteria = example.createCriteria();
+ if(parentID != null)
+ criteria.andParent_idEqualTo(parentID);
+ else
+ criteria.andParent_idIsNull();
+
+ // Query connection identifiers
+ List<ConnectionGroup> connectionGroups =
+ connectionGroupDAO.selectByExample(example);
+ for (ConnectionGroup connectionGroup : connectionGroups)
+ identifiers.add(String.valueOf(connectionGroup.getConnection_group_id()));
+
+ return identifiers;
+
+ }
+
+ /**
+ * Convert the given database-retrieved Connection into a MySQLConnection.
+ * The parameters of the given connection will be read and added to the
+ * MySQLConnection in the process.
+ *
+ * @param connection The connection to convert.
+ * @param userID The user who queried this connection.
+ * @return A new MySQLConnection containing all data associated with the
+ * specified connection.
+ */
+ private MySQLConnectionGroup toMySQLConnectionGroup(ConnectionGroup connectionGroup, int userID) {
+
+ // Create new MySQLConnection from retrieved data
+ MySQLConnectionGroup mySQLConnectionGroup = mysqlConnectionGroupProvider.get();
+
+ String mySqlType = connectionGroup.getType();
+ org.glyptodon.guacamole.net.auth.ConnectionGroup.Type authType;
+
+ if(mySqlType.equals(MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL))
+ authType = org.glyptodon.guacamole.net.auth.ConnectionGroup.Type.ORGANIZATIONAL;
+ else
+ authType = org.glyptodon.guacamole.net.auth.ConnectionGroup.Type.BALANCING;
+
+ mySQLConnectionGroup.init(
+ connectionGroup.getConnection_group_id(),
+ connectionGroup.getParent_id(),
+ connectionGroup.getConnection_group_name(),
+ Integer.toString(connectionGroup.getConnection_group_id()),
+ authType,
+ userID
+ );
+
+ return mySQLConnectionGroup;
+
+ }
+
+ /**
+ * Get the connection group IDs of all the connection groups defined in the system.
+ *
+ * @return A list of connection group IDs of all the connection groups defined in the system.
+ */
+ public List<Integer> getAllConnectionGroupIDs() {
+
+ // Set of all present connection group IDs
+ List<Integer> connectionGroupIDs = new ArrayList<Integer>();
+
+ // Query all connection IDs
+ List<ConnectionGroup> connections =
+ connectionGroupDAO.selectByExample(new ConnectionGroupExample());
+ for (ConnectionGroup connection : connections)
+ connectionGroupIDs.add(connection.getConnection_group_id());
+
+ return connectionGroupIDs;
+
+ }
+
+ /**
+ * Creates a new connection group having the given name and protocol.
+ *
+ * @param name The name to assign to the new connection group.
+ * @param userID The ID of the user who created this connection group.
+ * @param Type The type of the new connection group.
+ * @return A new MySQLConnectionGroup containing the data of the newly created
+ * connection group.
+ */
+ public MySQLConnectionGroup createConnectionGroup(String name, int userID,
+ Integer parentID, String type) {
+
+ // Initialize database connection
+ ConnectionGroup connectionGroup = new ConnectionGroup();
+ connectionGroup.setConnection_group_name(name);
+ connectionGroup.setParent_id(parentID);
+ connectionGroup.setType(type);
+
+ // Create connection
+ connectionGroupDAO.insert(connectionGroup);
+ return toMySQLConnectionGroup(connectionGroup, userID);
+
+ }
+
+ /**
+ * Updates the connection group in the database corresponding to the given
+ * MySQLConnectionGroup.
+ *
+ * @param mySQLConnectionGroup The MySQLConnectionGroup to update (save)
+ * to the database.
+ * This connection must already exist.
+ */
+ public void updateConnectionGroup(MySQLConnectionGroup mySQLConnectionGroup) {
+
+ // Populate connection
+ ConnectionGroup connectionGroup = new ConnectionGroup();
+ connectionGroup.setConnection_group_id(mySQLConnectionGroup.getConnectionGroupID());
+ connectionGroup.setParent_id(mySQLConnectionGroup.getParentID());
+ connectionGroup.setConnection_group_name(mySQLConnectionGroup.getName());
+
+ switch(mySQLConnectionGroup.getType()) {
+ case BALANCING :
+ connectionGroup.setType(MySQLConstants.CONNECTION_GROUP_BALANCING);
+ break;
+ case ORGANIZATIONAL:
+ connectionGroup.setType(MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL);
+ break;
+ }
+
+ // Update the connection group in the database
+ connectionGroupDAO.updateByPrimaryKey(connectionGroup);
+
+ }
+
+ /**
+ * Deletes the connection group having the given ID from the database.
+ * @param id The ID of the connection group to delete.
+ */
+ public void deleteConnectionGroup(int id) {
+ connectionGroupDAO.deleteByPrimaryKey(id);
+ }
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/ConnectionService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/ConnectionService.java
new file mode 100644
index 0000000..e1c0b5c
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/ConnectionService.java
@@ -0,0 +1,490 @@
+
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.InetGuacamoleSocket;
+import org.glyptodon.guacamole.net.SSLGuacamoleSocket;
+import net.sourceforge.guacamole.net.auth.mysql.ActiveConnectionMap;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConnection;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConnectionRecord;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLGuacamoleSocket;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionHistoryMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionParameterMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.Connection;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionExample.Criteria;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionHistory;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionHistoryExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionParameter;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionParameterExample;
+import net.sourceforge.guacamole.net.auth.mysql.properties.MySQLGuacamoleProperties;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.glyptodon.guacamole.protocol.ConfiguredGuacamoleSocket;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.apache.ibatis.session.RowBounds;
+
+/**
+ * Service which provides convenience methods for creating, retrieving, and
+ * manipulating connections.
+ *
+ * @author Michael Jumper, James Muehlner
+ */
+public class ConnectionService {
+
+ /**
+ * DAO for accessing connections.
+ */
+ @Inject
+ private ConnectionMapper connectionDAO;
+
+ /**
+ * DAO for accessing connection parameters.
+ */
+ @Inject
+ private ConnectionParameterMapper connectionParameterDAO;
+
+ /**
+ * DAO for accessing connection history.
+ */
+ @Inject
+ private ConnectionHistoryMapper connectionHistoryDAO;
+
+ /**
+ * Provider which creates MySQLConnections.
+ */
+ @Inject
+ private Provider<MySQLConnection> mySQLConnectionProvider;
+
+ /**
+ * Provider which creates MySQLGuacamoleSockets.
+ */
+ @Inject
+ private Provider<MySQLGuacamoleSocket> mySQLGuacamoleSocketProvider;
+
+ /**
+ * Map of all currently active connections.
+ */
+ @Inject
+ private ActiveConnectionMap activeConnectionMap;
+
+ /**
+ * Service managing users.
+ */
+ @Inject
+ private UserService userService;
+
+ /**
+ * Retrieves the connection having the given name from the database.
+ *
+ * @param name The name of the connection to return.
+ * @param parentID The ID of the parent connection group.
+ * @param userID The ID of the user who queried this connection.
+ * @return The connection having the given name, or null if no such
+ * connection could be found.
+ */
+ public MySQLConnection retrieveConnection(String name, Integer parentID,
+ int userID) {
+
+ // Create criteria
+ ConnectionExample example = new ConnectionExample();
+ Criteria criteria = example.createCriteria().andConnection_nameEqualTo(name);
+ if(parentID != null)
+ criteria.andParent_idEqualTo(parentID);
+ else
+ criteria.andParent_idIsNull();
+
+ // Query connection by name and parentID
+ List<Connection> connections =
+ connectionDAO.selectByExample(example);
+
+ // If no connection found, return null
+ if(connections.isEmpty())
+ return null;
+
+ // Otherwise, return found connection
+ return toMySQLConnection(connections.get(0), userID);
+
+ }
+
+ /**
+ * Retrieves the connection having the given unique identifier
+ * from the database.
+ *
+ * @param uniqueIdentifier The unique identifier of the connection to retrieve.
+ * @param userID The ID of the user who queried this connection.
+ * @return The connection having the given unique identifier,
+ * or null if no such connection was found.
+ */
+ public MySQLConnection retrieveConnection(String uniqueIdentifier, int userID) {
+
+ // The unique identifier for a MySQLConnection is the database ID
+ int connectionID;
+ try {
+ connectionID = Integer.parseInt(uniqueIdentifier);
+ } catch(NumberFormatException e) {
+ // Invalid number means it can't be a DB record; not found
+ return null;
+ }
+
+ return retrieveConnection(connectionID, userID);
+ }
+
+ /**
+ * Retrieves the connection having the given ID from the database.
+ *
+ * @param id The ID of the connection to retrieve.
+ * @param userID The ID of the user who queried this connection.
+ * @return The connection having the given ID, or null if no such
+ * connection was found.
+ */
+ public MySQLConnection retrieveConnection(int id, int userID) {
+
+ // Query connection by ID
+ Connection connection = connectionDAO.selectByPrimaryKey(id);
+
+ // If no connection found, return null
+ if(connection == null)
+ return null;
+
+ // Otherwise, return found connection
+ return toMySQLConnection(connection, userID);
+ }
+
+ /**
+ * Returns a list of the IDs of all connections with a given parent ID.
+ * @param parentID The ID of the parent for all the queried connections.
+ * @return a list of the IDs of all connections with a given parent ID.
+ */
+ public List<Integer> getAllConnectionIDs(Integer parentID) {
+
+ // Create criteria
+ ConnectionExample example = new ConnectionExample();
+ Criteria criteria = example.createCriteria();
+
+ if(parentID != null)
+ criteria.andParent_idEqualTo(parentID);
+ else
+ criteria.andParent_idIsNull();
+
+ // Query the connections
+ List<Connection> connections = connectionDAO.selectByExample(example);
+
+ // List of IDs of connections with the given parent
+ List<Integer> connectionIDs = new ArrayList<Integer>();
+
+ for(Connection connection : connections) {
+ connectionIDs.add(connection.getConnection_id());
+ }
+
+ return connectionIDs;
+ }
+
+ /**
+ * Convert the given database-retrieved Connection into a MySQLConnection.
+ * The parameters of the given connection will be read and added to the
+ * MySQLConnection in the process.
+ *
+ * @param connection The connection to convert.
+ * @param userID The user who queried this connection.
+ * @return A new MySQLConnection containing all data associated with the
+ * specified connection.
+ */
+ private MySQLConnection toMySQLConnection(Connection connection, int userID) {
+
+ // Build configuration
+ GuacamoleConfiguration config = new GuacamoleConfiguration();
+
+ // Query parameters for configuration
+ ConnectionParameterExample connectionParameterExample = new ConnectionParameterExample();
+ connectionParameterExample.createCriteria().andConnection_idEqualTo(connection.getConnection_id());
+ List<ConnectionParameter> connectionParameters =
+ connectionParameterDAO.selectByExample(connectionParameterExample);
+
+ // Set protocol
+ config.setProtocol(connection.getProtocol());
+
+ // Set all values for all parameters
+ for (ConnectionParameter parameter : connectionParameters)
+ config.setParameter(parameter.getParameter_name(),
+ parameter.getParameter_value());
+
+ // Create new MySQLConnection from retrieved data
+ MySQLConnection mySQLConnection = mySQLConnectionProvider.get();
+ mySQLConnection.init(
+ connection.getConnection_id(),
+ connection.getParent_id(),
+ connection.getConnection_name(),
+ Integer.toString(connection.getConnection_id()),
+ config,
+ retrieveHistory(connection.getConnection_id()),
+ userID
+ );
+
+ return mySQLConnection;
+
+ }
+
+ /**
+ * Retrieves the history of the connection having the given ID.
+ *
+ * @param connectionID The ID of the connection to retrieve the history of.
+ * @return A list of MySQLConnectionRecord documenting the history of this
+ * connection.
+ */
+ public List<MySQLConnectionRecord> retrieveHistory(int connectionID) {
+
+ // Retrieve history records relating to given connection ID
+ ConnectionHistoryExample example = new ConnectionHistoryExample();
+ example.createCriteria().andConnection_idEqualTo(connectionID);
+
+ // We want to return the newest records first
+ example.setOrderByClause("start_date DESC");
+
+ // Set the maximum number of history records returned to 100
+ RowBounds rowBounds = new RowBounds(0, 100);
+
+ // Retrieve all connection history entries
+ List<ConnectionHistory> connectionHistories =
+ connectionHistoryDAO.selectByExampleWithRowbounds(example, rowBounds);
+
+ // Convert history entries to connection records
+ List<MySQLConnectionRecord> connectionRecords = new ArrayList<MySQLConnectionRecord>();
+ Set<Integer> userIDSet = new HashSet<Integer>();
+ for(ConnectionHistory history : connectionHistories) {
+ userIDSet.add(history.getUser_id());
+ }
+
+ // Get all the usernames for the users who are in the history
+ Map<Integer, String> usernameMap = userService.retrieveUsernames(userIDSet);
+
+ // Create the new ConnectionRecords
+ for(ConnectionHistory history : connectionHistories) {
+ Date startDate = history.getStart_date();
+ Date endDate = history.getEnd_date();
+ String username = usernameMap.get(history.getUser_id());
+ MySQLConnectionRecord connectionRecord = new MySQLConnectionRecord(startDate, endDate, username);
+ connectionRecords.add(connectionRecord);
+ }
+
+ return connectionRecords;
+ }
+
+
+
+ /**
+ * Create a MySQLGuacamoleSocket using the provided connection.
+ *
+ * @param connection The connection to use when connecting the socket.
+ * @param info The information to use when performing the connection
+ * handshake.
+ * @param userID The ID of the user who is connecting to the socket.
+ * @param connectionGroupID The ID of the balancing connection group that is
+ * being connected to; null if not used.
+ * @return The connected socket.
+ * @throws GuacamoleException If an error occurs while connecting the
+ * socket.
+ */
+ public MySQLGuacamoleSocket connect(MySQLConnection connection,
+ GuacamoleClientInformation info, int userID, Integer connectionGroupID)
+ throws GuacamoleException {
+
+ // If the given connection is active, and multiple simultaneous
+ // connections are not allowed, disallow connection
+ if(GuacamoleProperties.getProperty(
+ MySQLGuacamoleProperties.MYSQL_DISALLOW_SIMULTANEOUS_CONNECTIONS, false)
+ && activeConnectionMap.isActive(connection.getConnectionID()))
+ throw new GuacamoleClientException("Cannot connect. This connection is in use.");
+
+ if(GuacamoleProperties.getProperty(
+ MySQLGuacamoleProperties.MYSQL_DISALLOW_DUPLICATE_CONNECTIONS, true)
+ && activeConnectionMap.isConnectionUserActive(connection.getConnectionID(), userID))
+ throw new GuacamoleClientException
+ ("Cannot connect. Connection already in use by this user.");
+
+ // Get guacd connection information
+ String host = GuacamoleProperties.getRequiredProperty(GuacamoleProperties.GUACD_HOSTNAME);
+ int port = GuacamoleProperties.getRequiredProperty(GuacamoleProperties.GUACD_PORT);
+
+ // Get socket
+ GuacamoleSocket socket;
+ if (GuacamoleProperties.getProperty(GuacamoleProperties.GUACD_SSL, false))
+ socket = new ConfiguredGuacamoleSocket(
+ new SSLGuacamoleSocket(host, port),
+ connection.getConfiguration(), info
+ );
+ else
+ socket = new ConfiguredGuacamoleSocket(
+ new InetGuacamoleSocket(host, port),
+ connection.getConfiguration(), info
+ );
+
+ // Mark this connection as active
+ int historyID = activeConnectionMap.openConnection(connection.getConnectionID(),
+ userID, connectionGroupID);
+
+ // Return new MySQLGuacamoleSocket
+ MySQLGuacamoleSocket mySQLGuacamoleSocket = mySQLGuacamoleSocketProvider.get();
+ mySQLGuacamoleSocket.init(socket, connection.getConnectionID(), userID,
+ historyID, connectionGroupID);
+
+ return mySQLGuacamoleSocket;
+
+ }
+
+ /**
+ * Creates a new connection having the given name and protocol.
+ *
+ * @param name The name to assign to the new connection.
+ * @param protocol The protocol to assign to the new connection.
+ * @param userID The ID of the user who created this connection.
+ * @param parentID The ID of the parent connection group.
+ * @return A new MySQLConnection containing the data of the newly created
+ * connection.
+ */
+ public MySQLConnection createConnection(String name, String protocol,
+ int userID, Integer parentID) {
+
+ // Initialize database connection
+ Connection connection = new Connection();
+ connection.setConnection_name(name);
+ connection.setProtocol(protocol);
+ connection.setParent_id(parentID);
+
+ // Create connection
+ connectionDAO.insert(connection);
+ return toMySQLConnection(connection, userID);
+
+ }
+
+ /**
+ * Deletes the connection having the given ID from the database.
+ * @param id The ID of the connection to delete.
+ */
+ public void deleteConnection(int id) {
+ connectionDAO.deleteByPrimaryKey(id);
+ }
+
+ /**
+ * Updates the connection in the database corresponding to the given
+ * MySQLConnection.
+ *
+ * @param mySQLConnection The MySQLConnection to update (save) to the
+ * database. This connection must already exist.
+ */
+ public void updateConnection(MySQLConnection mySQLConnection) {
+
+ // Populate connection
+ Connection connection = new Connection();
+ connection.setConnection_id(mySQLConnection.getConnectionID());
+ connection.setParent_id(mySQLConnection.getParentID());
+ connection.setConnection_name(mySQLConnection.getName());
+ connection.setProtocol(mySQLConnection.getConfiguration().getProtocol());
+
+ // Update the connection in the database
+ connectionDAO.updateByPrimaryKey(connection);
+
+ }
+
+ /**
+ * Get the identifiers of all the connections defined in the system
+ * with a certain parentID.
+ *
+ * @return A Set of identifiers of all the connections defined in the system
+ * with the given parentID.
+ */
+ public Set<String> getAllConnectionIdentifiers(Integer parentID) {
+
+ // Set of all present connection identifiers
+ Set<String> identifiers = new HashSet<String>();
+
+ // Set up Criteria
+ ConnectionExample example = new ConnectionExample();
+ Criteria criteria = example.createCriteria();
+ if(parentID != null)
+ criteria.andParent_idEqualTo(parentID);
+ else
+ criteria.andParent_idIsNull();
+
+ // Query connection identifiers
+ List<Connection> connections =
+ connectionDAO.selectByExample(example);
+ for (Connection connection : connections)
+ identifiers.add(String.valueOf(connection.getConnection_id()));
+
+ return identifiers;
+
+ }
+
+ /**
+ * Get the connection IDs of all the connections defined in the system
+ * with a certain parent connection group.
+ *
+ * @return A list of connection IDs of all the connections defined in the system.
+ */
+ public List<Integer> getAllConnectionIDs() {
+
+ // Set of all present connection IDs
+ List<Integer> connectionIDs = new ArrayList<Integer>();
+
+ // Create the criteria
+ ConnectionExample example = new ConnectionExample();
+
+ // Query the connections
+ List<Connection> connections =
+ connectionDAO.selectByExample(example);
+ for (Connection connection : connections)
+ connectionIDs.add(connection.getConnection_id());
+
+ return connectionIDs;
+
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/PasswordEncryptionService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/PasswordEncryptionService.java
new file mode 100644
index 0000000..0989a1b
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/PasswordEncryptionService.java
@@ -0,0 +1,69 @@
+
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A service to perform password encryption and checking.
+ * @author James Muehlner
+ */
+public interface PasswordEncryptionService {
+
+ /**
+ * Checks whether the provided, unhashed password matches the given
+ * hash/salt pair.
+ *
+ * @param password The unhashed password to validate.
+ * @param hashedPassword The hashed password to compare the given password
+ * against.
+ * @param salt The salt used when the hashed password given was created.
+ * @return true if the provided credentials match the values given, false
+ * otherwise.
+ */
+ public boolean checkPassword(String password, byte[] hashedPassword,
+ byte[] salt);
+
+ /**
+ * Creates a password hash based on the provided username, password, and
+ * salt.
+ *
+ * @param password The password to hash.
+ * @param salt The salt to use when hashing the password.
+ * @return The generated password hash.
+ */
+ public byte[] createPasswordHash(String password, byte[] salt);
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/PermissionCheckService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/PermissionCheckService.java
new file mode 100644
index 0000000..ddf74ab
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/PermissionCheckService.java
@@ -0,0 +1,848 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+import com.google.inject.Inject;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConnectionGroup;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLConstants;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionGroupPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.ConnectionPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.SystemPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.dao.UserPermissionMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionGroupPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionPermissionExample.Criteria;
+import net.sourceforge.guacamole.net.auth.mysql.model.ConnectionPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.model.SystemPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.SystemPermissionKey;
+import net.sourceforge.guacamole.net.auth.mysql.model.UserPermissionExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.UserPermissionKey;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionGroupPermission;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+import org.glyptodon.guacamole.net.auth.permission.UserPermission;
+
+/**
+ * A service to retrieve information about what objects a user has permission to.
+ * @author James Muehlner
+ */
+public class PermissionCheckService {
+
+ /**
+ * Service for accessing users.
+ */
+ @Inject
+ private UserService userService;
+
+ /**
+ * Service for accessing connections.
+ */
+ @Inject
+ private ConnectionService connectionService;
+
+ /**
+ * Service for accessing connection groups.
+ */
+ @Inject
+ private ConnectionGroupService connectionGroupService;
+
+ /**
+ * DAO for accessing permissions related to users.
+ */
+ @Inject
+ private UserPermissionMapper userPermissionDAO;
+
+ /**
+ * DAO for accessing permissions related to connections.
+ */
+ @Inject
+ private ConnectionPermissionMapper connectionPermissionDAO;
+
+ /**
+ * DAO for accessing permissions related to connection groups.
+ */
+ @Inject
+ private ConnectionGroupPermissionMapper connectionGroupPermissionDAO;
+
+ /**
+ * DAO for accessing permissions related to the system as a whole.
+ */
+ @Inject
+ private SystemPermissionMapper systemPermissionDAO;
+
+ /**
+ * Verifies that the user has the specified access to the given other
+ * user. If permission is denied, a GuacamoleSecurityException is thrown.
+ *
+ * @param userID The ID of the user to check.
+ * @param affectedUserID The user that would be affected by the operation
+ * if permission is granted.
+ * @param permissionType The type of permission to check for.
+ * @throws GuacamoleSecurityException If the specified permission is not
+ * granted.
+ */
+ public void verifyUserAccess(int userID, int affectedUserID,
+ String permissionType) throws GuacamoleSecurityException {
+
+ // If permission does not exist, throw exception
+ if(!checkUserAccess(userID, affectedUserID, permissionType))
+ throw new GuacamoleSecurityException("Permission denied.");
+
+ }
+
+ /**
+ * Verifies that the user has the specified access to the given connection.
+ * If permission is denied, a GuacamoleSecurityException is thrown.
+ *
+ * @param userID The ID of the user to check.
+ * @param affectedConnectionID The connection that would be affected by the
+ * operation if permission is granted.
+ * @param permissionType The type of permission to check for.
+ * @throws GuacamoleSecurityException If the specified permission is not
+ * granted.
+ */
+ public void verifyConnectionAccess(int userID, int affectedConnectionID, String permissionType) throws GuacamoleSecurityException {
+
+ // If permission does not exist, throw exception
+ if(!checkConnectionAccess(userID, affectedConnectionID, permissionType))
+ throw new GuacamoleSecurityException("Permission denied.");
+
+ }
+
+ /**
+ * Verifies that the user has the specified access to the given connection group.
+ * If permission is denied, a GuacamoleSecurityException is thrown.
+ *
+ * @param userID The ID of the user to check.
+ * @param affectedConnectionGroupID The connection group that would be affected by the
+ * operation if permission is granted.
+ * @param permissionType The type of permission to check for.
+ * @throws GuacamoleSecurityException If the specified permission is not
+ * granted.
+ */
+ public void verifyConnectionGroupAccess(int userID, Integer affectedConnectionGroupID, String permissionType) throws GuacamoleSecurityException {
+
+ // If permission does not exist, throw exception
+ if(!checkConnectionGroupAccess(userID, affectedConnectionGroupID, permissionType))
+ throw new GuacamoleSecurityException("Permission denied.");
+
+ }
+
+ /**
+ * Verifies that the user has the specified access to the system. If
+ * permission is denied, a GuacamoleSecurityException is thrown.
+ *
+ * @param userID The ID of the user to check.
+ * @param systemPermissionType The type of permission to check for.
+ * @throws GuacamoleSecurityException If the specified permission is not
+ * granted.
+ */
+ public void verifySystemAccess(int userID, String systemPermissionType)
+ throws GuacamoleSecurityException {
+
+ // If permission does not exist, throw exception
+ if(!checkSystemAccess(userID, systemPermissionType))
+ throw new GuacamoleSecurityException("Permission denied.");
+
+ }
+
+ /**
+ * Checks whether a user has the specified type of access to the affected
+ * user.
+ *
+ * @param userID The ID of the user to check.
+ * @param affectedUserID The user that would be affected by the operation
+ * if permission is granted.
+ * @param permissionType The type of permission to check for.
+ * @return true if the specified permission is granted, false otherwise.
+ */
+ public boolean checkUserAccess(int userID, Integer affectedUserID, String permissionType) {
+
+ // A system administrator has full access to everything.
+ if(checkSystemAdministratorAccess(userID))
+ return true;
+
+ // Check existence of requested permission
+ UserPermissionExample example = new UserPermissionExample();
+ example.createCriteria().andUser_idEqualTo(userID).andAffected_user_idEqualTo(affectedUserID).andPermissionEqualTo(permissionType);
+ return userPermissionDAO.countByExample(example) > 0;
+
+ }
+
+ /**
+ * Checks whether a user has the specified type of access to the affected
+ * connection.
+ *
+ * @param userID The ID of the user to check.
+ * @param affectedConnectionID The connection that would be affected by the
+ * operation if permission is granted.
+ * @param permissionType The type of permission to check for.
+ * @return true if the specified permission is granted, false otherwise.
+ */
+ public boolean checkConnectionAccess(int userID, Integer affectedConnectionID, String permissionType) {
+
+ // A system administrator has full access to everything.
+ if(checkSystemAdministratorAccess(userID))
+ return true;
+
+ // Check existence of requested permission
+ ConnectionPermissionExample example = new ConnectionPermissionExample();
+ example.createCriteria().andUser_idEqualTo(userID).andConnection_idEqualTo(affectedConnectionID).andPermissionEqualTo(permissionType);
+ return connectionPermissionDAO.countByExample(example) > 0;
+
+ }
+
+ /**
+ * Checks whether a user has the specified type of access to the affected
+ * connection group.
+ *
+ * @param userID The ID of the user to check.
+ * @param affectedConnectionGroupID The connection group that would be affected by the
+ * operation if permission is granted.
+ * @param permissionType The type of permission to check for.
+ * @return true if the specified permission is granted, false otherwise.
+ */
+ public boolean checkConnectionGroupAccess(int userID, Integer affectedConnectionGroupID, String permissionType) {
+
+ // All users have implicit permission to read and update the root connection group
+ if(affectedConnectionGroupID == null &&
+ MySQLConstants.CONNECTION_GROUP_READ.equals(permissionType) ||
+ MySQLConstants.CONNECTION_GROUP_UPDATE.equals(permissionType))
+ return true;
+
+ // A system administrator has full access to everything.
+ if(checkSystemAdministratorAccess(userID))
+ return true;
+
+ // Check existence of requested permission
+ ConnectionGroupPermissionExample example = new ConnectionGroupPermissionExample();
+ example.createCriteria().andUser_idEqualTo(userID).andConnection_group_idEqualTo(affectedConnectionGroupID).andPermissionEqualTo(permissionType);
+ return connectionGroupPermissionDAO.countByExample(example) > 0;
+
+ }
+
+ /**
+ * Checks whether a user has the specified type of access to the system.
+ *
+ * @param userID The ID of the user to check.
+ * @param systemPermissionType The type of permission to check for.
+ * @return true if the specified permission is granted, false otherwise.
+ */
+ private boolean checkSystemAccess(int userID, String systemPermissionType) {
+
+ // A system administrator has full access to everything.
+ if(checkSystemAdministratorAccess(userID))
+ return true;
+
+ // Check existence of requested permission
+ SystemPermissionExample example = new SystemPermissionExample();
+ example.createCriteria().andUser_idEqualTo(userID).andPermissionEqualTo(systemPermissionType);
+ return systemPermissionDAO.countByExample(example) > 0;
+
+ }
+
+
+ /**
+ * Checks whether a user has system administrator access to the system.
+ *
+ * @param userID The ID of the user to check.
+ * @return true if the system administrator access exists, false otherwise.
+ */
+ private boolean checkSystemAdministratorAccess(int userID) {
+
+ // Check existence of system administrator permission
+ SystemPermissionExample example = new SystemPermissionExample();
+ example.createCriteria().andUser_idEqualTo(userID).
+ andPermissionEqualTo(MySQLConstants.SYSTEM_ADMINISTER);
+ return systemPermissionDAO.countByExample(example) > 0;
+ }
+
+ /**
+ * Verifies that the specified group can be used for organization
+ * by the given user.
+ *
+ * @param connectionGroupID The ID of the affected ConnectionGroup.
+ * @param userID The ID of the user to check.
+ * @throws GuacamoleSecurityException If the connection group
+ * cannot be used for organization.
+ */
+ public void verifyConnectionGroupUsageAccess(Integer connectionGroupID,
+ int userID, String type) throws GuacamoleSecurityException {
+
+ // If permission does not exist, throw exception
+ if(!checkConnectionGroupUsageAccess(connectionGroupID, userID, type))
+ throw new GuacamoleSecurityException("Permission denied.");
+
+ }
+
+ /**
+ * Check whether a user can use connectionGroup for the given usage.
+ * @param connectionGroupID the ID of the affected connection group.
+ * @param userID The ID of the user to check.
+ * @param usage The desired usage.
+ * @return true if the user can use the connection group for the given usage.
+ */
+ private boolean checkConnectionGroupUsageAccess(
+ Integer connectionGroupID, int userID, String usage) {
+
+ // The root level connection group can only be used for organization
+ if(connectionGroupID == null)
+ return MySQLConstants.CONNECTION_GROUP_ORGANIZATIONAL.equals(usage);
+
+ // A system administrator has full access to everything.
+ if(checkSystemAdministratorAccess(userID))
+ return true;
+
+ // A connection group administrator can use the group either way.
+ if(checkConnectionGroupAccess(userID, connectionGroupID,
+ MySQLConstants.CONNECTION_GROUP_ADMINISTER))
+ return true;
+
+ // Query the connection group
+ MySQLConnectionGroup connectionGroup = connectionGroupService.
+ retrieveConnectionGroup(connectionGroupID, userID);
+
+ // If the connection group is not found, it cannot be used.
+ if(connectionGroup == null)
+ return false;
+
+ // Verify that the desired usage matches the type.
+ return MySQLConstants.getConnectionGroupTypeConstant(
+ connectionGroup.getType()).equals(usage);
+
+ }
+
+
+ /**
+ * Find the list of the IDs of all users a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param permissionType The type of permission to check for.
+ * @return A list of all user IDs this user has the specified access to.
+ */
+ public List<Integer> retrieveUserIDs(int userID, String permissionType) {
+
+ // A system administrator has access to all users.
+ if(checkSystemAdministratorAccess(userID))
+ return userService.getAllUserIDs();
+
+ // Query all user permissions for the given user and permission type
+ UserPermissionExample example = new UserPermissionExample();
+ example.createCriteria().andUser_idEqualTo(userID).andPermissionEqualTo(permissionType);
+ example.setDistinct(true);
+ List<UserPermissionKey> userPermissions =
+ userPermissionDAO.selectByExample(example);
+
+ // Convert result into list of IDs
+ List<Integer> userIDs = new ArrayList<Integer>(userPermissions.size());
+ for(UserPermissionKey permission : userPermissions)
+ userIDs.add(permission.getAffected_user_id());
+
+ return userIDs;
+
+ }
+
+ /**
+ * Find the list of the IDs of all connections a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param permissionType The type of permission to check for.
+ * @return A list of all connection IDs this user has the specified access
+ * to.
+ */
+ public List<Integer> retrieveConnectionIDs(int userID,
+ String permissionType) {
+
+ return retrieveConnectionIDs(userID, null, permissionType, false);
+
+ }
+
+ /**
+ * Find the list of the IDs of all connections a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param parentID the parent connection group.
+ * @param permissionType The type of permission to check for.
+ * @return A list of all connection IDs this user has the specified access
+ * to.
+ */
+ public List<Integer> retrieveConnectionIDs(int userID, Integer parentID,
+ String permissionType) {
+
+ return retrieveConnectionIDs(userID, parentID, permissionType, true);
+
+ }
+
+ /**
+ * Find the list of the IDs of all connections a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param parentID the parent connection group.
+ * @param permissionType The type of permission to check for.
+ * @param checkParentID Whether the parentID should be checked or not.
+ * @return A list of all connection IDs this user has the specified access
+ * to.
+ */
+ private List<Integer> retrieveConnectionIDs(int userID, Integer parentID,
+ String permissionType, boolean checkParentID) {
+
+ // A system administrator has access to all connections.
+ if(checkSystemAdministratorAccess(userID)) {
+ if(checkParentID)
+ return connectionService.getAllConnectionIDs(parentID);
+ else
+ return connectionService.getAllConnectionIDs();
+ }
+
+ // Query all connection permissions for the given user and permission type
+ ConnectionPermissionExample example = new ConnectionPermissionExample();
+ Criteria criteria = example.createCriteria().andUser_idEqualTo(userID)
+ .andPermissionEqualTo(permissionType);
+
+ // Ensure that the connections are all under the parent ID, if needed
+ if(checkParentID) {
+ // Get the IDs of all connections in the connection group
+ List<Integer> allConnectionIDs = connectionService.getAllConnectionIDs(parentID);
+
+ if(allConnectionIDs.isEmpty())
+ return Collections.EMPTY_LIST;
+
+ criteria.andConnection_idIn(allConnectionIDs);
+ }
+
+ example.setDistinct(true);
+ List<ConnectionPermissionKey> connectionPermissions =
+ connectionPermissionDAO.selectByExample(example);
+
+ // Convert result into list of IDs
+ List<Integer> connectionIDs = new ArrayList<Integer>(connectionPermissions.size());
+ for(ConnectionPermissionKey permission : connectionPermissions)
+ connectionIDs.add(permission.getConnection_id());
+
+ return connectionIDs;
+
+ }
+
+ /**
+ * Find the list of the IDs of all connection groups a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param permissionType The type of permission to check for.
+ * @return A list of all connection group IDs this user has the specified access
+ * to.
+ */
+ public List<Integer> retrieveConnectionGroupIDs(int userID,
+ String permissionType) {
+
+ return retrieveConnectionGroupIDs(userID, null, permissionType, false);
+
+ }
+
+ /**
+ * Find the list of the IDs of all connection groups a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param parentID the parent connection group.
+ * @param permissionType The type of permission to check for.
+ * @return A list of all connection group IDs this user has the specified access
+ * to.
+ */
+ public List<Integer> retrieveConnectionGroupIDs(int userID, Integer parentID,
+ String permissionType) {
+
+ return retrieveConnectionGroupIDs(userID, parentID, permissionType, true);
+
+ }
+
+ /**
+ * Find the list of the IDs of all connection groups a user has permission to.
+ * The access type is defined by permissionType.
+ *
+ * @param userID The ID of the user to check.
+ * @param parentID the parent connection group.
+ * @param permissionType The type of permission to check for.
+ * @param checkParentID Whether the parentID should be checked or not.
+ * @return A list of all connection group IDs this user has the specified access
+ * to.
+ */
+ private List<Integer> retrieveConnectionGroupIDs(int userID, Integer parentID,
+ String permissionType, boolean checkParentID) {
+
+ // A system administrator has access to all connectionGroups .
+ if(checkSystemAdministratorAccess(userID)) {
+ if(checkParentID)
+ return connectionGroupService.getAllConnectionGroupIDs(parentID);
+ else
+ return connectionGroupService.getAllConnectionGroupIDs();
+ }
+
+ // Query all connection permissions for the given user and permission type
+ ConnectionGroupPermissionExample example = new ConnectionGroupPermissionExample();
+ ConnectionGroupPermissionExample.Criteria criteria =
+ example.createCriteria().andUser_idEqualTo(userID)
+ .andPermissionEqualTo(permissionType);
+
+ // Ensure that the connection groups are all under the parent ID, if needed
+ if(checkParentID) {
+ // Get the IDs of all connection groups in the connection group
+ List<Integer> allConnectionGroupIDs = connectionGroupService
+ .getAllConnectionGroupIDs(parentID);
+
+ if(allConnectionGroupIDs.isEmpty())
+ return Collections.EMPTY_LIST;
+
+ criteria.andConnection_group_idIn(allConnectionGroupIDs);
+ }
+
+ example.setDistinct(true);
+ List<ConnectionGroupPermissionKey> connectionGroupPermissions =
+ connectionGroupPermissionDAO.selectByExample(example);
+
+ // Convert result into list of IDs
+ List<Integer> connectionGroupIDs = new ArrayList<Integer>(connectionGroupPermissions.size());
+ for(ConnectionGroupPermissionKey permission : connectionGroupPermissions)
+ connectionGroupIDs.add(permission.getConnection_group_id());
+
+ // All users have implicit access to read and update the root group
+ if(MySQLConstants.CONNECTION_GROUP_READ.equals(permissionType)
+ && MySQLConstants.CONNECTION_GROUP_UPDATE.equals(permissionType)
+ && !checkParentID)
+ connectionGroupIDs.add(null);
+
+ return connectionGroupIDs;
+
+ }
+
+ /**
+ * Retrieve all existing usernames that the given user has permission to
+ * perform the given operation upon.
+ *
+ * @param userID The user whose permissions should be checked.
+ * @param permissionType The permission to check.
+ * @return A set of all usernames for which the given user has the given
+ * permission.
+ */
+ public Set<String> retrieveUsernames(int userID, String permissionType) {
+
+ // A system administrator has access to all users.
+ if(checkSystemAdministratorAccess(userID))
+ return userService.getAllUsernames();
+
+ // List of all user IDs for which this user has read access
+ List<Integer> userIDs =
+ retrieveUserIDs(userID, MySQLConstants.USER_READ);
+
+ // Query all associated users
+ return userService.translateUsernames(userIDs).keySet();
+
+ }
+
+ /**
+ * Retrieve all existing connection identifiers that the given user has
+ * permission to perform the given operation upon.
+ *
+ * @param userID The user whose permissions should be checked.
+ * @param permissionType The permission to check.
+ * @param parentID The parent connection group.
+ * @return A set of all connection identifiers for which the given user
+ * has the given permission.
+ */
+ public Set<String> retrieveConnectionIdentifiers(int userID, Integer parentID,
+ String permissionType) {
+
+ // A system administrator has access to all connections.
+ if(checkSystemAdministratorAccess(userID))
+ return connectionService.getAllConnectionIdentifiers(parentID);
+
+ // List of all connection IDs for which this user has access
+ List<Integer> connectionIDs =
+ retrieveConnectionIDs(userID, parentID, permissionType);
+
+ // Unique Identifiers for MySQLConnections are the database IDs
+ Set<String> connectionIdentifiers = new HashSet<String>();
+
+ for(Integer connectionID : connectionIDs)
+ connectionIdentifiers.add(Integer.toString(connectionID));
+
+ return connectionIdentifiers;
+ }
+
+ /**
+ * Retrieve all existing connection group identifiers that the given user
+ * has permission to perform the given operation upon.
+ *
+ * @param userID The user whose permissions should be checked.
+ * @param permissionType The permission to check.
+ * @param parentID The parent connection group.
+ * @return A set of all connection group identifiers for which the given
+ * user has the given permission.
+ */
+ public Set<String> retrieveConnectionGroupIdentifiers(int userID, Integer parentID,
+ String permissionType) {
+
+ // A system administrator has access to all connections.
+ if(checkSystemAdministratorAccess(userID))
+ return connectionGroupService.getAllConnectionGroupIdentifiers(parentID);
+
+ // List of all connection group IDs for which this user has access
+ List<Integer> connectionGroupIDs =
+ retrieveConnectionGroupIDs(userID, parentID, permissionType);
+
+ // Unique Identifiers for MySQLConnectionGroups are the database IDs
+ Set<String> connectionGroupIdentifiers = new HashSet<String>();
+
+ for(Integer connectionGroupID : connectionGroupIDs)
+ connectionGroupIdentifiers.add(Integer.toString(connectionGroupID));
+
+ return connectionGroupIdentifiers;
+ }
+
+ /**
+ * Retrieves all user permissions granted to the user having the given ID.
+ *
+ * @param userID The ID of the user to retrieve permissions of.
+ * @return A set of all user permissions granted to the user having the
+ * given ID.
+ */
+ public Set<UserPermission> retrieveUserPermissions(int userID) {
+
+ // Set of all permissions
+ Set<UserPermission> permissions = new HashSet<UserPermission>();
+
+ // Query all user permissions
+ UserPermissionExample userPermissionExample = new UserPermissionExample();
+ userPermissionExample.createCriteria().andUser_idEqualTo(userID);
+ List<UserPermissionKey> userPermissions =
+ userPermissionDAO.selectByExample(userPermissionExample);
+
+ // Get list of affected user IDs
+ List<Integer> affectedUserIDs = new ArrayList<Integer>();
+ for(UserPermissionKey userPermission : userPermissions)
+ affectedUserIDs.add(userPermission.getAffected_user_id());
+
+ // Get corresponding usernames
+ Map<Integer, String> affectedUsers =
+ userService.retrieveUsernames(affectedUserIDs);
+
+ // Add user permissions
+ for(UserPermissionKey userPermission : userPermissions) {
+
+ // Construct permission from data
+ UserPermission permission = new UserPermission(
+ UserPermission.Type.valueOf(userPermission.getPermission()),
+ affectedUsers.get(userPermission.getAffected_user_id())
+ );
+
+ // Add to set
+ permissions.add(permission);
+
+ }
+
+ return permissions;
+
+ }
+
+ /**
+ * Retrieves all connection permissions granted to the user having the
+ * given ID.
+ *
+ * @param userID The ID of the user to retrieve permissions of.
+ * @return A set of all connection permissions granted to the user having
+ * the given ID.
+ */
+ public Set<ConnectionPermission> retrieveConnectionPermissions(int userID) {
+
+ // Set of all permissions
+ Set<ConnectionPermission> permissions = new HashSet<ConnectionPermission>();
+
+ // Query all connection permissions
+ ConnectionPermissionExample connectionPermissionExample = new ConnectionPermissionExample();
+ connectionPermissionExample.createCriteria().andUser_idEqualTo(userID);
+ List<ConnectionPermissionKey> connectionPermissions =
+ connectionPermissionDAO.selectByExample(connectionPermissionExample);
+
+ // Add connection permissions
+ for(ConnectionPermissionKey connectionPermission : connectionPermissions) {
+
+ // Construct permission from data
+ ConnectionPermission permission = new ConnectionPermission(
+ ConnectionPermission.Type.valueOf(connectionPermission.getPermission()),
+ String.valueOf(connectionPermission.getConnection_id())
+ );
+
+ // Add to set
+ permissions.add(permission);
+
+ }
+
+ return permissions;
+
+ }
+
+ /**
+ * Retrieves all connection group permissions granted to the user having the
+ * given ID.
+ *
+ * @param userID The ID of the user to retrieve permissions of.
+ * @return A set of all connection group permissions granted to the user having
+ * the given ID.
+ */
+ public Set<ConnectionGroupPermission> retrieveConnectionGroupPermissions(int userID) {
+
+ // Set of all permissions
+ Set<ConnectionGroupPermission> permissions = new HashSet<ConnectionGroupPermission>();
+
+ // Query all connection permissions
+ ConnectionGroupPermissionExample connectionGroupPermissionExample = new ConnectionGroupPermissionExample();
+ connectionGroupPermissionExample.createCriteria().andUser_idEqualTo(userID);
+ List<ConnectionGroupPermissionKey> connectionGroupPermissions =
+ connectionGroupPermissionDAO.selectByExample(connectionGroupPermissionExample);
+
+ // Add connection permissions
+ for(ConnectionGroupPermissionKey connectionGroupPermission : connectionGroupPermissions) {
+
+ // Construct permission from data
+ ConnectionGroupPermission permission = new ConnectionGroupPermission(
+ ConnectionGroupPermission.Type.valueOf(connectionGroupPermission.getPermission()),
+ String.valueOf(connectionGroupPermission.getConnection_group_id())
+ );
+
+ // Add to set
+ permissions.add(permission);
+
+ }
+
+ // All users have implict access to read the root connection group
+ permissions.add(new ConnectionGroupPermission(
+ ConnectionGroupPermission.Type.READ,
+ MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER
+ ));
+
+ // All users have implict access to update the root connection group
+ permissions.add(new ConnectionGroupPermission(
+ ConnectionGroupPermission.Type.UPDATE,
+ MySQLConstants.CONNECTION_GROUP_ROOT_IDENTIFIER
+ ));
+
+ return permissions;
+
+ }
+
+ /**
+ * Retrieves all system permissions granted to the user having the
+ * given ID.
+ *
+ * @param userID The ID of the user to retrieve permissions of.
+ * @return A set of all system permissions granted to the user having the
+ * given ID.
+ */
+ public Set<SystemPermission> retrieveSystemPermissions(int userID) {
+
+ // Set of all permissions
+ Set<SystemPermission> permissions = new HashSet<SystemPermission>();
+
+ // And finally, system permissions
+ SystemPermissionExample systemPermissionExample = new SystemPermissionExample();
+ systemPermissionExample.createCriteria().andUser_idEqualTo(userID);
+ List<SystemPermissionKey> systemPermissions =
+ systemPermissionDAO.selectByExample(systemPermissionExample);
+ for(SystemPermissionKey systemPermission : systemPermissions) {
+
+ // User creation permission
+ if(systemPermission.getPermission().equals(MySQLConstants.SYSTEM_USER_CREATE))
+ permissions.add(new SystemPermission(SystemPermission.Type.CREATE_USER));
+
+ // System creation permission
+ else if(systemPermission.getPermission().equals(MySQLConstants.SYSTEM_CONNECTION_CREATE))
+ permissions.add(new SystemPermission(SystemPermission.Type.CREATE_CONNECTION));
+
+ // System creation permission
+ else if(systemPermission.getPermission().equals(MySQLConstants.SYSTEM_CONNECTION_GROUP_CREATE))
+ permissions.add(new SystemPermission(SystemPermission.Type.CREATE_CONNECTION_GROUP));
+
+ // System administration permission
+ else if(systemPermission.getPermission().equals(MySQLConstants.SYSTEM_ADMINISTER))
+ permissions.add(new SystemPermission(SystemPermission.Type.ADMINISTER));
+
+ }
+
+ return permissions;
+
+ }
+
+ /**
+ * Retrieves all permissions granted to the user having the given ID.
+ *
+ * @param userID The ID of the user to retrieve permissions of.
+ * @return A set of all permissions granted to the user having the given
+ * ID.
+ */
+ public Set<Permission> retrieveAllPermissions(int userID) {
+
+ // Set which will contain all permissions
+ Set<Permission> allPermissions = new HashSet<Permission>();
+
+ // Add user permissions
+ allPermissions.addAll(retrieveUserPermissions(userID));
+
+ // Add connection permissions
+ allPermissions.addAll(retrieveConnectionPermissions(userID));
+
+ // add connection group permissions
+ allPermissions.addAll(retrieveConnectionGroupPermissions(userID));
+
+ // Add system permissions
+ allPermissions.addAll(retrieveSystemPermissions(userID));
+
+ return allPermissions;
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SHA256PasswordEncryptionService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SHA256PasswordEncryptionService.java
new file mode 100644
index 0000000..04fea1a
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SHA256PasswordEncryptionService.java
@@ -0,0 +1,90 @@
+
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import javax.xml.bind.DatatypeConverter;
+
+/**
+ * Provides a SHA-256 based implementation of the password encryption functionality.
+ * @author James Muehlner
+ */
+public class SHA256PasswordEncryptionService implements PasswordEncryptionService {
+
+ @Override
+ public boolean checkPassword(String password, byte[] hashedPassword,
+ byte[] salt) {
+
+ // Compare bytes of password in credentials against hashed password
+ byte[] passwordBytes = createPasswordHash(password, salt);
+ return Arrays.equals(passwordBytes, hashedPassword);
+
+ }
+
+ @Override
+ public byte[] createPasswordHash(String password, byte[] salt) {
+
+ try {
+
+ // Build salted password
+ StringBuilder builder = new StringBuilder();
+ builder.append(password);
+ builder.append(DatatypeConverter.printHexBinary(salt));
+
+ // Hash UTF-8 bytes of salted password
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ md.update(builder.toString().getBytes("UTF-8"));
+ return md.digest();
+
+ }
+
+ // Should not happen
+ catch (UnsupportedEncodingException ex) {
+ throw new RuntimeException(ex);
+ }
+
+ // Should not happen
+ catch (NoSuchAlgorithmException ex) {
+ throw new RuntimeException(ex);
+ }
+
+ }
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SaltService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SaltService.java
new file mode 100644
index 0000000..0d194c9
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SaltService.java
@@ -0,0 +1,48 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/**
+ * A service to generate password salts.
+ * @author James Muehlner
+ */
+public interface SaltService {
+ /**
+ * Generates a new String that can be used as a password salt.
+ * @return a new salt for password encryption.
+ */
+ public byte[] generateSalt();
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SecureRandomSaltService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SecureRandomSaltService.java
new file mode 100644
index 0000000..35caba2
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/SecureRandomSaltService.java
@@ -0,0 +1,60 @@
+
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.security.SecureRandom;
+
+/**
+ * Generates password salts via SecureRandom.
+ * @author James Muehlner
+ */
+public class SecureRandomSaltService implements SaltService {
+
+ /**
+ * Instance of SecureRandom for generating the salt.
+ */
+ private SecureRandom secureRandom = new SecureRandom();
+
+ @Override
+ public byte[] generateSalt() {
+ byte[] salt = new byte[32];
+ secureRandom.nextBytes(salt);
+ return salt;
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/UserService.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/UserService.java
new file mode 100644
index 0000000..b988983
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/UserService.java
@@ -0,0 +1,381 @@
+
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mysql.
+ *
+ * The Initial Developer of the Original Code is
+ * James Muehlner.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import net.sourceforge.guacamole.net.auth.mysql.MySQLUser;
+import net.sourceforge.guacamole.net.auth.mysql.dao.UserMapper;
+import net.sourceforge.guacamole.net.auth.mysql.model.User;
+import net.sourceforge.guacamole.net.auth.mysql.model.UserExample;
+import net.sourceforge.guacamole.net.auth.mysql.model.UserWithBLOBs;
+
+/**
+ * Service which provides convenience methods for creating, retrieving, and
+ * manipulating users.
+ *
+ * @author Michael Jumper, James Muehlner
+ */
+public class UserService {
+
+ /**
+ * DAO for accessing users.
+ */
+ @Inject
+ private UserMapper userDAO;
+
+ /**
+ * Provider for creating users.
+ */
+ @Inject
+ private Provider<MySQLUser> mySQLUserProvider;
+
+ /**
+ * Service for checking permissions.
+ */
+ @Inject
+ private PermissionCheckService permissionCheckService;
+
+ /**
+ * Service for encrypting passwords.
+ */
+ @Inject
+ private PasswordEncryptionService passwordService;
+
+ /**
+ * Service for generating random salts.
+ */
+ @Inject
+ private SaltService saltService;
+
+ /**
+ * Create a new MySQLUser based on the provided User.
+ *
+ * @param user The User to use when populating the data of the given
+ * MySQLUser.
+ * @return A new MySQLUser object, populated with the data of the given
+ * user.
+ *
+ * @throws GuacamoleException If an error occurs while reading the data
+ * of the provided User.
+ */
+ public MySQLUser toMySQLUser(org.glyptodon.guacamole.net.auth.User user) throws GuacamoleException {
+ MySQLUser mySQLUser = mySQLUserProvider.get();
+ mySQLUser.init(user);
+ return mySQLUser;
+ }
+
+ /**
+ * Create a new MySQLUser based on the provided database record.
+ *
+ * @param user The database record describing the user.
+ * @return A new MySQLUser object, populated with the data of the given
+ * database record.
+ */
+ private MySQLUser toMySQLUser(UserWithBLOBs user) {
+
+ // Retrieve user from provider
+ MySQLUser mySQLUser = mySQLUserProvider.get();
+
+ // Init with data from given database user
+ mySQLUser.init(
+ user.getUser_id(),
+ user.getUsername(),
+ null,
+ permissionCheckService.retrieveAllPermissions(user.getUser_id())
+ );
+
+ // Return new user
+ return mySQLUser;
+
+ }
+
+ /**
+ * Retrieves the user having the given ID from the database.
+ *
+ * @param id The ID of the user to retrieve.
+ * @return The existing MySQLUser object if found, null otherwise.
+ */
+ public MySQLUser retrieveUser(int id) {
+
+ // Query user by ID
+ UserWithBLOBs user = userDAO.selectByPrimaryKey(id);
+
+ // If no user found, return null
+ if(user == null)
+ return null;
+
+ // Otherwise, return found user
+ return toMySQLUser(user);
+
+ }
+
+ /**
+ * Retrieves the user having the given username from the database.
+ *
+ * @param name The username of the user to retrieve.
+ * @return The existing MySQLUser object if found, null otherwise.
+ */
+ public MySQLUser retrieveUser(String name) {
+
+ // Query user by ID
+ UserExample example = new UserExample();
+ example.createCriteria().andUsernameEqualTo(name);
+ List<UserWithBLOBs> users = userDAO.selectByExampleWithBLOBs(example);
+
+ // If no user found, return null
+ if(users.isEmpty())
+ return null;
+
+ // Otherwise, return found user
+ return toMySQLUser(users.get(0));
+
+ }
+
+ /**
+ * Retrieves the user corresponding to the given credentials from the
+ * database.
+ *
+ * @param credentials The credentials to use when locating the user.
+ * @return The existing MySQLUser object if the credentials given are
+ * valid, null otherwise.
+ */
+ public MySQLUser retrieveUser(Credentials credentials) {
+
+ // No null users in database
+ if (credentials.getUsername() == null)
+ return null;
+
+ // Query user
+ UserExample userExample = new UserExample();
+ userExample.createCriteria().andUsernameEqualTo(credentials.getUsername());
+ List<UserWithBLOBs> users = userDAO.selectByExampleWithBLOBs(userExample);
+
+ // Check that a user was found
+ if (users.isEmpty())
+ return null;
+
+ // Assert only one user found
+ assert users.size() == 1 : "Multiple users with same username.";
+
+ // Get first (and only) user
+ UserWithBLOBs user = users.get(0);
+
+ // Check password, if invalid return null
+ if (!passwordService.checkPassword(credentials.getPassword(),
+ user.getPassword_hash(), user.getPassword_salt()))
+ return null;
+
+ // Return found user
+ return toMySQLUser(user);
+
+ }
+
+ /**
+ * Retrieves a translation map of usernames to their corresponding IDs.
+ *
+ * @param ids The IDs of the users to retrieve the usernames of.
+ * @return A map containing the names of all users and their corresponding
+ * IDs.
+ */
+ public Map<String, Integer> translateUsernames(List<Integer> ids) {
+
+ // If no IDs given, just return empty map
+ if (ids.isEmpty())
+ return Collections.EMPTY_MAP;
+
+ // Map of all names onto their corresponding IDs
+ Map<String, Integer> names = new HashMap<String, Integer>();
+
+ // Get all users having the given IDs
+ UserExample example = new UserExample();
+ example.createCriteria().andUser_idIn(ids);
+ List<User> users =
+ userDAO.selectByExample(example);
+
+ // Produce set of names
+ for (User user : users)
+ names.put(user.getUsername(), user.getUser_id());
+
+ return names;
+
+ }
+
+ /**
+ * Retrieves a map of all usernames for the given IDs.
+ *
+ * @param ids The IDs of the users to retrieve the usernames of.
+ * @return A map containing the names of all users and their corresponding
+ * IDs.
+ */
+ public Map<Integer, String> retrieveUsernames(Collection<Integer> ids) {
+
+ // If no IDs given, just return empty map
+ if (ids.isEmpty())
+ return Collections.EMPTY_MAP;
+
+ // Map of all names onto their corresponding IDs
+ Map<Integer, String> names = new HashMap<Integer, String>();
+
+ // Get all users having the given IDs
+ UserExample example = new UserExample();
+ example.createCriteria().andUser_idIn(Lists.newArrayList(ids));
+ List<User> users =
+ userDAO.selectByExample(example);
+
+ // Produce set of names
+ for (User user : users)
+ names.put(user.getUser_id(), user.getUsername());
+
+ return names;
+
+ }
+
+ /**
+ * Creates a new user having the given username and password.
+ *
+ * @param username The username to assign to the new user.
+ * @param password The password to assign to the new user.
+ * @return A new MySQLUser containing the data of the newly created
+ * user.
+ */
+ public MySQLUser createUser(String username, String password) {
+
+ // Initialize database user
+ UserWithBLOBs user = new UserWithBLOBs();
+ user.setUsername(username);
+
+ // Set password if specified
+ if (password != null) {
+ byte[] salt = saltService.generateSalt();
+ user.setPassword_salt(salt);
+ user.setPassword_hash(
+ passwordService.createPasswordHash(password, salt));
+ }
+
+ // Create user
+ userDAO.insert(user);
+ return toMySQLUser(user);
+
+ }
+
+ /**
+ * Deletes the user having the given ID from the database.
+ * @param user_id The ID of the user to delete.
+ */
+ public void deleteUser(int user_id) {
+ userDAO.deleteByPrimaryKey(user_id);
+ }
+
+ /**
+ * Updates the user in the database corresponding to the given MySQLUser.
+ *
+ * @param mySQLUser The MySQLUser to update (save) to the database. This
+ * user must already exist.
+ */
+ public void updateUser(MySQLUser mySQLUser) {
+
+ UserWithBLOBs user = new UserWithBLOBs();
+ user.setUser_id(mySQLUser.getUserID());
+ user.setUsername(mySQLUser.getUsername());
+
+ // Set password if specified
+ if (mySQLUser.getPassword() != null) {
+ byte[] salt = saltService.generateSalt();
+ user.setPassword_salt(salt);
+ user.setPassword_hash(
+ passwordService.createPasswordHash(mySQLUser.getPassword(), salt));
+ }
+
+ // Update the user in the database
+ userDAO.updateByPrimaryKeySelective(user);
+
+ }
+
+ /**
+ * Get the usernames of all the users defined in the system.
+ *
+ * @return A Set of usernames of all the users defined in the system.
+ */
+ public Set<String> getAllUsernames() {
+
+ // Set of all present usernames
+ Set<String> usernames = new HashSet<String>();
+
+ // Query all usernames
+ List<User> users =
+ userDAO.selectByExample(new UserExample());
+ for (User user : users)
+ usernames.add(user.getUsername());
+
+ return usernames;
+
+ }
+
+ /**
+ * Get the user IDs of all the users defined in the system.
+ *
+ * @return A list of user IDs of all the users defined in the system.
+ */
+ public List<Integer> getAllUserIDs() {
+
+ // Set of all present user IDs
+ List<Integer> userIDs = new ArrayList<Integer>();
+
+ // Query all user IDs
+ List<User> users =
+ userDAO.selectByExample(new UserExample());
+ for (User user : users)
+ userIDs.add(user.getUser_id());
+
+ return userIDs;
+
+ }
+
+}
diff --git a/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/package-info.java b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/package-info.java
new file mode 100644
index 0000000..4cc071f
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/java/net/sourceforge/guacamole/net/auth/mysql/service/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Service classes which help fill the needs of the MySQL authentication
+ * provider.
+ */
+package net.sourceforge.guacamole.net.auth.mysql.service;
+
diff --git a/extensions/guacamole-auth-mysql/src/main/resources/generatorConfig.xml b/extensions/guacamole-auth-mysql/src/main/resources/generatorConfig.xml
new file mode 100644
index 0000000..a232603
--- /dev/null
+++ b/extensions/guacamole-auth-mysql/src/main/resources/generatorConfig.xml
@@ -0,0 +1,114 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE generatorConfiguration
+ PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
+ "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
+
+<generatorConfiguration>
+ <context id="guacamoleTables" targetRuntime="MyBatis3">
+
+ <!-- Allow selectByExample with RowBounds -->
+ <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
+
+ <!-- MySQL JDBC driver class. -->
+ <jdbcConnection driverClass="com.mysql.jdbc.Driver"
+ connectionURL="jdbc:mysql://127.0.0.1:3306"
+ userId="${guacamole.database.user}"
+ password="${guacamole.database.password}"/>
+
+ <javaModelGenerator
+ targetPackage="net.sourceforge.guacamole.net.auth.mysql.model"
+ targetProject="MAVEN"/>
+
+ <sqlMapGenerator
+ targetPackage="net.sourceforge.guacamole.net.auth.mysql.dao"
+ targetProject="MAVEN"/>
+
+ <javaClientGenerator type="XMLMAPPER"
+ targetPackage="net.sourceforge.guacamole.net.auth.mysql.dao"
+ targetProject="MAVEN"/>
+
+ <!-- TABLES -->
+
+ <table tableName="guacamole_connection"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="Connection" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ <generatedKey column="connection_id" identity="true"
+ sqlStatement="SELECT LAST_INSERT_ID()"/>
+ </table>
+
+ <table tableName="guacamole_connection_group"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="ConnectionGroup" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ <generatedKey column="connection_group_id" identity="true"
+ sqlStatement="SELECT LAST_INSERT_ID()"/>
+ </table>
+
+ <table tableName="guacamole_connection_parameter"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="ConnectionParameter" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ </table>
+
+ <table tableName="guacamole_connection_permission"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="ConnectionPermission" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ </table>
+
+ <table tableName="guacamole_connection_group_permission"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="ConnectionGroupPermission" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ </table>
+
+ <table tableName="guacamole_system_permission"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="SystemPermission" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ </table>
+
+ <table tableName="guacamole_user"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="User" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ <generatedKey column="user_id" identity="true"
+ sqlStatement="SELECT LAST_INSERT_ID()"/>
+ </table>
+
+ <table tableName="guacamole_user_permission"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="UserPermission" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ </table>
+
+ <table tableName="guacamole_connection_history"
+ catalog="${guacamole.database.catalog}"
+ schema="${guacamole.database.schema}"
+ domainObjectName="ConnectionHistory" >
+ <property name="useActualColumnNames" value="true"/>
+ <property name="ignoreQualifiersAtRuntime" value="true"/>
+ <generatedKey column="history_id" identity="true"
+ sqlStatement="SELECT LAST_INSERT_ID()"/>
+ </table>
+
+ </context>
+</generatorConfiguration>
+
diff --git a/extensions/guacamole-auth-noauth/README b/extensions/guacamole-auth-noauth/README
new file mode 100644
index 0000000..53eac57
--- /dev/null
+++ b/extensions/guacamole-auth-noauth/README
@@ -0,0 +1,117 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-auth-noauth?
+------------------------------------------------------------
+
+guacamole-auth-noauth is a Java library for use with the Guacamole web
+application which removes all authentication. It provides a static set of
+connections to anyone using the web application.
+
+Beware that with authentication disabled, any person with access to your
+Guacamole server will have access to any connections it provides. The login
+screen will not appear unless guacamole-auth-noauth was set up incorrectly or
+it is not compatible with your version of Guacamole.
+
+
+------------------------------------------------------------
+ Compiling and installing guacamole-auth-noauth
+------------------------------------------------------------
+
+guacamole-auth-noauth is built using Maven. Building guacamole-auth-noauth
+compiles all classes and packages them into a redistributable .jar file. This
+.jar file can be installed in the library directory configured in
+guacamole.properties such that the authentication provider is available.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .jar file will be
+ created in the target/ subdirectory of the current directory.
+
+ If this process fails, check the build errors, and verify that the
+ contents of your settings.xml file is correct.
+
+2) Extract the .tar.gz file now present in the target/ directory, and
+ place the .jar files in the extracted lib/ subdirectory in the library
+ directory specified in guacamole.properties.
+
+ You will likely need to do this as root.
+
+ If you do not have a library directory configured in your
+ guacamole.properties, you will need to specify one. The directory
+ is specified using the "lib-directory" property.
+
+3) Write a noauth-config.xml file containing all desired connections
+
+ The guacamole-auth-noauth authentication provided is configured by a
+ static XML file which lists all available connections.
+
+ The file consists of a single <configs> tag which contains any number of
+ <config> tags, each having a name and protocol. These <config> tags
+ correspond to connections.
+
+ Each <config> can contain any number of <param> tags which correspond to
+ the parameters of the protocol chosen. Each <param> tag has a name and
+ value, where the name is defined by the documentation of the protocol
+ being used.
+
+ For example, to define a single RDP connection to your RDP server with
+ the hostname "my-rdp-server-hostname", you could write:
+
+ <configs>
+ <config name="my-rdp-server" protocol="rdp">
+ <param name="hostname" value="my-rdp-server-hostname" />
+ <param name="port" value="3389" />
+ </config>
+ </configs>
+
+ When completed, this file should be placed in a common location such
+ that it can be referenced from guacamole.properties, like
+ /etc/guacamole/noauth-config.xml.
+
+4) Configure guacamole.properties
+
+ An additional property is required by guacamole-auth-noauth which defines
+ where the configuration file is found. It must be added to your
+ guacamole.properties:
+
+ # Configuration for NoAuth
+ noauth-config: /etc/guacamole/noauth-config.xml
+
+5) Restart Tomcat
+
+ The guacamole.properties file as well as any authentication provider .jar
+ files are only read when Tomcat starts. This goes for any other servlet
+ container as well.
+
+ You must restart Tomcat before any of the above changes can take effect.
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/extensions/guacamole-auth-noauth/doc/example/noauth-config.xml b/extensions/guacamole-auth-noauth/doc/example/noauth-config.xml
new file mode 100644
index 0000000..be02d89
--- /dev/null
+++ b/extensions/guacamole-auth-noauth/doc/example/noauth-config.xml
@@ -0,0 +1,6 @@
+<configs>
+ <config name="myconfig" protocol="rdp">
+ <param name="hostname" value="rdp-server" />
+ <param name="port" value="3389" />
+ </config>
+</configs>
diff --git a/extensions/guacamole-auth-noauth/pom.xml b/extensions/guacamole-auth-noauth/pom.xml
new file mode 100644
index 0000000..7667a9e
--- /dev/null
+++ b/extensions/guacamole-auth-noauth/pom.xml
@@ -0,0 +1,72 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-auth-noauth</artifactId>
+ <packaging>jar</packaging>
+ <version>0.8.0</version>
+ <name>guacamole-auth-noauth</name>
+ <url>http://guacamole.sourceforge.net/</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Written for 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <!-- Assembly plugin - for easy distribution -->
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2-beta-5</version>
+ <configuration>
+ <finalName>${project.artifactId}-${project.version}</finalName>
+ <appendAssemblyId>false</appendAssemblyId>
+ <descriptors>
+ <descriptor>src/main/assembly/dist.xml</descriptor>
+ </descriptors>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-dist-archive</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <!-- Guacamole Java API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+
+ <!-- Guacamole Extension API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-ext</artifactId>
+ <version>0.8.1</version>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/extensions/guacamole-auth-noauth/src/main/assembly/dist.xml b/extensions/guacamole-auth-noauth/src/main/assembly/dist.xml
new file mode 100644
index 0000000..bb42806
--- /dev/null
+++ b/extensions/guacamole-auth-noauth/src/main/assembly/dist.xml
@@ -0,0 +1,48 @@
+<assembly
+ xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+
+ <id>dist</id>
+ <baseDirectory>${project.artifactId}-${project.version}</baseDirectory>
+
+ <!-- Output tar.gz -->
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+
+ <!-- Include docs and schema -->
+ <fileSets>
+
+ <!-- Include docs -->
+ <fileSet>
+ <outputDirectory>/</outputDirectory>
+ <directory>doc</directory>
+ </fileSet>
+
+ </fileSets>
+
+ <!-- Include self and all dependencies except guacamole-common
+ and guacamole-ext -->
+ <dependencySets>
+ <dependencySet>
+
+ <outputDirectory>/lib</outputDirectory>
+ <scope>runtime</scope>
+ <unpack>false</unpack>
+ <useProjectArtifact>true</useProjectArtifact>
+ <useTransitiveFiltering>true</useTransitiveFiltering>
+
+ <excludes>
+
+ <!-- Do not include guacamole-common -->
+ <exclude>org.glyptodon.guacamole:guacamole-common</exclude>
+
+ <!-- Do not include guacamole-ext -->
+ <exclude>org.glyptodon.guacamole:guacamole-ext</exclude>
+
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+
+</assembly>
diff --git a/extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthConfigContentHandler.java b/extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthConfigContentHandler.java
new file mode 100644
index 0000000..b1f4b92
--- /dev/null
+++ b/extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthConfigContentHandler.java
@@ -0,0 +1,137 @@
+
+package net.sourceforge.guacamole.net.auth.noauth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-noauth.
+ *
+ * The Initial Developer of the Original Code is
+ * Laurent Meunier
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * XML parser for the configuration file used by the NoAuth auth provider.
+ *
+ * @author Laurent Meunier
+ */
+public class NoAuthConfigContentHandler extends DefaultHandler {
+
+ /**
+ * Map of all configurations, indexed by name.
+ */
+ private Map<String, GuacamoleConfiguration> configs = new HashMap<String, GuacamoleConfiguration>();
+
+ /**
+ * The name of the current configuration, if any.
+ */
+ private String current = null;
+
+ /**
+ * The current configuration being parsed, if any.
+ */
+ private GuacamoleConfiguration currentConfig = null;
+
+ /**
+ * Returns the a map of all available configurations as parsed from the
+ * XML file. This map is unmodifiable.
+ *
+ * @return A map of all available configurations.
+ */
+ public Map<String, GuacamoleConfiguration> getConfigs() {
+ return Collections.unmodifiableMap(configs);
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName) throws SAXException {
+
+ // If end of config element, add to map
+ if (localName.equals("config")) {
+
+ // Add to map
+ configs.put(current, currentConfig);
+
+ // Reset state for next configuration
+ currentConfig = null;
+ current = null;
+
+ }
+
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
+
+ // Begin configuration parsing if config element
+ if (localName.equals("config")) {
+
+ // Ensure this config is on the top level
+ if (current != null)
+ throw new SAXException("Configurations cannot be nested.");
+
+ // Read name
+ String name = attributes.getValue("name");
+ if (name == null)
+ throw new SAXException("Each configuration must have a name.");
+
+ // Read protocol
+ String protocol = attributes.getValue("protocol");
+ if (protocol == null)
+ throw new SAXException("Each configuration must have a protocol.");
+
+ // Create config stub
+ current = name;
+ currentConfig = new GuacamoleConfiguration();
+ currentConfig.setProtocol(protocol);
+
+ }
+
+ // Add parameters to existing configuration
+ else if (localName.equals("param")) {
+
+ // Ensure a corresponding config exists
+ if (currentConfig == null)
+ throw new SAXException("Parameter without corresponding configuration.");
+
+ currentConfig.setParameter(attributes.getValue("name"), attributes.getValue("value"));
+
+ }
+
+ }
+
+}
diff --git a/extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthenticationProvider.java b/extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthenticationProvider.java
new file mode 100644
index 0000000..7d5ded9
--- /dev/null
+++ b/extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthenticationProvider.java
@@ -0,0 +1,186 @@
+
+package net.sourceforge.guacamole.net.auth.noauth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-noauth.
+ *
+ * The Initial Developer of the Original Code is
+ * Laurent Meunier
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Map;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.net.auth.simple.SimpleAuthenticationProvider;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.properties.FileGuacamoleProperty;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Logger;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+
+/**
+ * Disable authentication in Guacamole. All users accessing Guacamole are
+ * automatically authenticated as "Anonymous" user and are able to use all
+ * available GuacamoleConfigurations.
+ *
+ * GuacamoleConfiguration are read from the XML file defined by `noauth-config`
+ * in the Guacamole configuration file (`guacamole.properties`).
+ *
+ *
+ * Example `guacamole.properties`:
+ *
+ * auth-provider: net.sourceforge.guacamole.net.auth.noauth.NoAuthenticationProvider
+ * noauth-config: /etc/guacamole/noauth-config.xml
+ *
+ *
+ * Example `noauth-config.xml`:
+ *
+ * <configs>
+ * <config name="my-rdp-server" protocol="rdp">
+ * <param name="hostname" value="my-rdp-server-hostname" />
+ * <param name="port" value="3389" />
+ * </config>
+ * </configs>
+ *
+ * @author Laurent Meunier
+ */
+public class NoAuthenticationProvider extends SimpleAuthenticationProvider {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(NoAuthenticationProvider.class);
+
+ /**
+ * Map of all known configurations, indexed by identifier.
+ */
+ private Map<String, GuacamoleConfiguration> configs;
+
+ /**
+ * The last time the configuration XML was modified, as milliseconds since
+ * UNIX epoch.
+ */
+ private long configTime;
+
+ /**
+ * The filename of the XML file to read the user mapping from.
+ */
+ public static final FileGuacamoleProperty NOAUTH_CONFIG = new FileGuacamoleProperty() {
+
+ @Override
+ public String getName() {
+ return "noauth-config";
+ }
+
+ };
+
+ /**
+ * Retrieves the configuration file, as defined within guacamole.properties.
+ *
+ * @return The configuration file, as defined within guacamole.properties.
+ * @throws GuacamoleException If an error occurs while reading the
+ * property.
+ */
+ private File getConfigurationFile() throws GuacamoleException {
+ return GuacamoleProperties.getRequiredProperty(NOAUTH_CONFIG);
+ }
+
+ public synchronized void init() throws GuacamoleException {
+
+ // Get configuration file
+ File configFile = getConfigurationFile();
+ logger.info("Reading configuration file: {}", configFile);
+
+ // Parse document
+ try {
+
+ // Set up parser
+ NoAuthConfigContentHandler contentHandler = new NoAuthConfigContentHandler();
+
+ XMLReader parser = XMLReaderFactory.createXMLReader();
+ parser.setContentHandler(contentHandler);
+
+ // Read and parse file
+ Reader reader = new BufferedReader(new FileReader(configFile));
+ parser.parse(new InputSource(reader));
+ reader.close();
+
+ // Init configs
+ configTime = configFile.lastModified();
+ configs = contentHandler.getConfigs();
+
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException("Error reading configuration file: " + e.getMessage(), e);
+ }
+ catch (SAXException e) {
+ throw new GuacamoleServerException("Error parsing XML file: " + e.getMessage(), e);
+ }
+
+ }
+
+ @Override
+ public Map<String, GuacamoleConfiguration> getAuthorizedConfigurations(Credentials credentials) throws GuacamoleException {
+
+ // Check mapping file mod time
+ File configFile = getConfigurationFile();
+ if (configFile.exists() && configTime < configFile.lastModified()) {
+
+ // If modified recently, gain exclusive access and recheck
+ synchronized (this) {
+ if (configFile.exists() && configTime < configFile.lastModified()) {
+ logger.info("Config file {} has been modified.", configFile);
+ init(); // If still not up to date, re-init
+ }
+ }
+
+ }
+
+ // If no mapping available, report as such
+ if (configs == null)
+ throw new GuacamoleServerException("Configuration could not be read.");
+
+ return configs;
+
+ }
+}
diff --git a/guacamole-common-js/ChangeLog b/guacamole-common-js/ChangeLog
new file mode 100644
index 0000000..d069a60
--- /dev/null
+++ b/guacamole-common-js/ChangeLog
@@ -0,0 +1,61 @@
+2013-07-01 Michael Jumper <mike.jumper at guac-dev.org>
+
+ * Add support for "file", "blob", and "end" instructions
+
+2013-05-29 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix support for AltGr and modifiers
+ * Handle bad source rect sizes in copy
+
+2012-10-24 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Implement base audio support
+ * Implement audio instruction
+ * Add width/height getters to client
+ * Add onresize event to client
+
+2012-10-16 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix stream inefficiency bug (ticket #201)
+
+2012-09-27 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix variable naming conflict (ticket #191)
+
+2012-08-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Improve documentation
+
+2012-08-02 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix keyboard event handling
+
+2012-08-01 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Implement absolute touch device emulation
+
+2012-05-04 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Improved iPad and touch device support
+ * Improved touch support
+ * Implemented new drawing instructions
+ * Nestable layers
+
+2011-12-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Implemented improved instruction format
+ * Fixed errors in IE in on-screen keyboard
+ * Relicensed as Mozilla/LGPL/GPL
+ * Touch support (emulates touchpad control of mouse pointer)
+ * "rect" and "clip" instructions
+
+2011-07-13 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * "sync" instruction
+ * Channel masks (alpha compositing)
+ * Multiple tunnel support
+
+2011-03-02 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Initial release
+
diff --git a/guacamole-common-js/LICENSE b/guacamole-common-js/LICENSE
new file mode 100644
index 0000000..7714141
--- /dev/null
+++ b/guacamole-common-js/LICENSE
@@ -0,0 +1,470 @@
+ MOZILLA PUBLIC LICENSE
+ Version 1.1
+
+ ---------------
+
+1. Definitions.
+
+ 1.0.1. "Commercial Use" means distribution or otherwise making the
+ Covered Code available to a third party.
+
+ 1.1. "Contributor" means each entity that creates or contributes to
+ the creation of Modifications.
+
+ 1.2. "Contributor Version" means the combination of the Original
+ Code, prior Modifications used by a Contributor, and the Modifications
+ made by that particular Contributor.
+
+ 1.3. "Covered Code" means the Original Code or Modifications or the
+ combination of the Original Code and Modifications, in each case
+ including portions thereof.
+
+ 1.4. "Electronic Distribution Mechanism" means a mechanism generally
+ accepted in the software development community for the electronic
+ transfer of data.
+
+ 1.5. "Executable" means Covered Code in any form other than Source
+ Code.
+
+ 1.6. "Initial Developer" means the individual or entity identified
+ as the Initial Developer in the Source Code notice required by Exhibit
+ A.
+
+ 1.7. "Larger Work" means a work which combines Covered Code or
+ portions thereof with code not governed by the terms of this License.
+
+ 1.8. "License" means this document.
+
+ 1.8.1. "Licensable" means having the right to grant, to the maximum
+ extent possible, whether at the time of the initial grant or
+ subsequently acquired, any and all of the rights conveyed herein.
+
+ 1.9. "Modifications" means any addition to or deletion from the
+ substance or structure of either the Original Code or any previous
+ Modifications. When Covered Code is released as a series of files, a
+ Modification is:
+ A. Any addition to or deletion from the contents of a file
+ containing Original Code or previous Modifications.
+
+ B. Any new file that contains any part of the Original Code or
+ previous Modifications.
+
+ 1.10. "Original Code" means Source Code of computer software code
+ which is described in the Source Code notice required by Exhibit A as
+ Original Code, and which, at the time of its release under this
+ License is not already Covered Code governed by this License.
+
+ 1.10.1. "Patent Claims" means any patent claim(s), now owned or
+ hereafter acquired, including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by grantor.
+
+ 1.11. "Source Code" means the preferred form of the Covered Code for
+ making modifications to it, including all modules it contains, plus
+ any associated interface definition files, scripts used to control
+ compilation and installation of an Executable, or source code
+ differential comparisons against either the Original Code or another
+ well known, available Covered Code of the Contributor's choice. The
+ Source Code can be in a compressed or archival form, provided the
+ appropriate decompression or de-archiving software is widely available
+ for no charge.
+
+ 1.12. "You" (or "Your") means an individual or a legal entity
+ exercising rights under, and complying with all of the terms of, this
+ License or a future version of this License issued under Section 6.1.
+ For legal entities, "You" includes any entity which controls, is
+ controlled by, or is under common control with You. For purposes of
+ this definition, "control" means (a) the power, direct or indirect,
+ to cause the direction or management of such entity, whether by
+ contract or otherwise, or (b) ownership of more than fifty percent
+ (50%) of the outstanding shares or beneficial ownership of such
+ entity.
+
+2. Source Code License.
+
+ 2.1. The Initial Developer Grant.
+ The Initial Developer hereby grants You a world-wide, royalty-free,
+ non-exclusive license, subject to third party intellectual property
+ claims:
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Initial Developer to use, reproduce,
+ modify, display, perform, sublicense and distribute the Original
+ Code (or portions thereof) with or without Modifications, and/or
+ as part of a Larger Work; and
+
+ (b) under Patents Claims infringed by the making, using or
+ selling of Original Code, to make, have made, use, practice,
+ sell, and offer for sale, and/or otherwise dispose of the
+ Original Code (or portions thereof).
+
+ (c) the licenses granted in this Section 2.1(a) and (b) are
+ effective on the date Initial Developer first distributes
+ Original Code under the terms of this License.
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is
+ granted: 1) for code that You delete from the Original Code; 2)
+ separate from the Original Code; or 3) for infringements caused
+ by: i) the modification of the Original Code or ii) the
+ combination of the Original Code with other software or devices.
+
+ 2.2. Contributor Grant.
+ Subject to third party intellectual property claims, each Contributor
+ hereby grants You a world-wide, royalty-free, non-exclusive license
+
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Contributor, to use, reproduce, modify,
+ display, perform, sublicense and distribute the Modifications
+ created by such Contributor (or portions thereof) either on an
+ unmodified basis, with other Modifications, as Covered Code
+ and/or as part of a Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using, or
+ selling of Modifications made by that Contributor either alone
+ and/or in combination with its Contributor Version (or portions
+ of such combination), to make, use, sell, offer for sale, have
+ made, and/or otherwise dispose of: 1) Modifications made by that
+ Contributor (or portions thereof); and 2) the combination of
+ Modifications made by that Contributor with its Contributor
+ Version (or portions of such combination).
+
+ (c) the licenses granted in Sections 2.2(a) and 2.2(b) are
+ effective on the date Contributor first makes Commercial Use of
+ the Covered Code.
+
+ (d) Notwithstanding Section 2.2(b) above, no patent license is
+ granted: 1) for any code that Contributor has deleted from the
+ Contributor Version; 2) separate from the Contributor Version;
+ 3) for infringements caused by: i) third party modifications of
+ Contributor Version or ii) the combination of Modifications made
+ by that Contributor with other software (except as part of the
+ Contributor Version) or other devices; or 4) under Patent Claims
+ infringed by Covered Code in the absence of Modifications made by
+ that Contributor.
+
+3. Distribution Obligations.
+
+ 3.1. Application of License.
+ The Modifications which You create or to which You contribute are
+ governed by the terms of this License, including without limitation
+ Section 2.2. The Source Code version of Covered Code may be
+ distributed only under the terms of this License or a future version
+ of this License released under Section 6.1, and You must include a
+ copy of this License with every copy of the Source Code You
+ distribute. You may not offer or impose any terms on any Source Code
+ version that alters or restricts the applicable version of this
+ License or the recipients' rights hereunder. However, You may include
+ an additional document offering the additional rights described in
+ Section 3.5.
+
+ 3.2. Availability of Source Code.
+ Any Modification which You create or to which You contribute must be
+ made available in Source Code form under the terms of this License
+ either on the same media as an Executable version or via an accepted
+ Electronic Distribution Mechanism to anyone to whom you made an
+ Executable version available; and if made available via Electronic
+ Distribution Mechanism, must remain available for at least twelve (12)
+ months after the date it initially became available, or at least six
+ (6) months after a subsequent version of that particular Modification
+ has been made available to such recipients. You are responsible for
+ ensuring that the Source Code version remains available even if the
+ Electronic Distribution Mechanism is maintained by a third party.
+
+ 3.3. Description of Modifications.
+ You must cause all Covered Code to which You contribute to contain a
+ file documenting the changes You made to create that Covered Code and
+ the date of any change. You must include a prominent statement that
+ the Modification is derived, directly or indirectly, from Original
+ Code provided by the Initial Developer and including the name of the
+ Initial Developer in (a) the Source Code, and (b) in any notice in an
+ Executable version or related documentation in which You describe the
+ origin or ownership of the Covered Code.
+
+ 3.4. Intellectual Property Matters
+ (a) Third Party Claims.
+ If Contributor has knowledge that a license under a third party's
+ intellectual property rights is required to exercise the rights
+ granted by such Contributor under Sections 2.1 or 2.2,
+ Contributor must include a text file with the Source Code
+ distribution titled "LEGAL" which describes the claim and the
+ party making the claim in sufficient detail that a recipient will
+ know whom to contact. If Contributor obtains such knowledge after
+ the Modification is made available as described in Section 3.2,
+ Contributor shall promptly modify the LEGAL file in all copies
+ Contributor makes available thereafter and shall take other steps
+ (such as notifying appropriate mailing lists or newsgroups)
+ reasonably calculated to inform those who received the Covered
+ Code that new knowledge has been obtained.
+
+ (b) Contributor APIs.
+ If Contributor's Modifications include an application programming
+ interface and Contributor has knowledge of patent licenses which
+ are reasonably necessary to implement that API, Contributor must
+ also include this information in the LEGAL file.
+
+ (c) Representations.
+ Contributor represents that, except as disclosed pursuant to
+ Section 3.4(a) above, Contributor believes that Contributor's
+ Modifications are Contributor's original creation(s) and/or
+ Contributor has sufficient rights to grant the rights conveyed by
+ this License.
+
+ 3.5. Required Notices.
+ You must duplicate the notice in Exhibit A in each file of the Source
+ Code. If it is not possible to put such notice in a particular Source
+ Code file due to its structure, then You must include such notice in a
+ location (such as a relevant directory) where a user would be likely
+ to look for such a notice. If You created one or more Modification(s)
+ You may add your name as a Contributor to the notice described in
+ Exhibit A. You must also duplicate this License in any documentation
+ for the Source Code where You describe recipients' rights or ownership
+ rights relating to Covered Code. You may choose to offer, and to
+ charge a fee for, warranty, support, indemnity or liability
+ obligations to one or more recipients of Covered Code. However, You
+ may do so only on Your own behalf, and not on behalf of the Initial
+ Developer or any Contributor. You must make it absolutely clear than
+ any such warranty, support, indemnity or liability obligation is
+ offered by You alone, and You hereby agree to indemnify the Initial
+ Developer and every Contributor for any liability incurred by the
+ Initial Developer or such Contributor as a result of warranty,
+ support, indemnity or liability terms You offer.
+
+ 3.6. Distribution of Executable Versions.
+ You may distribute Covered Code in Executable form only if the
+ requirements of Section 3.1-3.5 have been met for that Covered Code,
+ and if You include a notice stating that the Source Code version of
+ the Covered Code is available under the terms of this License,
+ including a description of how and where You have fulfilled the
+ obligations of Section 3.2. The notice must be conspicuously included
+ in any notice in an Executable version, related documentation or
+ collateral in which You describe recipients' rights relating to the
+ Covered Code. You may distribute the Executable version of Covered
+ Code or ownership rights under a license of Your choice, which may
+ contain terms different from this License, provided that You are in
+ compliance with the terms of this License and that the license for the
+ Executable version does not attempt to limit or alter the recipient's
+ rights in the Source Code version from the rights set forth in this
+ License. If You distribute the Executable version under a different
+ license You must make it absolutely clear that any terms which differ
+ from this License are offered by You alone, not by the Initial
+ Developer or any Contributor. You hereby agree to indemnify the
+ Initial Developer and every Contributor for any liability incurred by
+ the Initial Developer or such Contributor as a result of any such
+ terms You offer.
+
+ 3.7. Larger Works.
+ You may create a Larger Work by combining Covered Code with other code
+ not governed by the terms of this License and distribute the Larger
+ Work as a single product. In such a case, You must make sure the
+ requirements of this License are fulfilled for the Covered Code.
+
+4. Inability to Comply Due to Statute or Regulation.
+
+ If it is impossible for You to comply with any of the terms of this
+ License with respect to some or all of the Covered Code due to
+ statute, judicial order, or regulation then You must: (a) comply with
+ the terms of this License to the maximum extent possible; and (b)
+ describe the limitations and the code they affect. Such description
+ must be included in the LEGAL file described in Section 3.4 and must
+ be included with all distributions of the Source Code. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Application of this License.
+
+ This License applies to code to which the Initial Developer has
+ attached the notice in Exhibit A and to related Covered Code.
+
+6. Versions of the License.
+
+ 6.1. New Versions.
+ Netscape Communications Corporation ("Netscape") may publish revised
+ and/or new versions of the License from time to time. Each version
+ will be given a distinguishing version number.
+
+ 6.2. Effect of New Versions.
+ Once Covered Code has been published under a particular version of the
+ License, You may always continue to use it under the terms of that
+ version. You may also choose to use such Covered Code under the terms
+ of any subsequent version of the License published by Netscape. No one
+ other than Netscape has the right to modify the terms applicable to
+ Covered Code created under this License.
+
+ 6.3. Derivative Works.
+ If You create or use a modified version of this License (which you may
+ only do in order to apply it to code which is not already Covered Code
+ governed by this License), You must (a) rename Your license so that
+ the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
+ "MPL", "NPL" or any confusingly similar phrase do not appear in your
+ license (except to note that your license differs from this License)
+ and (b) otherwise make it clear that Your version of the license
+ contains terms which differ from the Mozilla Public License and
+ Netscape Public License. (Filling in the name of the Initial
+ Developer, Original Code or Contributor in the notice described in
+ Exhibit A shall not of themselves be deemed to be modifications of
+ this License.)
+
+7. DISCLAIMER OF WARRANTY.
+
+ COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+ WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
+ DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
+ THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
+ IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
+ YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
+ COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
+ OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
+ ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+8. TERMINATION.
+
+ 8.1. This License and the rights granted hereunder will terminate
+ automatically if You fail to comply with terms herein and fail to cure
+ such breach within 30 days of becoming aware of the breach. All
+ sublicenses to the Covered Code which are properly granted shall
+ survive any termination of this License. Provisions which, by their
+ nature, must remain in effect beyond the termination of this License
+ shall survive.
+
+ 8.2. If You initiate litigation by asserting a patent infringement
+ claim (excluding declatory judgment actions) against Initial Developer
+ or a Contributor (the Initial Developer or Contributor against whom
+ You file such action is referred to as "Participant") alleging that:
+
+ (a) such Participant's Contributor Version directly or indirectly
+ infringes any patent, then any and all rights granted by such
+ Participant to You under Sections 2.1 and/or 2.2 of this License
+ shall, upon 60 days notice from Participant terminate prospectively,
+ unless if within 60 days after receipt of notice You either: (i)
+ agree in writing to pay Participant a mutually agreeable reasonable
+ royalty for Your past and future use of Modifications made by such
+ Participant, or (ii) withdraw Your litigation claim with respect to
+ the Contributor Version against such Participant. If within 60 days
+ of notice, a reasonable royalty and payment arrangement are not
+ mutually agreed upon in writing by the parties or the litigation claim
+ is not withdrawn, the rights granted by Participant to You under
+ Sections 2.1 and/or 2.2 automatically terminate at the expiration of
+ the 60 day notice period specified above.
+
+ (b) any software, hardware, or device, other than such Participant's
+ Contributor Version, directly or indirectly infringes any patent, then
+ any rights granted to You by such Participant under Sections 2.1(b)
+ and 2.2(b) are revoked effective as of the date You first made, used,
+ sold, distributed, or had made, Modifications made by that
+ Participant.
+
+ 8.3. If You assert a patent infringement claim against Participant
+ alleging that such Participant's Contributor Version directly or
+ indirectly infringes any patent where such claim is resolved (such as
+ by license or settlement) prior to the initiation of patent
+ infringement litigation, then the reasonable value of the licenses
+ granted by such Participant under Sections 2.1 or 2.2 shall be taken
+ into account in determining the amount or value of any payment or
+ license.
+
+ 8.4. In the event of termination under Sections 8.1 or 8.2 above,
+ all end user license agreements (excluding distributors and resellers)
+ which have been validly granted by You or any distributor hereunder
+ prior to termination shall survive termination.
+
+9. LIMITATION OF LIABILITY.
+
+ UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
+ (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
+ DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
+ OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
+ ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
+ CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
+ WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
+ COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
+ INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
+ LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
+ RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
+ PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
+ EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
+ THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+10. U.S. GOVERNMENT END USERS.
+
+ The Covered Code is a "commercial item," as that term is defined in
+ 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
+ software" and "commercial computer software documentation," as such
+ terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
+ C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
+ all U.S. Government End Users acquire Covered Code with only those
+ rights set forth herein.
+
+11. MISCELLANEOUS.
+
+ This License represents the complete agreement concerning subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. This License shall be governed by
+ California law provisions (except to the extent applicable law, if
+ any, provides otherwise), excluding its conflict-of-law provisions.
+ With respect to disputes in which at least one party is a citizen of,
+ or an entity chartered or registered to do business in the United
+ States of America, any litigation relating to this License shall be
+ subject to the jurisdiction of the Federal Courts of the Northern
+ District of California, with venue lying in Santa Clara County,
+ California, with the losing party responsible for costs, including
+ without limitation, court costs and reasonable attorneys' fees and
+ expenses. The application of the United Nations Convention on
+ Contracts for the International Sale of Goods is expressly excluded.
+ Any law or regulation which provides that the language of a contract
+ shall be construed against the drafter shall not apply to this
+ License.
+
+12. RESPONSIBILITY FOR CLAIMS.
+
+ As between Initial Developer and the Contributors, each party is
+ responsible for claims and damages arising, directly or indirectly,
+ out of its utilization of rights under this License and You agree to
+ work with Initial Developer and Contributors to distribute such
+ responsibility on an equitable basis. Nothing herein is intended or
+ shall be deemed to constitute any admission of liability.
+
+13. MULTIPLE-LICENSED CODE.
+
+ Initial Developer may designate portions of the Covered Code as
+ "Multiple-Licensed". "Multiple-Licensed" means that the Initial
+ Developer permits you to utilize portions of the Covered Code under
+ Your choice of the NPL or the alternative licenses, if any, specified
+ by the Initial Developer in the file described in Exhibit A.
+
+EXHIBIT A -Mozilla Public License.
+
+ ``The contents of this file are subject to the Mozilla Public License
+ Version 1.1 (the "License"); you may not use this file except in
+ compliance with the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS"
+ basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ License for the specific language governing rights and limitations
+ under the License.
+
+ The Original Code is ______________________________________.
+
+ The Initial Developer of the Original Code is ________________________.
+ Portions created by ______________________ are Copyright (C) ______
+ _______________________. All Rights Reserved.
+
+ Contributor(s): ______________________________________.
+
+ Alternatively, the contents of this file may be used under the terms
+ of the _____ license (the "[___] License"), in which case the
+ provisions of [______] License are applicable instead of those
+ above. If you wish to allow use of your version of this file only
+ under the terms of the [____] License and not to allow others to use
+ your version of this file under the MPL, indicate your decision by
+ deleting the provisions above and replace them with the notice and
+ other provisions required by the [___] License. If you do not delete
+ the provisions above, a recipient may use your version of this file
+ under either the MPL or the [___] License."
+
+ [NOTE: The text of this Exhibit A may differ slightly from the text of
+ the notices in the Source Code files of the Original Code. You should
+ use the text of this Exhibit A rather than the text found in the
+ Original Code Source Code for Your Modifications.]
+
diff --git a/guacamole-common-js/README b/guacamole-common-js/README
new file mode 100644
index 0000000..3929fe4
--- /dev/null
+++ b/guacamole-common-js/README
@@ -0,0 +1,78 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-common-js?
+------------------------------------------------------------
+
+guacamole-common-js is the core JavaScript library used by the Guacamole web
+application.
+
+guacamole-common-js provides an efficient HTTP tunnel for transporting
+protocol data between JavaScript and the web application, as well as an
+implementation of a Guacamole protocol client and abstract synchronized
+drawing layers.
+
+
+------------------------------------------------------------
+ Compiling and installing guacamole-common-js
+------------------------------------------------------------
+
+guacamole-common-js is built using Maven. Note that this is JavaScript code
+and not actually compiled. "Building" guacamole-common-js actually simply
+packages it into a redistributable .zip file. This .zip file can be easily
+included and expanded into other Maven-based projects (like Guacamole).
+
+Note that prebuilt versions of guacamole-common-js are available from the
+main guac-dev.org Maven repository which is referenced in all Maven
+projects in Guacamole. Unless you want to make changes to guacamole-common-js
+or you want to use a newer, unreleased version (such as the unstable branch),
+you do not need to build this manually. You can let Maven download it for
+you when you build Guacamole.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .zip file.
+ Once all dependencies have been downloaded, the .zip file will be
+ created in the target/ subdirectory of the current directory.
+
+2) Run mvn install
+
+ $ mvn install
+
+ DO NOT RUN THIS AS ROOT!
+
+ Maven will install guacamole-common-js to your user's local Maven
+ repository where it can be used in future builds. It will not install
+ into a system-wide repository and does not require root privileges.
+
+ Once installed, building other Maven projects that depend on
+ guacamole-common-js (such as Guacamole) will be possible.
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/guacamole-common-js/doc/guacamole-osk.dtd b/guacamole-common-js/doc/guacamole-osk.dtd
new file mode 100644
index 0000000..e3a4689
--- /dev/null
+++ b/guacamole-common-js/doc/guacamole-osk.dtd
@@ -0,0 +1,32 @@
+<!--
+
+<!DOCTYPE keyboard PUBLIC
+ "-//Guacamole/Guacamole Onscreen Keyboard DTD 0.6.0//EN"
+ "http://guac-dev.org/pub/dtd/guacamole-osk-0.6.0.dtd">
+
+-->
+
+<!ELEMENT keyboard ((row|column)*)>
+ <!ATTLIST keyboard size CDATA #REQUIRED>
+ <!ATTLIST keyboard lang CDATA #REQUIRED>
+ <!ATTLIST keyboard layout CDATA #REQUIRED>
+
+<!ELEMENT column (row*)>
+ <!ATTLIST column align (left|center|right) "left">
+
+<!ELEMENT row ((column|gap|key)*)>
+
+<!ELEMENT gap EMPTY>
+ <!ATTLIST gap size CDATA #IMPLIED>
+
+<!ELEMENT key (cap*)>
+ <!ATTLIST key size CDATA #IMPLIED>
+ <!ATTLIST key class CDATA #IMPLIED>
+
+<!ELEMENT cap ANY>
+ <!ATTLIST cap if CDATA #IMPLIED>
+ <!ATTLIST cap modifier CDATA #IMPLIED>
+ <!ATTLIST cap keysym CDATA #IMPLIED>
+ <!ATTLIST cap sticky (true|false) "false">
+ <!ATTLIST cap class CDATA #IMPLIED>
+
diff --git a/guacamole-common-js/pom.xml b/guacamole-common-js/pom.xml
new file mode 100644
index 0000000..2ede1ea
--- /dev/null
+++ b/guacamole-common-js/pom.xml
@@ -0,0 +1,87 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common-js</artifactId>
+ <packaging>pom</packaging>
+ <version>0.7.4</version>
+ <name>guacamole-common-js</name>
+ <url>http://guac-dev.org/</url>
+
+ <description>
+ The base JavaScript API of the Guacamole project, providing JavaScript
+ support for the Guacamole stack, including a full client
+ implementation for the Guacamole protocol.
+ </description>
+
+ <!-- All applicable licenses -->
+ <licenses>
+ <license>
+ <name>Mozilla Public License Version 1.1</name>
+ <url>http://www.mozilla.org/MPL/1.1/</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>GNU General Public License, version 2</name>
+ <url>http://www.gnu.org/licenses/gpl-2.0.html</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>GNU Lesser General Public License, version 2.1</name>
+ <url>http://www.gnu.org/licenses/lgpl-2.1.html</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <!-- Git repository -->
+ <scm>
+ <url>https://github.com/glyptodon/guacamole-client</url>
+ <connection>scm:git:git://github.com/glyptodon/guacamole-client.git</connection>
+ </scm>
+
+ <!-- Developers -->
+ <developers>
+ <developer>
+ <id>mike.jumper</id>
+ <name>Michael Jumper</name>
+ <email>mike.jumper at guac-dev.org</email>
+ </developer>
+ <developer>
+ <id>james.muehlner</id>
+ <name>James Muehlner</name>
+ <email>james.muehlner at guac-dev.org</email>
+ </developer>
+ </developers>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.4</version>
+ <configuration>
+ <appendAssemblyId>false</appendAssemblyId>
+ <descriptors>
+ <descriptor>static.xml</descriptor>
+ </descriptors>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-zip</id>
+ <phase>package</phase>
+ <goals>
+ <goal>attached</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </build>
+
+</project>
diff --git a/guacamole-common-js/src/main/resources/audio.js b/guacamole-common-js/src/main/resources/audio.js
new file mode 100644
index 0000000..8a3243c
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/audio.js
@@ -0,0 +1,228 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Abstract audio channel which queues and plays arbitrary audio data.
+ * @constructor
+ */
+Guacamole.AudioChannel = function() {
+
+ /**
+ * Reference to this AudioChannel.
+ * @private
+ */
+ var channel = this;
+
+ /**
+ * When the next packet should play.
+ * @private
+ */
+ var next_packet_time = 0;
+
+ /**
+ * Queues up the given data for playing by this channel once all previously
+ * queued data has been played. If no data has been queued, the data will
+ * play immediately.
+ *
+ * @param {String} mimetype The mimetype of the data provided.
+ * @param {Number} duration The duration of the data provided, in
+ * milliseconds.
+ * @param {String} data The base64-encoded data to play.
+ */
+ this.play = function(mimetype, duration, data) {
+
+ var packet =
+ new Guacamole.AudioChannel.Packet(mimetype, data);
+
+ var now = Guacamole.AudioChannel.getTimestamp();
+
+ // If underflow is detected, reschedule new packets relative to now.
+ if (next_packet_time < now)
+ next_packet_time = now;
+
+ // Schedule next packet
+ packet.play(next_packet_time);
+ next_packet_time += duration;
+
+ };
+
+};
+
+// Define context if available
+if (window.webkitAudioContext) {
+ Guacamole.AudioChannel.context = new webkitAudioContext();
+}
+
+/**
+ * Returns a base timestamp which can be used for scheduling future audio
+ * playback. Scheduling playback for the value returned by this function plus
+ * N will cause the associated audio to be played back N milliseconds after
+ * the function is called.
+ *
+ * @return {Number} An arbitrary channel-relative timestamp, in milliseconds.
+ */
+Guacamole.AudioChannel.getTimestamp = function() {
+
+ // If we have an audio context, use its timestamp
+ if (Guacamole.AudioChannel.context)
+ return Guacamole.AudioChannel.context.currentTime * 1000;
+
+ // If we have high-resolution timers, use those
+ if (window.performance) {
+
+ if (window.performance.now)
+ return window.performance.now();
+
+ if (window.performance.webkitNow)
+ return window.performance.webkitNow();
+
+ }
+
+ // Fallback to millisecond-resolution system time
+ return new Date().getTime();
+
+};
+
+/**
+ * Abstract representation of an audio packet.
+ *
+ * @constructor
+ *
+ * @param {String} mimetype The mimetype of the data contained by this packet.
+ * @param {String} data The base64-encoded sound data contained by this packet.
+ */
+Guacamole.AudioChannel.Packet = function(mimetype, data) {
+
+ /**
+ * Schedules this packet for playback at the given time.
+ *
+ * @function
+ * @param {Number} when The time this packet should be played, in
+ * milliseconds.
+ */
+ this.play = undefined; // Defined conditionally depending on support
+
+ // If audio API available, use it.
+ if (Guacamole.AudioChannel.context) {
+
+ var readyBuffer = null;
+
+ // By default, when decoding finishes, store buffer for future
+ // playback
+ var handleReady = function(buffer) {
+ readyBuffer = buffer;
+ };
+
+ // Convert to ArrayBuffer
+ var binary = window.atob(data);
+ var arrayBuffer = new ArrayBuffer(binary.length);
+ var bufferView = new Uint8Array(arrayBuffer);
+
+ for (var i=0; i<binary.length; i++)
+ bufferView[i] = binary.charCodeAt(i);
+
+ // Get context and start decoding
+ Guacamole.AudioChannel.context.decodeAudioData(
+ arrayBuffer,
+ function(buffer) { handleReady(buffer); }
+ );
+
+ // Set up buffer source
+ var source = Guacamole.AudioChannel.context.createBufferSource();
+ source.connect(Guacamole.AudioChannel.context.destination);
+
+ var play_when;
+
+ function playDelayed(buffer) {
+ source.buffer = buffer;
+ source.noteOn(play_when / 1000);
+ }
+
+ /** @ignore */
+ this.play = function(when) {
+
+ play_when = when;
+
+ // If buffer available, play it NOW
+ if (readyBuffer)
+ playDelayed(readyBuffer);
+
+ // Otherwise, play when decoded
+ else
+ handleReady = playDelayed;
+
+ };
+
+ }
+
+ else {
+
+ // Build data URI
+ var data_uri = "data:" + mimetype + ";base64," + data;
+
+ // Create audio element to house and play the data
+ var audio = new Audio();
+ audio.src = data_uri;
+
+ /** @ignore */
+ this.play = function(when) {
+
+ // Calculate time until play
+ var now = Guacamole.AudioChannel.getTimestamp();
+ var delay = when - now;
+
+ // Play now if too late
+ if (delay < 0)
+ audio.play();
+
+ // Otherwise, schedule later playback
+ else
+ window.setTimeout(function() {
+ audio.play();
+ }, delay);
+
+ };
+
+ }
+
+};
diff --git a/guacamole-common-js/src/main/resources/guacamole.js b/guacamole-common-js/src/main/resources/guacamole.js
new file mode 100644
index 0000000..01765a1
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/guacamole.js
@@ -0,0 +1,1662 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * Matt Hortman
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Simple Guacamole protocol parser that invokes an oninstruction event when
+ * full instructions are available from data received via receive().
+ *
+ * @constructor
+ */
+Guacamole.Parser = function() {
+
+ /**
+ * Reference to this parser.
+ * @private
+ */
+ var parser = this;
+
+ /**
+ * Current buffer of received data. This buffer grows until a full
+ * element is available. After a full element is available, that element
+ * is flushed into the element buffer.
+ *
+ * @private
+ */
+ var buffer = "";
+
+ /**
+ * Buffer of all received, complete elements. After an entire instruction
+ * is read, this buffer is flushed, and a new instruction begins.
+ *
+ * @private
+ */
+ var element_buffer = [];
+
+ // The location of the last element's terminator
+ var element_end = -1;
+
+ // Where to start the next length search or the next element
+ var start_index = 0;
+
+ /**
+ * Appends the given instruction data packet to the internal buffer of
+ * this Guacamole.Parser, executing all completed instructions at
+ * the beginning of this buffer, if any.
+ *
+ * @param {String} packet The instruction data to append.
+ */
+ this.receive = function(packet) {
+
+ // Truncate buffer as necessary
+ if (start_index > 4096 && element_end >= start_index) {
+
+ buffer = buffer.substring(start_index);
+
+ // Reset parse relative to truncation
+ element_end -= start_index;
+ start_index = 0;
+
+ }
+
+ // Append data to buffer
+ buffer += packet;
+
+ // While search is within currently received data
+ while (element_end < buffer.length) {
+
+ // If we are waiting for element data
+ if (element_end >= start_index) {
+
+ // We now have enough data for the element. Parse.
+ var element = buffer.substring(start_index, element_end);
+ var terminator = buffer.substring(element_end, element_end+1);
+
+ // Add element to array
+ element_buffer.push(element);
+
+ // If last element, handle instruction
+ if (terminator == ";") {
+
+ // Get opcode
+ var opcode = element_buffer.shift();
+
+ // Call instruction handler.
+ if (parser.oninstruction != null)
+ parser.oninstruction(opcode, element_buffer);
+
+ // Clear elements
+ element_buffer.length = 0;
+
+ }
+ else if (terminator != ',')
+ throw new Error("Illegal terminator.");
+
+ // Start searching for length at character after
+ // element terminator
+ start_index = element_end + 1;
+
+ }
+
+ // Search for end of length
+ var length_end = buffer.indexOf(".", start_index);
+ if (length_end != -1) {
+
+ // Parse length
+ var length = parseInt(buffer.substring(element_end+1, length_end));
+ if (length == NaN)
+ throw new Error("Non-numeric character in element length.");
+
+ // Calculate start of element
+ start_index = length_end + 1;
+
+ // Calculate location of element terminator
+ element_end = start_index + length;
+
+ }
+
+ // If no period yet, continue search when more data
+ // is received
+ else {
+ start_index = buffer.length;
+ break;
+ }
+
+ } // end parse loop
+
+ };
+
+ /**
+ * Fired once for every complete Guacamole instruction received, in order.
+ *
+ * @event
+ * @param {String} opcode The Guacamole instruction opcode.
+ * @param {Array} parameters The parameters provided for the instruction,
+ * if any.
+ */
+ this.oninstruction = null;
+
+};
+
+
+/**
+ * A blob abstraction used by the Guacamole client to facilitate transfer of
+ * files or other binary data.
+ *
+ * @constructor
+ * @param {String} mimetype The mimetype of the data this blob will contain.
+ * @param {String} name An arbitrary name for this blob.
+ */
+Guacamole.Blob = function(mimetype, name) {
+
+ /**
+ * Reference to this Guacamole.Blob.
+ * @private
+ */
+ var guac_blob = this;
+
+ /**
+ * The length of this Guacamole.Blob in bytes.
+ * @private
+ */
+ var length = 0;
+
+ /**
+ * The mimetype of the data contained within this blob.
+ */
+ this.mimetype = mimetype;
+
+ /**
+ * The name of this blob. In general, this should be an appropriate
+ * filename.
+ */
+ this.name = name;
+
+ // Get blob builder
+ var blob_builder;
+ if (window.BlobBuilder) blob_builder = new BlobBuilder();
+ else if (window.WebKitBlobBuilder) blob_builder = new WebKitBlobBuilder();
+ else if (window.MozBlobBuilder) blob_builder = new MozBlobBuilder();
+ else
+ blob_builder = new (function() {
+
+ var blobs = [];
+
+ this.append = function(data) {
+ blobs.push(new Blob([data], {"type": mimetype}));
+ };
+
+ this.getBlob = function() {
+ return new Blob(blobs, {"type": mimetype});
+ };
+
+ })();
+
+ /**
+ * Appends the given ArrayBuffer to this Guacamole.Blob.
+ *
+ * @param {ArrayBuffer} buffer An ArrayBuffer containing the data to be
+ * appended.
+ */
+ this.append = function(buffer) {
+
+ blob_builder.append(buffer);
+ length += buffer.byteLength;
+
+ // Call handler, if present
+ if (guac_blob.ondata)
+ guac_blob.ondata(buffer.byteLength);
+
+ };
+
+ /**
+ * Closes this Guacamole.Blob such that no further data will be written.
+ */
+ this.close = function() {
+
+ // Call handler, if present
+ if (guac_blob.oncomplete)
+ guac_blob.oncomplete();
+
+ // NOTE: Currently not enforced.
+
+ };
+
+ /**
+ * Returns the current length of this Guacamole.Blob, in bytes.
+ * @return {Number} The current length of this Guacamole.Blob.
+ */
+ this.getLength = function() {
+ return length;
+ };
+
+ /**
+ * Returns the contents of this Guacamole.Blob as a Blob.
+ * @return {Blob} The contents of this Guacamole.Blob.
+ */
+ this.getBlob = function() {
+ return blob_builder.getBlob();
+ };
+
+ /**
+ * Fired once for every blob of data received.
+ *
+ * @event
+ * @param {Number} length The number of bytes received.
+ */
+ this.ondata = null;
+
+ /**
+ * Fired once this blob is finished and no further data will be written.
+ * @event
+ */
+ this.oncomplete = null;
+
+};
+
+
+/**
+ * Guacamole protocol client. Given a display element and {@link Guacamole.Tunnel},
+ * automatically handles incoming and outgoing Guacamole instructions via the
+ * provided tunnel, updating the display using one or more canvas elements.
+ *
+ * @constructor
+ * @param {Guacamole.Tunnel} tunnel The tunnel to use to send and receive
+ * Guacamole instructions.
+ */
+Guacamole.Client = function(tunnel) {
+
+ var guac_client = this;
+
+ var STATE_IDLE = 0;
+ var STATE_CONNECTING = 1;
+ var STATE_WAITING = 2;
+ var STATE_CONNECTED = 3;
+ var STATE_DISCONNECTING = 4;
+ var STATE_DISCONNECTED = 5;
+
+ var currentState = STATE_IDLE;
+
+ var currentTimestamp = 0;
+ var pingInterval = null;
+
+ var displayWidth = 0;
+ var displayHeight = 0;
+ var displayScale = 1;
+
+ /**
+ * Translation from Guacamole protocol line caps to Layer line caps.
+ * @private
+ */
+ var lineCap = {
+ 0: "butt",
+ 1: "round",
+ 2: "square"
+ };
+
+ /**
+ * Translation from Guacamole protocol line caps to Layer line caps.
+ * @private
+ */
+ var lineJoin = {
+ 0: "bevel",
+ 1: "miter",
+ 2: "round"
+ };
+
+ // Create bounding div
+ var bounds = document.createElement("div");
+ bounds.style.position = "relative";
+ bounds.style.width = (displayWidth*displayScale) + "px";
+ bounds.style.height = (displayHeight*displayScale) + "px";
+
+ // Create display
+ var display = document.createElement("div");
+ display.style.position = "relative";
+ display.style.width = displayWidth + "px";
+ display.style.height = displayHeight + "px";
+
+ // Ensure transformations on display originate at 0,0
+ display.style.transformOrigin =
+ display.style.webkitTransformOrigin =
+ display.style.MozTransformOrigin =
+ display.style.OTransformOrigin =
+ display.style.msTransformOrigin =
+ "0 0";
+
+ // Create default layer
+ var default_layer_container = new Guacamole.Client.LayerContainer(displayWidth, displayHeight);
+
+ // Position default layer
+ var default_layer_container_element = default_layer_container.getElement();
+ default_layer_container_element.style.position = "absolute";
+ default_layer_container_element.style.left = "0px";
+ default_layer_container_element.style.top = "0px";
+ default_layer_container_element.style.overflow = "hidden";
+
+ // Create cursor layer
+ var cursor = new Guacamole.Client.LayerContainer(0, 0);
+ cursor.getLayer().setChannelMask(Guacamole.Layer.SRC);
+ cursor.getLayer().autoflush = true;
+
+ // Position cursor layer
+ var cursor_element = cursor.getElement();
+ cursor_element.style.position = "absolute";
+ cursor_element.style.left = "0px";
+ cursor_element.style.top = "0px";
+
+ // Add default layer and cursor to display
+ display.appendChild(default_layer_container.getElement());
+ display.appendChild(cursor.getElement());
+
+ // Add display to bounds
+ bounds.appendChild(display);
+
+ // Initially, only default layer exists
+ var layers = [default_layer_container];
+
+ // No initial buffers
+ var buffers = [];
+
+ // No initial parsers
+ var parsers = [];
+
+ // No initial audio channels
+ var audio_channels = [];
+
+ // No initial blobs
+ var blobs = [];
+
+ tunnel.onerror = function(message) {
+ if (guac_client.onerror)
+ guac_client.onerror(message);
+ };
+
+ function setState(state) {
+ if (state != currentState) {
+ currentState = state;
+ if (guac_client.onstatechange)
+ guac_client.onstatechange(currentState);
+ }
+ }
+
+ function isConnected() {
+ return currentState == STATE_CONNECTED
+ || currentState == STATE_WAITING;
+ }
+
+ var cursorHotspotX = 0;
+ var cursorHotspotY = 0;
+
+ var cursorX = 0;
+ var cursorY = 0;
+
+ function moveCursor(x, y) {
+
+ // Move cursor layer
+ cursor.translate(x - cursorHotspotX, y - cursorHotspotY);
+
+ // Update stored position
+ cursorX = x;
+ cursorY = y;
+
+ }
+
+ /**
+ * Returns an element containing the display of this Guacamole.Client.
+ * Adding the element returned by this function to an element in the body
+ * of a document will cause the client's display to be visible.
+ *
+ * @return {Element} An element containing ths display of this
+ * Guacamole.Client.
+ */
+ this.getDisplay = function() {
+ return bounds;
+ };
+
+ /**
+ * Sends the current size of the screen.
+ *
+ * @param {Number} width The width of the screen.
+ * @param {Number} height The height of the screen.
+ */
+ this.sendSize = function(width, height) {
+
+ // Do not send requests if not connected
+ if (!isConnected())
+ return;
+
+ tunnel.sendMessage("size", width, height);
+
+ };
+
+ /**
+ * Sends a key event having the given properties as if the user
+ * pressed or released a key.
+ *
+ * @param {Boolean} pressed Whether the key is pressed (true) or released
+ * (false).
+ * @param {Number} keysym The keysym of the key being pressed or released.
+ */
+ this.sendKeyEvent = function(pressed, keysym) {
+ // Do not send requests if not connected
+ if (!isConnected())
+ return;
+
+ tunnel.sendMessage("key", keysym, pressed);
+ };
+
+ /**
+ * Sends a mouse event having the properties provided by the given mouse
+ * state.
+ *
+ * @param {Guacamole.Mouse.State} mouseState The state of the mouse to send
+ * in the mouse event.
+ */
+ this.sendMouseState = function(mouseState) {
+
+ // Do not send requests if not connected
+ if (!isConnected())
+ return;
+
+ // Update client-side cursor
+ moveCursor(
+ Math.floor(mouseState.x),
+ Math.floor(mouseState.y)
+ );
+
+ // Build mask
+ var buttonMask = 0;
+ if (mouseState.left) buttonMask |= 1;
+ if (mouseState.middle) buttonMask |= 2;
+ if (mouseState.right) buttonMask |= 4;
+ if (mouseState.up) buttonMask |= 8;
+ if (mouseState.down) buttonMask |= 16;
+
+ // Send message
+ tunnel.sendMessage("mouse", Math.floor(mouseState.x), Math.floor(mouseState.y), buttonMask);
+ };
+
+ /**
+ * Sets the clipboard of the remote client to the given text data.
+ *
+ * @param {String} data The data to send as the clipboard contents.
+ */
+ this.setClipboard = function(data) {
+
+ // Do not send requests if not connected
+ if (!isConnected())
+ return;
+
+ tunnel.sendMessage("clipboard", data);
+ };
+
+ /**
+ * Fired whenever the state of this Guacamole.Client changes.
+ *
+ * @event
+ * @param {Number} state The new state of the client.
+ */
+ this.onstatechange = null;
+
+ /**
+ * Fired when the remote client sends a name update.
+ *
+ * @event
+ * @param {String} name The new name of this client.
+ */
+ this.onname = null;
+
+ /**
+ * Fired when an error is reported by the remote client, and the connection
+ * is being closed.
+ *
+ * @event
+ * @param {String} error A human-readable description of the error.
+ */
+ this.onerror = null;
+
+ /**
+ * Fired when the clipboard of the remote client is changing.
+ *
+ * @event
+ * @param {String} data The new text data of the remote clipboard.
+ */
+ this.onclipboard = null;
+
+ /**
+ * Fired when the default layer (and thus the entire Guacamole display)
+ * is resized.
+ *
+ * @event
+ * @param {Number} width The new width of the Guacamole display.
+ * @param {Number} height The new height of the Guacamole display.
+ */
+ this.onresize = null;
+
+ /**
+ * Fired when a blob is created. The blob provided to this event handler
+ * will contain its own event handlers for received data and the close
+ * event.
+ *
+ * @event
+ * @param {Guacamole.Blob} blob A container for blob data that will receive
+ * data from the server.
+ */
+ this.onblob = null;
+
+ // Layers
+ function getBufferLayer(index) {
+
+ index = -1 - index;
+ var buffer = buffers[index];
+
+ // Create buffer if necessary
+ if (buffer == null) {
+ buffer = new Guacamole.Layer(0, 0);
+ buffer.autoflush = 1;
+ buffer.autosize = 1;
+ buffers[index] = buffer;
+ }
+
+ return buffer;
+
+ }
+
+ function getLayerContainer(index) {
+
+ var layer = layers[index];
+ if (layer == null) {
+
+ // Add new layer
+ layer = new Guacamole.Client.LayerContainer(displayWidth, displayHeight);
+ layers[index] = layer;
+
+ // Get and position layer
+ var layer_element = layer.getElement();
+ layer_element.style.position = "absolute";
+ layer_element.style.left = "0px";
+ layer_element.style.top = "0px";
+ layer_element.style.overflow = "hidden";
+
+ // Add to default layer container
+ default_layer_container.getElement().appendChild(layer_element);
+
+ }
+
+ return layer;
+
+ }
+
+ function getLayer(index) {
+
+ // If buffer, just get layer
+ if (index < 0)
+ return getBufferLayer(index);
+
+ // Otherwise, retrieve layer from layer container
+ return getLayerContainer(index).getLayer();
+
+ }
+
+ function getParser(index) {
+
+ var parser = parsers[index];
+
+ // If parser not yet created, create it, and tie to the
+ // oninstruction handler of the tunnel.
+ if (parser == null) {
+ parser = parsers[index] = new Guacamole.Parser();
+ parser.oninstruction = tunnel.oninstruction;
+ }
+
+ return parser;
+
+ }
+
+ function getAudioChannel(index) {
+
+ var audio_channel = audio_channels[index];
+
+ // If audio channel not yet created, create it
+ if (audio_channel == null)
+ audio_channel = audio_channels[index] = new Guacamole.AudioChannel();
+
+ return audio_channel;
+
+ }
+
+ /**
+ * Handlers for all defined layer properties.
+ * @private
+ */
+ var layerPropertyHandlers = {
+
+ "miter-limit": function(layer, value) {
+ layer.setMiterLimit(parseFloat(value));
+ }
+
+ };
+
+ /**
+ * Handlers for all instruction opcodes receivable by a Guacamole protocol
+ * client.
+ * @private
+ */
+ var instructionHandlers = {
+
+ "arc": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var x = parseInt(parameters[1]);
+ var y = parseInt(parameters[2]);
+ var radius = parseInt(parameters[3]);
+ var startAngle = parseFloat(parameters[4]);
+ var endAngle = parseFloat(parameters[5]);
+ var negative = parseInt(parameters[6]);
+
+ layer.arc(x, y, radius, startAngle, endAngle, negative != 0);
+
+ },
+
+ "audio": function(parameters) {
+
+ var channel = getAudioChannel(parseInt(parameters[0]));
+ var mimetype = parameters[1];
+ var duration = parseFloat(parameters[2]);
+ var data = parameters[3];
+
+ channel.play(mimetype, duration, data);
+
+ },
+
+ "blob": function(parameters) {
+
+ // Get blob
+ var blob_index = parseInt(parameters[0]);
+ var data = parameters[1];
+ var blob = blobs[blob_index];
+
+ // Convert to ArrayBuffer
+ var binary = window.atob(data);
+ var arrayBuffer = new ArrayBuffer(binary.length);
+ var bufferView = new Uint8Array(arrayBuffer);
+
+ for (var i=0; i<binary.length; i++)
+ bufferView[i] = binary.charCodeAt(i);
+
+ // Write data
+ blob.append(arrayBuffer);
+
+ },
+
+ "cfill": function(parameters) {
+
+ var channelMask = parseInt(parameters[0]);
+ var layer = getLayer(parseInt(parameters[1]));
+ var r = parseInt(parameters[2]);
+ var g = parseInt(parameters[3]);
+ var b = parseInt(parameters[4]);
+ var a = parseInt(parameters[5]);
+
+ layer.setChannelMask(channelMask);
+
+ layer.fillColor(r, g, b, a);
+
+ },
+
+ "clip": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+
+ layer.clip();
+
+ },
+
+ "clipboard": function(parameters) {
+ if (guac_client.onclipboard) guac_client.onclipboard(parameters[0]);
+ },
+
+ "close": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+
+ layer.close();
+
+ },
+
+ "copy": function(parameters) {
+
+ var srcL = getLayer(parseInt(parameters[0]));
+ var srcX = parseInt(parameters[1]);
+ var srcY = parseInt(parameters[2]);
+ var srcWidth = parseInt(parameters[3]);
+ var srcHeight = parseInt(parameters[4]);
+ var channelMask = parseInt(parameters[5]);
+ var dstL = getLayer(parseInt(parameters[6]));
+ var dstX = parseInt(parameters[7]);
+ var dstY = parseInt(parameters[8]);
+
+ dstL.setChannelMask(channelMask);
+
+ dstL.copy(
+ srcL,
+ srcX,
+ srcY,
+ srcWidth,
+ srcHeight,
+ dstX,
+ dstY
+ );
+
+ },
+
+ "cstroke": function(parameters) {
+
+ var channelMask = parseInt(parameters[0]);
+ var layer = getLayer(parseInt(parameters[1]));
+ var cap = lineCap[parseInt(parameters[2])];
+ var join = lineJoin[parseInt(parameters[3])];
+ var thickness = parseInt(parameters[4]);
+ var r = parseInt(parameters[5]);
+ var g = parseInt(parameters[6]);
+ var b = parseInt(parameters[7]);
+ var a = parseInt(parameters[8]);
+
+ layer.setChannelMask(channelMask);
+
+ layer.strokeColor(cap, join, thickness, r, g, b, a);
+
+ },
+
+ "cursor": function(parameters) {
+
+ cursorHotspotX = parseInt(parameters[0]);
+ cursorHotspotY = parseInt(parameters[1]);
+ var srcL = getLayer(parseInt(parameters[2]));
+ var srcX = parseInt(parameters[3]);
+ var srcY = parseInt(parameters[4]);
+ var srcWidth = parseInt(parameters[5]);
+ var srcHeight = parseInt(parameters[6]);
+
+ // Reset cursor size
+ cursor.resize(srcWidth, srcHeight);
+
+ // Draw cursor to cursor layer
+ cursor.getLayer().copy(
+ srcL,
+ srcX,
+ srcY,
+ srcWidth,
+ srcHeight,
+ 0,
+ 0
+ );
+
+ // Update cursor position (hotspot may have changed)
+ moveCursor(cursorX, cursorY);
+
+ },
+
+ "curve": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var cp1x = parseInt(parameters[1]);
+ var cp1y = parseInt(parameters[2]);
+ var cp2x = parseInt(parameters[3]);
+ var cp2y = parseInt(parameters[4]);
+ var x = parseInt(parameters[5]);
+ var y = parseInt(parameters[6]);
+
+ layer.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
+
+ },
+
+ "dispose": function(parameters) {
+
+ var layer_index = parseInt(parameters[0]);
+
+ // If visible layer, remove from parent
+ if (layer_index > 0) {
+
+ // Get container element
+ var layer_container = getLayerContainer(layer_index).getElement();
+
+ // Remove from parent
+ layer_container.parentNode.removeChild(layer_container);
+
+ // Delete reference
+ delete layers[layer_index];
+
+ }
+
+ // If buffer, just delete reference
+ else if (layer_index < 0)
+ delete buffers[-1 - layer_index];
+
+ // Attempting to dispose the root layer currently has no effect.
+
+ },
+
+ "distort": function(parameters) {
+
+ var layer_index = parseInt(parameters[0]);
+ var a = parseFloat(parameters[1]);
+ var b = parseFloat(parameters[2]);
+ var c = parseFloat(parameters[3]);
+ var d = parseFloat(parameters[4]);
+ var e = parseFloat(parameters[5]);
+ var f = parseFloat(parameters[6]);
+
+ // Only valid for visible layers (not buffers)
+ if (layer_index >= 0) {
+
+ // Get container element
+ var layer_container = getLayerContainer(layer_index).getElement();
+
+ // Set layer transform
+ layer_container.transform(a, b, c, d, e, f);
+
+ }
+
+ },
+
+ "error": function(parameters) {
+ if (guac_client.onerror) guac_client.onerror(parameters[0]);
+ guac_client.disconnect();
+ },
+
+ "end": function(parameters) {
+
+ // Get blob
+ var blob_index = parseInt(parameters[0]);
+ var blob = blobs[blob_index];
+
+ // Close blob
+ blob.close();
+
+ },
+
+ "file": function(parameters) {
+
+ var blob_index = parseInt(parameters[0]);
+ var mimetype = parameters[1];
+ var filename = parameters[2];
+
+ // Create blob
+ var blob = blobs[blob_index] = new Guacamole.Blob(mimetype, filename);
+
+ // Call handler now that blob is created
+ if (guac_client.onblob)
+ guac_client.onblob(blob);
+
+ },
+
+ "identity": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+
+ layer.setTransform(1, 0, 0, 1, 0, 0);
+
+ },
+
+ "lfill": function(parameters) {
+
+ var channelMask = parseInt(parameters[0]);
+ var layer = getLayer(parseInt(parameters[1]));
+ var srcLayer = getLayer(parseInt(parameters[2]));
+
+ layer.setChannelMask(channelMask);
+
+ layer.fillLayer(srcLayer);
+
+ },
+
+ "line": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var x = parseInt(parameters[1]);
+ var y = parseInt(parameters[2]);
+
+ layer.lineTo(x, y);
+
+ },
+
+ "lstroke": function(parameters) {
+
+ var channelMask = parseInt(parameters[0]);
+ var layer = getLayer(parseInt(parameters[1]));
+ var srcLayer = getLayer(parseInt(parameters[2]));
+
+ layer.setChannelMask(channelMask);
+
+ layer.strokeLayer(srcLayer);
+
+ },
+
+ "move": function(parameters) {
+
+ var layer_index = parseInt(parameters[0]);
+ var parent_index = parseInt(parameters[1]);
+ var x = parseInt(parameters[2]);
+ var y = parseInt(parameters[3]);
+ var z = parseInt(parameters[4]);
+
+ // Only valid for non-default layers
+ if (layer_index > 0 && parent_index >= 0) {
+
+ // Get container element
+ var layer_container = getLayerContainer(layer_index);
+ var layer_container_element = layer_container.getElement();
+ var parent = getLayerContainer(parent_index).getElement();
+
+ // Set parent if necessary
+ if (!(layer_container_element.parentNode === parent))
+ parent.appendChild(layer_container_element);
+
+ // Move layer
+ layer_container.translate(x, y);
+ layer_container_element.style.zIndex = z;
+
+ }
+
+ },
+
+ "name": function(parameters) {
+ if (guac_client.onname) guac_client.onname(parameters[0]);
+ },
+
+ "nest": function(parameters) {
+ var parser = getParser(parseInt(parameters[0]));
+ parser.receive(parameters[1]);
+ },
+
+ "png": function(parameters) {
+
+ var channelMask = parseInt(parameters[0]);
+ var layer = getLayer(parseInt(parameters[1]));
+ var x = parseInt(parameters[2]);
+ var y = parseInt(parameters[3]);
+ var data = parameters[4];
+
+ layer.setChannelMask(channelMask);
+
+ layer.draw(
+ x,
+ y,
+ "data:image/png;base64," + data
+ );
+
+ },
+
+ "pop": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+
+ layer.pop();
+
+ },
+
+ "push": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+
+ layer.push();
+
+ },
+
+ "rect": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var x = parseInt(parameters[1]);
+ var y = parseInt(parameters[2]);
+ var w = parseInt(parameters[3]);
+ var h = parseInt(parameters[4]);
+
+ layer.rect(x, y, w, h);
+
+ },
+
+ "reset": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+
+ layer.reset();
+
+ },
+
+ "set": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var name = parameters[1];
+ var value = parameters[2];
+
+ // Call property handler if defined
+ var handler = layerPropertyHandlers[name];
+ if (handler)
+ handler(layer, value);
+
+ },
+
+ "shade": function(parameters) {
+
+ var layer_index = parseInt(parameters[0]);
+ var a = parseInt(parameters[1]);
+
+ // Only valid for visible layers (not buffers)
+ if (layer_index >= 0) {
+
+ // Get container element
+ var layer_container = getLayerContainer(layer_index).getElement();
+
+ // Set layer opacity
+ layer_container.style.opacity = a/255.0;
+
+ }
+
+ },
+
+ "size": function(parameters) {
+
+ var layer_index = parseInt(parameters[0]);
+ var width = parseInt(parameters[1]);
+ var height = parseInt(parameters[2]);
+
+ // If not buffer, resize layer and container
+ if (layer_index >= 0) {
+
+ // Resize layer
+ var layer_container = getLayerContainer(layer_index);
+ layer_container.resize(width, height);
+
+ // If layer is default, resize display
+ if (layer_index == 0) {
+
+ displayWidth = width;
+ displayHeight = height;
+
+ // Update (set) display size
+ display.style.width = displayWidth + "px";
+ display.style.height = displayHeight + "px";
+
+ // Update bounds size
+ bounds.style.width = (displayWidth*displayScale) + "px";
+ bounds.style.height = (displayHeight*displayScale) + "px";
+
+ // Call resize event handler if defined
+ if (guac_client.onresize)
+ guac_client.onresize(width, height);
+
+ }
+
+ }
+
+ // If buffer, resize layer only
+ else {
+ var layer = getBufferLayer(parseInt(parameters[0]));
+ layer.resize(width, height);
+ }
+
+ },
+
+ "start": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var x = parseInt(parameters[1]);
+ var y = parseInt(parameters[2]);
+
+ layer.moveTo(x, y);
+
+ },
+
+ "sync": function(parameters) {
+
+ var timestamp = parameters[0];
+
+ // When all layers have finished rendering all instructions
+ // UP TO THIS POINT IN TIME, send sync response.
+
+ var layersToSync = 0;
+ function syncLayer() {
+
+ layersToSync--;
+
+ // Send sync response when layers are finished
+ if (layersToSync == 0) {
+ if (timestamp != currentTimestamp) {
+ tunnel.sendMessage("sync", timestamp);
+ currentTimestamp = timestamp;
+ }
+ }
+
+ }
+
+ // Count active, not-ready layers and install sync tracking hooks
+ for (var i=0; i<layers.length; i++) {
+
+ var layer = layers[i].getLayer();
+ if (layer) {
+
+ // Flush layer
+ layer.flush();
+
+ // If still not ready, sync later
+ if (!layer.isReady()) {
+ layersToSync++;
+ layer.sync(syncLayer);
+ }
+
+ }
+
+ }
+
+ // If all layers are ready, then we didn't install any hooks.
+ // Send sync message now,
+ if (layersToSync == 0) {
+ if (timestamp != currentTimestamp) {
+ tunnel.sendMessage("sync", timestamp);
+ currentTimestamp = timestamp;
+ }
+ }
+
+ // If received first update, no longer waiting.
+ if (currentState == STATE_WAITING)
+ setState(STATE_CONNECTED);
+
+ },
+
+ "transfer": function(parameters) {
+
+ var srcL = getLayer(parseInt(parameters[0]));
+ var srcX = parseInt(parameters[1]);
+ var srcY = parseInt(parameters[2]);
+ var srcWidth = parseInt(parameters[3]);
+ var srcHeight = parseInt(parameters[4]);
+ var transferFunction = Guacamole.Client.DefaultTransferFunction[parameters[5]];
+ var dstL = getLayer(parseInt(parameters[6]));
+ var dstX = parseInt(parameters[7]);
+ var dstY = parseInt(parameters[8]);
+
+ dstL.transfer(
+ srcL,
+ srcX,
+ srcY,
+ srcWidth,
+ srcHeight,
+ dstX,
+ dstY,
+ transferFunction
+ );
+
+ },
+
+ "transform": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var a = parseFloat(parameters[1]);
+ var b = parseFloat(parameters[2]);
+ var c = parseFloat(parameters[3]);
+ var d = parseFloat(parameters[4]);
+ var e = parseFloat(parameters[5]);
+ var f = parseFloat(parameters[6]);
+
+ layer.transform(a, b, c, d, e, f);
+
+ },
+
+ "video": function(parameters) {
+
+ var layer = getLayer(parseInt(parameters[0]));
+ var mimetype = parameters[1];
+ var duration = parseFloat(parameters[2]);
+ var data = parameters[3];
+
+ layer.play(mimetype, duration, "data:" + mimetype + ";base64," + data);
+
+ }
+
+
+ };
+
+
+ tunnel.oninstruction = function(opcode, parameters) {
+
+ var handler = instructionHandlers[opcode];
+ if (handler)
+ handler(parameters);
+
+ };
+
+
+ /**
+ * Sends a disconnect instruction to the server and closes the tunnel.
+ */
+ this.disconnect = function() {
+
+ // Only attempt disconnection not disconnected.
+ if (currentState != STATE_DISCONNECTED
+ && currentState != STATE_DISCONNECTING) {
+
+ setState(STATE_DISCONNECTING);
+
+ // Stop ping
+ if (pingInterval)
+ window.clearInterval(pingInterval);
+
+ // Send disconnect message and disconnect
+ tunnel.sendMessage("disconnect");
+ tunnel.disconnect();
+ setState(STATE_DISCONNECTED);
+
+ }
+
+ };
+
+ /**
+ * Connects the underlying tunnel of this Guacamole.Client, passing the
+ * given arbitrary data to the tunnel during the connection process.
+ *
+ * @param data Arbitrary connection data to be sent to the underlying
+ * tunnel during the connection process.
+ */
+ this.connect = function(data) {
+
+ setState(STATE_CONNECTING);
+
+ try {
+ tunnel.connect(data);
+ }
+ catch (e) {
+ setState(STATE_IDLE);
+ throw e;
+ }
+
+ // Ping every 5 seconds (ensure connection alive)
+ pingInterval = window.setInterval(function() {
+ tunnel.sendMessage("sync", currentTimestamp);
+ }, 5000);
+
+ setState(STATE_WAITING);
+ };
+
+ /**
+ * Sets the scale of the client display element such that it renders at
+ * a relatively smaller or larger size, without affecting the true
+ * resolution of the display.
+ *
+ * @param {Number} scale The scale to resize to, where 1.0 is normal
+ * size (1:1 scale).
+ */
+ this.scale = function(scale) {
+
+ display.style.transform =
+ display.style.WebkitTransform =
+ display.style.MozTransform =
+ display.style.OTransform =
+ display.style.msTransform =
+
+ "scale(" + scale + "," + scale + ")";
+
+ displayScale = scale;
+
+ // Update bounds size
+ bounds.style.width = (displayWidth*displayScale) + "px";
+ bounds.style.height = (displayHeight*displayScale) + "px";
+
+ };
+
+ /**
+ * Returns the width of the display.
+ *
+ * @return {Number} The width of the display.
+ */
+ this.getWidth = function() {
+ return displayWidth;
+ };
+
+ /**
+ * Returns the height of the display.
+ *
+ * @return {Number} The height of the display.
+ */
+ this.getHeight = function() {
+ return displayHeight;
+ };
+
+ /**
+ * Returns the scale of the display.
+ *
+ * @return {Number} The scale of the display.
+ */
+ this.getScale = function() {
+ return displayScale;
+ };
+
+ /**
+ * Returns a canvas element containing the entire display, with all child
+ * layers composited within.
+ *
+ * @return {HTMLCanvasElement} A new canvas element containing a copy of
+ * the display.
+ */
+ this.flatten = function() {
+
+ // Get source and destination canvases
+ var source = getLayer(0).getCanvas();
+ var canvas = document.createElement("canvas");
+
+ // Set dimensions
+ canvas.width = source.width;
+ canvas.height = source.height;
+
+ // Copy image from source
+ var context = canvas.getContext("2d");
+ context.drawImage(source, 0, 0);
+
+ // Return new canvas copy
+ return canvas;
+
+ };
+
+};
+
+/**
+ * Simple container for Guacamole.Layer, allowing layers to be easily
+ * repositioned and nested. This allows certain operations to be accelerated
+ * through DOM manipulation, rather than raster operations.
+ *
+ * @constructor
+ *
+ * @param {Number} width The width of the Layer, in pixels. The canvas element
+ * backing this Layer will be given this width.
+ *
+ * @param {Number} height The height of the Layer, in pixels. The canvas element
+ * backing this Layer will be given this height.
+ */
+Guacamole.Client.LayerContainer = function(width, height) {
+
+ /**
+ * Reference to this LayerContainer.
+ * @private
+ */
+ var layer_container = this;
+
+ // Create layer with given size
+ var layer = new Guacamole.Layer(width, height);
+
+ // Set layer position
+ var canvas = layer.getCanvas();
+ canvas.style.position = "absolute";
+ canvas.style.left = "0px";
+ canvas.style.top = "0px";
+
+ // Create div with given size
+ var div = document.createElement("div");
+ div.appendChild(canvas);
+ div.style.width = width + "px";
+ div.style.height = height + "px";
+
+ /**
+ * Changes the size of this LayerContainer and the contained Layer to the
+ * given width and height.
+ *
+ * @param {Number} width The new width to assign to this Layer.
+ * @param {Number} height The new height to assign to this Layer.
+ */
+ this.resize = function(width, height) {
+
+ // Resize layer
+ layer.resize(width, height);
+
+ // Resize containing div
+ div.style.width = width + "px";
+ div.style.height = height + "px";
+
+ };
+
+ /**
+ * Returns the Layer contained within this LayerContainer.
+ * @returns {Guacamole.Layer} The Layer contained within this
+ * LayerContainer.
+ */
+ this.getLayer = function() {
+ return layer;
+ };
+
+ /**
+ * Returns the element containing the Layer within this LayerContainer.
+ * @returns {Element} The element containing the Layer within this
+ * LayerContainer.
+ */
+ this.getElement = function() {
+ return div;
+ };
+
+ /**
+ * The translation component of this LayerContainer's transform.
+ * @private
+ */
+ var translate = "translate(0px, 0px)"; // (0, 0)
+
+ /**
+ * The arbitrary matrix component of this LayerContainer's transform.
+ * @private
+ */
+ var matrix = "matrix(1, 0, 0, 1, 0, 0)"; // Identity
+
+ /**
+ * Moves the upper-left corner of this LayerContainer to the given X and Y
+ * coordinate.
+ *
+ * @param {Number} x The X coordinate to move to.
+ * @param {Number} y The Y coordinate to move to.
+ */
+ this.translate = function(x, y) {
+
+ // Generate translation
+ translate = "translate("
+ + x + "px,"
+ + y + "px)";
+
+ // Set layer transform
+ div.style.transform =
+ div.style.WebkitTransform =
+ div.style.MozTransform =
+ div.style.OTransform =
+ div.style.msTransform =
+
+ translate + " " + matrix;
+
+ };
+
+ /**
+ * Applies the given affine transform (defined with six values from the
+ * transform's matrix).
+ *
+ * @param {Number} a The first value in the affine transform's matrix.
+ * @param {Number} b The second value in the affine transform's matrix.
+ * @param {Number} c The third value in the affine transform's matrix.
+ * @param {Number} d The fourth value in the affine transform's matrix.
+ * @param {Number} e The fifth value in the affine transform's matrix.
+ * @param {Number} f The sixth value in the affine transform's matrix.
+ */
+ this.transform = function(a, b, c, d, e, f) {
+
+ // Generate matrix transformation
+ matrix =
+
+ /* a c e
+ * b d f
+ * 0 0 1
+ */
+
+ "matrix(" + a + "," + b + "," + c + "," + d + "," + e + "," + f + ")";
+
+ // Set layer transform
+ div.style.transform =
+ div.style.WebkitTransform =
+ div.style.MozTransform =
+ div.style.OTransform =
+ div.style.msTransform =
+
+ translate + " " + matrix;
+
+ };
+
+};
+
+/**
+ * Map of all Guacamole binary raster operations to transfer functions.
+ * @private
+ */
+Guacamole.Client.DefaultTransferFunction = {
+
+ /* BLACK */
+ 0x0: function (src, dst) {
+ dst.red = dst.green = dst.blue = 0x00;
+ },
+
+ /* WHITE */
+ 0xF: function (src, dst) {
+ dst.red = dst.green = dst.blue = 0xFF;
+ },
+
+ /* SRC */
+ 0x3: function (src, dst) {
+ dst.red = src.red;
+ dst.green = src.green;
+ dst.blue = src.blue;
+ dst.alpha = src.alpha;
+ },
+
+ /* DEST (no-op) */
+ 0x5: function (src, dst) {
+ // Do nothing
+ },
+
+ /* Invert SRC */
+ 0xC: function (src, dst) {
+ dst.red = 0xFF & ~src.red;
+ dst.green = 0xFF & ~src.green;
+ dst.blue = 0xFF & ~src.blue;
+ dst.alpha = src.alpha;
+ },
+
+ /* Invert DEST */
+ 0xA: function (src, dst) {
+ dst.red = 0xFF & ~dst.red;
+ dst.green = 0xFF & ~dst.green;
+ dst.blue = 0xFF & ~dst.blue;
+ },
+
+ /* AND */
+ 0x1: function (src, dst) {
+ dst.red = ( src.red & dst.red);
+ dst.green = ( src.green & dst.green);
+ dst.blue = ( src.blue & dst.blue);
+ },
+
+ /* NAND */
+ 0xE: function (src, dst) {
+ dst.red = 0xFF & ~( src.red & dst.red);
+ dst.green = 0xFF & ~( src.green & dst.green);
+ dst.blue = 0xFF & ~( src.blue & dst.blue);
+ },
+
+ /* OR */
+ 0x7: function (src, dst) {
+ dst.red = ( src.red | dst.red);
+ dst.green = ( src.green | dst.green);
+ dst.blue = ( src.blue | dst.blue);
+ },
+
+ /* NOR */
+ 0x8: function (src, dst) {
+ dst.red = 0xFF & ~( src.red | dst.red);
+ dst.green = 0xFF & ~( src.green | dst.green);
+ dst.blue = 0xFF & ~( src.blue | dst.blue);
+ },
+
+ /* XOR */
+ 0x6: function (src, dst) {
+ dst.red = ( src.red ^ dst.red);
+ dst.green = ( src.green ^ dst.green);
+ dst.blue = ( src.blue ^ dst.blue);
+ },
+
+ /* XNOR */
+ 0x9: function (src, dst) {
+ dst.red = 0xFF & ~( src.red ^ dst.red);
+ dst.green = 0xFF & ~( src.green ^ dst.green);
+ dst.blue = 0xFF & ~( src.blue ^ dst.blue);
+ },
+
+ /* AND inverted source */
+ 0x4: function (src, dst) {
+ dst.red = 0xFF & (~src.red & dst.red);
+ dst.green = 0xFF & (~src.green & dst.green);
+ dst.blue = 0xFF & (~src.blue & dst.blue);
+ },
+
+ /* OR inverted source */
+ 0xD: function (src, dst) {
+ dst.red = 0xFF & (~src.red | dst.red);
+ dst.green = 0xFF & (~src.green | dst.green);
+ dst.blue = 0xFF & (~src.blue | dst.blue);
+ },
+
+ /* AND inverted destination */
+ 0x2: function (src, dst) {
+ dst.red = 0xFF & ( src.red & ~dst.red);
+ dst.green = 0xFF & ( src.green & ~dst.green);
+ dst.blue = 0xFF & ( src.blue & ~dst.blue);
+ },
+
+ /* OR inverted destination */
+ 0xB: function (src, dst) {
+ dst.red = 0xFF & ( src.red | ~dst.red);
+ dst.green = 0xFF & ( src.green | ~dst.green);
+ dst.blue = 0xFF & ( src.blue | ~dst.blue);
+ }
+
+};
diff --git a/guacamole-common-js/src/main/resources/keyboard.js b/guacamole-common-js/src/main/resources/keyboard.js
new file mode 100644
index 0000000..46b2bfa
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/keyboard.js
@@ -0,0 +1,622 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Provides cross-browser and cross-keyboard keyboard for a specific element.
+ * Browser and keyboard layout variation is abstracted away, providing events
+ * which represent keys as their corresponding X11 keysym.
+ *
+ * @constructor
+ * @param {Element} element The Element to use to provide keyboard events.
+ */
+Guacamole.Keyboard = function(element) {
+
+ /**
+ * Reference to this Guacamole.Keyboard.
+ * @private
+ */
+ var guac_keyboard = this;
+
+ /**
+ * Fired whenever the user presses a key with the element associated
+ * with this Guacamole.Keyboard in focus.
+ *
+ * @event
+ * @param {Number} keysym The keysym of the key being pressed.
+ */
+ this.onkeydown = null;
+
+ /**
+ * Fired whenever the user releases a key with the element associated
+ * with this Guacamole.Keyboard in focus.
+ *
+ * @event
+ * @param {Number} keysym The keysym of the key being released.
+ */
+ this.onkeyup = null;
+
+ /**
+ * Map of known JavaScript keycodes which do not map to typable characters
+ * to their unshifted X11 keysym equivalents.
+ * @private
+ */
+ var unshiftedKeysym = {
+ 8: [0xFF08], // backspace
+ 9: [0xFF09], // tab
+ 13: [0xFF0D], // enter
+ 16: [0xFFE1, 0xFFE1, 0xFFE2], // shift
+ 17: [0xFFE3, 0xFFE3, 0xFFE4], // ctrl
+ 18: [0xFFE9, 0xFFE9, 0xFFEA], // alt
+ 19: [0xFF13], // pause/break
+ 20: [0xFFE5], // caps lock
+ 27: [0xFF1B], // escape
+ 32: [0x0020], // space
+ 33: [0xFF55], // page up
+ 34: [0xFF56], // page down
+ 35: [0xFF57], // end
+ 36: [0xFF50], // home
+ 37: [0xFF51], // left arrow
+ 38: [0xFF52], // up arrow
+ 39: [0xFF53], // right arrow
+ 40: [0xFF54], // down arrow
+ 45: [0xFF63], // insert
+ 46: [0xFFFF], // delete
+ 91: [0xFFEB], // left window key (super_l)
+ 92: [0xFF67], // right window key (menu key?)
+ 93: null, // select key
+ 112: [0xFFBE], // f1
+ 113: [0xFFBF], // f2
+ 114: [0xFFC0], // f3
+ 115: [0xFFC1], // f4
+ 116: [0xFFC2], // f5
+ 117: [0xFFC3], // f6
+ 118: [0xFFC4], // f7
+ 119: [0xFFC5], // f8
+ 120: [0xFFC6], // f9
+ 121: [0xFFC7], // f10
+ 122: [0xFFC8], // f11
+ 123: [0xFFC9], // f12
+ 144: [0xFF7F], // num lock
+ 145: [0xFF14] // scroll lock
+ };
+
+ /**
+ * Map of known JavaScript keyidentifiers which do not map to typable
+ * characters to their unshifted X11 keysym equivalents.
+ * @private
+ */
+ var keyidentifier_keysym = {
+ "AllCandidates": [0xFF3D],
+ "Alphanumeric": [0xFF30],
+ "Alt": [0xFFE9, 0xFFE9, 0xFFEA],
+ "Attn": [0xFD0E],
+ "AltGraph": [0xFFEA],
+ "CapsLock": [0xFFE5],
+ "Clear": [0xFF0B],
+ "Convert": [0xFF21],
+ "Copy": [0xFD15],
+ "Crsel": [0xFD1C],
+ "CodeInput": [0xFF37],
+ "Control": [0xFFE3, 0xFFE3, 0xFFE4],
+ "Down": [0xFF54],
+ "End": [0xFF57],
+ "Enter": [0xFF0D],
+ "EraseEof": [0xFD06],
+ "Execute": [0xFF62],
+ "Exsel": [0xFD1D],
+ "F1": [0xFFBE],
+ "F2": [0xFFBF],
+ "F3": [0xFFC0],
+ "F4": [0xFFC1],
+ "F5": [0xFFC2],
+ "F6": [0xFFC3],
+ "F7": [0xFFC4],
+ "F8": [0xFFC5],
+ "F9": [0xFFC6],
+ "F10": [0xFFC7],
+ "F11": [0xFFC8],
+ "F12": [0xFFC9],
+ "F13": [0xFFCA],
+ "F14": [0xFFCB],
+ "F15": [0xFFCC],
+ "F16": [0xFFCD],
+ "F17": [0xFFCE],
+ "F18": [0xFFCF],
+ "F19": [0xFFD0],
+ "F20": [0xFFD1],
+ "F21": [0xFFD2],
+ "F22": [0xFFD3],
+ "F23": [0xFFD4],
+ "F24": [0xFFD5],
+ "Find": [0xFF68],
+ "FullWidth": null,
+ "HalfWidth": null,
+ "HangulMode": [0xFF31],
+ "HanjaMode": [0xFF34],
+ "Help": [0xFF6A],
+ "Hiragana": [0xFF25],
+ "Home": [0xFF50],
+ "Insert": [0xFF63],
+ "JapaneseHiragana": [0xFF25],
+ "JapaneseKatakana": [0xFF26],
+ "JapaneseRomaji": [0xFF24],
+ "JunjaMode": [0xFF38],
+ "KanaMode": [0xFF2D],
+ "KanjiMode": [0xFF21],
+ "Katakana": [0xFF26],
+ "Left": [0xFF51],
+ "Meta": [0xFFE7],
+ "NumLock": [0xFF7F],
+ "PageDown": [0xFF55],
+ "PageUp": [0xFF56],
+ "Pause": [0xFF13],
+ "PreviousCandidate": [0xFF3E],
+ "PrintScreen": [0xFD1D],
+ "Right": [0xFF53],
+ "RomanCharacters": null,
+ "Scroll": [0xFF14],
+ "Select": [0xFF60],
+ "Shift": [0xFFE1, 0xFFE1, 0xFFE2],
+ "Up": [0xFF52],
+ "Undo": [0xFF65],
+ "Win": [0xFFEB]
+ };
+
+ /**
+ * Map of known JavaScript keycodes which do not map to typable characters
+ * to their shifted X11 keysym equivalents. Keycodes must only be listed
+ * here if their shifted X11 keysym equivalents differ from their unshifted
+ * equivalents.
+ * @private
+ */
+ var shiftedKeysym = {
+ 18: [0xFFE7, 0xFFE7, 0xFFEA] // alt
+ };
+
+ /**
+ * All keysyms which should not repeat when held down.
+ * @private
+ */
+ var no_repeat = {
+ 0xFFE1: true, // Left shift
+ 0xFFE2: true, // Right shift
+ 0xFFE3: true, // Left ctrl
+ 0xFFE4: true, // Right ctrl
+ 0xFFE9: true, // Left alt
+ 0xFFEA: true // Right alt (or AltGr)
+ };
+
+ /**
+ * All modifiers and their states.
+ */
+ this.modifiers = {
+
+ /**
+ * Whether shift is currently pressed.
+ */
+ "shift": false,
+
+ /**
+ * Whether ctrl is currently pressed.
+ */
+ "ctrl" : false,
+
+ /**
+ * Whether alt is currently pressed.
+ */
+ "alt" : false,
+
+ /**
+ * Whether meta (apple key) is currently pressed.
+ */
+ "meta" : false
+
+ };
+
+ /**
+ * The state of every key, indexed by keysym. If a particular key is
+ * pressed, the value of pressed for that keysym will be true. If a key
+ * is not currently pressed, it will not be defined.
+ */
+ this.pressed = {};
+
+ /**
+ * The keysym associated with a given keycode when keydown fired.
+ * @private
+ */
+ var keydownChar = [];
+
+ /**
+ * Timeout before key repeat starts.
+ * @private
+ */
+ var key_repeat_timeout = null;
+
+ /**
+ * Interval which presses and releases the last key pressed while that
+ * key is still being held down.
+ * @private
+ */
+ var key_repeat_interval = null;
+
+ /**
+ * Given an array of keysyms indexed by location, returns the keysym
+ * for the given location, or the keysym for the standard location if
+ * undefined.
+ *
+ * @param {Array} keysyms An array of keysyms, where the index of the
+ * keysym in the array is the location value.
+ * @param {Number} location The location on the keyboard corresponding to
+ * the key pressed, as defined at:
+ * http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent
+ */
+ function get_keysym(keysyms, location) {
+
+ if (!keysyms)
+ return null;
+
+ return keysyms[location] || keysyms[0];
+ }
+
+ function keysym_from_key_identifier(shifted, keyIdentifier, location) {
+
+ var unicodePrefixLocation = keyIdentifier.indexOf("U+");
+ if (unicodePrefixLocation >= 0) {
+
+ var hex = keyIdentifier.substring(unicodePrefixLocation+2);
+ var codepoint = parseInt(hex, 16);
+ var typedCharacter;
+
+ // Convert case if shifted
+ if (shifted == 0)
+ typedCharacter = String.fromCharCode(codepoint).toLowerCase();
+ else
+ typedCharacter = String.fromCharCode(codepoint).toUpperCase();
+
+ // Get codepoint
+ codepoint = typedCharacter.charCodeAt(0);
+
+ return keysym_from_charcode(codepoint);
+
+ }
+
+ return get_keysym(keyidentifier_keysym[keyIdentifier], location);
+
+ }
+
+ function isControlCharacter(codepoint) {
+ return codepoint <= 0x1F || (codepoint >= 0x7F && codepoint <= 0x9F);
+ }
+
+ function keysym_from_charcode(codepoint) {
+
+ // Keysyms for control characters
+ if (isControlCharacter(codepoint)) return 0xFF00 | codepoint;
+
+ // Keysyms for ASCII chars
+ if (codepoint >= 0x0000 && codepoint <= 0x00FF)
+ return codepoint;
+
+ // Keysyms for Unicode
+ if (codepoint >= 0x0100 && codepoint <= 0x10FFFF)
+ return 0x01000000 | codepoint;
+
+ return null;
+
+ }
+
+ function keysym_from_keycode(keyCode, location) {
+
+ var keysyms;
+
+ // If not shifted, just return unshifted keysym
+ if (!guac_keyboard.modifiers.shift)
+ keysyms = unshiftedKeysym[keyCode];
+
+ // Otherwise, return shifted keysym, if defined
+ else
+ keysyms = shiftedKeysym[keyCode] || unshiftedKeysym[keyCode];
+
+ return get_keysym(keysyms, location);
+
+ }
+
+
+ /**
+ * Marks a key as pressed, firing the keydown event if registered. Key
+ * repeat for the pressed key will start after a delay if that key is
+ * not a modifier.
+ * @private
+ */
+ function press_key(keysym) {
+
+ // Don't bother with pressing the key if the key is unknown
+ if (keysym == null) return;
+
+ // Only press if released
+ if (!guac_keyboard.pressed[keysym]) {
+
+ // Mark key as pressed
+ guac_keyboard.pressed[keysym] = true;
+
+ // Send key event
+ if (guac_keyboard.onkeydown) {
+ guac_keyboard.onkeydown(keysym);
+
+ // Stop any current repeat
+ window.clearTimeout(key_repeat_timeout);
+ window.clearInterval(key_repeat_interval);
+
+ // Repeat after a delay as long as pressed
+ if (!no_repeat[keysym])
+ key_repeat_timeout = window.setTimeout(function() {
+ key_repeat_interval = window.setInterval(function() {
+ guac_keyboard.onkeyup(keysym);
+ guac_keyboard.onkeydown(keysym);
+ }, 50);
+ }, 500);
+
+
+ }
+ }
+
+ }
+
+ /**
+ * Marks a key as released, firing the keyup event if registered.
+ * @private
+ */
+ function release_key(keysym) {
+
+ // Only release if pressed
+ if (guac_keyboard.pressed[keysym]) {
+
+ // Mark key as released
+ delete guac_keyboard.pressed[keysym];
+
+ // Stop repeat
+ window.clearTimeout(key_repeat_timeout);
+ window.clearInterval(key_repeat_interval);
+
+ // Send key event
+ if (keysym != null && guac_keyboard.onkeyup)
+ guac_keyboard.onkeyup(keysym);
+
+ }
+
+ }
+
+ function isTypable(keyIdentifier) {
+
+ // Find unicode prefix
+ var unicodePrefixLocation = keyIdentifier.indexOf("U+");
+ if (unicodePrefixLocation == -1)
+ return false;
+
+ // Parse codepoint value
+ var hex = keyIdentifier.substring(unicodePrefixLocation+2);
+ var codepoint = parseInt(hex, 16);
+
+ // If control character, not typable
+ if (isControlCharacter(codepoint)) return false;
+
+ // Otherwise, typable
+ return true;
+
+ }
+
+ /**
+ * Given a keyboard event, updates the local modifier state and remote
+ * key state based on the modifier flags within the event. This function
+ * pays no attention to keycodes.
+ *
+ * @param {KeyboardEvent} e The keyboard event containing the flags to update.
+ */
+ function update_modifier_state(e) {
+
+ // Release alt if implicitly released
+ if (guac_keyboard.modifiers.alt && e.altKey === false) {
+ release_key(0xFFE9); // Left alt
+ release_key(0xFFEA); // Right alt (or AltGr)
+ guac_keyboard.modifiers.alt = false;
+ }
+
+ // Release shift if implicitly released
+ if (guac_keyboard.modifiers.shift && e.shiftKey === false) {
+ release_key(0xFFE1); // Left shift
+ release_key(0xFFE2); // Right shift
+ guac_keyboard.modifiers.shift = false;
+ }
+
+ // Release ctrl if implicitly released
+ if (guac_keyboard.modifiers.ctrl && e.ctrlKey === false) {
+ release_key(0xFFE3); // Left ctrl
+ release_key(0xFFE4); // Right ctrl
+ guac_keyboard.modifiers.ctrl = false;
+ }
+
+ }
+
+ // When key pressed
+ element.addEventListener("keydown", function(e) {
+
+ // Only intercept if handler set
+ if (!guac_keyboard.onkeydown) return;
+
+ var keynum;
+ if (window.event) keynum = window.event.keyCode;
+ else if (e.which) keynum = e.which;
+
+ // Get key location
+ var location = e.location || e.keyLocation || 0;
+
+ // Ignore any unknown key events
+ if (keynum == 0 && !e.keyIdentifier) {
+ e.preventDefault();
+ return;
+ }
+
+ // Fix modifier states
+ update_modifier_state(e);
+
+ // Ctrl/Alt/Shift/Meta
+ if (keynum == 16) guac_keyboard.modifiers.shift = true;
+ else if (keynum == 17) guac_keyboard.modifiers.ctrl = true;
+ else if (keynum == 18) guac_keyboard.modifiers.alt = true;
+ else if (keynum == 91) guac_keyboard.modifiers.meta = true;
+
+ // Try to get keysym from keycode
+ var keysym = keysym_from_keycode(keynum, location);
+
+ // By default, we expect a corresponding keypress event
+ var expect_keypress = true;
+
+ // If key is known from keycode, prevent default
+ if (keysym)
+ expect_keypress = false;
+
+ // Also try to get get keysym from keyIdentifier
+ if (e.keyIdentifier) {
+
+ keysym = keysym ||
+ keysym_from_key_identifier(guac_keyboard.modifiers.shift,
+ e.keyIdentifier, location);
+
+ // Prevent default if non-typable character or if modifier combination
+ // likely to be eaten by browser otherwise (NOTE: We must not prevent
+ // default for Ctrl+Alt, as that combination is commonly used for
+ // AltGr. If we receive AltGr, we need to handle keypress, which
+ // means we cannot cancel keydown).
+ if (!isTypable(e.keyIdentifier)
+ || ( guac_keyboard.modifiers.ctrl && !guac_keyboard.modifiers.alt)
+ || (!guac_keyboard.modifiers.ctrl && guac_keyboard.modifiers.alt)
+ || (guac_keyboard.modifiers.meta))
+ expect_keypress = false;
+
+ }
+
+ // If we do not expect to handle via keypress, handle now
+ if (!expect_keypress) {
+ e.preventDefault();
+
+ // Press key if known
+ if (keysym != null) {
+ keydownChar[keynum] = keysym;
+ press_key(keysym);
+
+ // If a key is pressed while meta is held down, the keyup will never be sent in Chrome, so send it now. (bug #108404)
+ if(guac_keyboard.modifiers.meta) {
+ release_key(keysym);
+ }
+ }
+
+ }
+
+ }, true);
+
+ // When key pressed
+ element.addEventListener("keypress", function(e) {
+
+ // Only intercept if handler set
+ if (!guac_keyboard.onkeydown && !guac_keyboard.onkeyup) return;
+
+ e.preventDefault();
+
+ var keynum;
+ if (window.event) keynum = window.event.keyCode;
+ else if (e.which) keynum = e.which;
+
+ var keysym = keysym_from_charcode(keynum);
+
+ // Fix modifier states
+ update_modifier_state(e);
+
+ // If event identified as a typable character, and we're holding Ctrl+Alt,
+ // assume Ctrl+Alt is actually AltGr, and release both.
+ if (!isControlCharacter(keynum) && guac_keyboard.modifiers.ctrl && guac_keyboard.modifiers.alt) {
+ release_key(0xFFE3); // Left ctrl
+ release_key(0xFFE4); // Right ctrl
+ release_key(0xFFE9); // Left alt
+ release_key(0xFFEA); // Right alt
+ }
+
+ // Send press + release if keysym known
+ if (keysym != null) {
+ press_key(keysym);
+ release_key(keysym);
+ }
+
+ }, true);
+
+ // When key released
+ element.addEventListener("keyup", function(e) {
+
+ // Only intercept if handler set
+ if (!guac_keyboard.onkeyup) return;
+
+ e.preventDefault();
+
+ var keynum;
+ if (window.event) keynum = window.event.keyCode;
+ else if (e.which) keynum = e.which;
+
+ // Fix modifier states
+ update_modifier_state(e);
+
+ // Ctrl/Alt/Shift/Meta
+ if (keynum == 16) guac_keyboard.modifiers.shift = false;
+ else if (keynum == 17) guac_keyboard.modifiers.ctrl = false;
+ else if (keynum == 18) guac_keyboard.modifiers.alt = false;
+ else if (keynum == 91) guac_keyboard.modifiers.meta = false;
+
+ // Send release event if original key known
+ var keydown_keysym = keydownChar[keynum];
+ if (keydown_keysym != null)
+ release_key(keydown_keysym);
+
+ // Clear character record
+ keydownChar[keynum] = null;
+
+ }, true);
+
+};
diff --git a/guacamole-common-js/src/main/resources/layer.js b/guacamole-common-js/src/main/resources/layer.js
new file mode 100644
index 0000000..e3e8260
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/layer.js
@@ -0,0 +1,1210 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Abstract ordered drawing surface. Each Layer contains a canvas element and
+ * provides simple drawing instructions for drawing to that canvas element,
+ * however unlike the canvas element itself, drawing operations on a Layer are
+ * guaranteed to run in order, even if such an operation must wait for an image
+ * to load before completing.
+ *
+ * @constructor
+ *
+ * @param {Number} width The width of the Layer, in pixels. The canvas element
+ * backing this Layer will be given this width.
+ *
+ * @param {Number} height The height of the Layer, in pixels. The canvas element
+ * backing this Layer will be given this height.
+ */
+Guacamole.Layer = function(width, height) {
+
+ /**
+ * Reference to this Layer.
+ * @private
+ */
+ var layer = this;
+
+ /**
+ * The canvas element backing this Layer.
+ * @private
+ */
+ var display = document.createElement("canvas");
+
+ /**
+ * The 2D display context of the canvas element backing this Layer.
+ * @private
+ */
+ var displayContext = display.getContext("2d");
+ displayContext.save();
+
+ /**
+ * The queue of all pending Tasks. Tasks will be run in order, with new
+ * tasks added at the end of the queue and old tasks removed from the
+ * front of the queue (FIFO).
+ * @private
+ */
+ var tasks = new Array();
+
+ /**
+ * Whether a new path should be started with the next path drawing
+ * operations.
+ * @private
+ */
+ var pathClosed = true;
+
+ /**
+ * The number of states on the state stack.
+ *
+ * Note that there will ALWAYS be one element on the stack, but that
+ * element is not exposed. It is only used to reset the layer to its
+ * initial state.
+ *
+ * @private
+ */
+ var stackSize = 0;
+
+ /**
+ * Map of all Guacamole channel masks to HTML5 canvas composite operation
+ * names. Not all channel mask combinations are currently implemented.
+ * @private
+ */
+ var compositeOperation = {
+ /* 0x0 NOT IMPLEMENTED */
+ 0x1: "destination-in",
+ 0x2: "destination-out",
+ /* 0x3 NOT IMPLEMENTED */
+ 0x4: "source-in",
+ /* 0x5 NOT IMPLEMENTED */
+ 0x6: "source-atop",
+ /* 0x7 NOT IMPLEMENTED */
+ 0x8: "source-out",
+ 0x9: "destination-atop",
+ 0xA: "xor",
+ 0xB: "destination-over",
+ 0xC: "copy",
+ /* 0xD NOT IMPLEMENTED */
+ 0xE: "source-over",
+ 0xF: "lighter"
+ };
+
+ /**
+ * Resizes the canvas element backing this Layer without testing the
+ * new size. This function should only be used internally.
+ *
+ * @private
+ * @param {Number} newWidth The new width to assign to this Layer.
+ * @param {Number} newHeight The new height to assign to this Layer.
+ */
+ function resize(newWidth, newHeight) {
+
+ // Only preserve old data if width/height are both non-zero
+ var oldData = null;
+ if (width != 0 && height != 0) {
+
+ // Create canvas and context for holding old data
+ oldData = document.createElement("canvas");
+ oldData.width = width;
+ oldData.height = height;
+
+ var oldDataContext = oldData.getContext("2d");
+
+ // Copy image data from current
+ oldDataContext.drawImage(display,
+ 0, 0, width, height,
+ 0, 0, width, height);
+
+ }
+
+ // Preserve composite operation
+ var oldCompositeOperation = displayContext.globalCompositeOperation;
+
+ // Resize canvas
+ display.width = newWidth;
+ display.height = newHeight;
+
+ // Redraw old data, if any
+ if (oldData)
+ displayContext.drawImage(oldData,
+ 0, 0, width, height,
+ 0, 0, width, height);
+
+ // Restore composite operation
+ displayContext.globalCompositeOperation = oldCompositeOperation;
+
+ width = newWidth;
+ height = newHeight;
+
+ // Acknowledge reset of stack (happens on resize of canvas)
+ stackSize = 0;
+ displayContext.save();
+
+ }
+
+ /**
+ * Given the X and Y coordinates of the upper-left corner of a rectangle
+ * and the rectangle's width and height, resize the backing canvas element
+ * as necessary to ensure that the rectangle fits within the canvas
+ * element's coordinate space. This function will only make the canvas
+ * larger. If the rectangle already fits within the canvas element's
+ * coordinate space, the canvas is left unchanged.
+ *
+ * @private
+ * @param {Number} x The X coordinate of the upper-left corner of the
+ * rectangle to fit.
+ * @param {Number} y The Y coordinate of the upper-left corner of the
+ * rectangle to fit.
+ * @param {Number} w The width of the the rectangle to fit.
+ * @param {Number} h The height of the the rectangle to fit.
+ */
+ function fitRect(x, y, w, h) {
+
+ // Calculate bounds
+ var opBoundX = w + x;
+ var opBoundY = h + y;
+
+ // Determine max width
+ var resizeWidth;
+ if (opBoundX > width)
+ resizeWidth = opBoundX;
+ else
+ resizeWidth = width;
+
+ // Determine max height
+ var resizeHeight;
+ if (opBoundY > height)
+ resizeHeight = opBoundY;
+ else
+ resizeHeight = height;
+
+ // Resize if necessary
+ if (resizeWidth != width || resizeHeight != height)
+ resize(resizeWidth, resizeHeight);
+
+ }
+
+ /**
+ * A container for an task handler. Each operation which must be ordered
+ * is associated with a Task that goes into a task queue. Tasks in this
+ * queue are executed in order once their handlers are set, while Tasks
+ * without handlers block themselves and any following Tasks from running.
+ *
+ * @constructor
+ * @private
+ * @param {function} taskHandler The function to call when this task
+ * runs, if any.
+ * @param {boolean} blocked Whether this task should start blocked.
+ */
+ function Task(taskHandler, blocked) {
+
+ var task = this;
+
+ /**
+ * Whether this Task is blocked.
+ *
+ * @type boolean
+ */
+ this.blocked = blocked;
+
+ /**
+ * The handler this Task is associated with, if any.
+ *
+ * @type function
+ */
+ this.handler = taskHandler;
+
+ /**
+ * Unblocks this Task, allowing it to run.
+ */
+ this.unblock = function() {
+ if (task.blocked) {
+ task.blocked = false;
+
+ // Flush automatically if enabled
+ if (layer.autoflush || !flushComplete)
+ layer.flush();
+
+ }
+ }
+
+ }
+
+ /**
+ * If no tasks are pending or running, run the provided handler immediately,
+ * if any. Otherwise, schedule a task to run immediately after all currently
+ * running or pending tasks are complete.
+ *
+ * @private
+ * @param {function} handler The function to call when possible, if any.
+ * @param {boolean} blocked Whether the task should start blocked.
+ * @returns {Task} The Task created and added to the queue for future
+ * running, if any, or null if the handler was run
+ * immediately and no Task needed to be created.
+ */
+ function scheduleTask(handler, blocked) {
+
+ // If no pending tasks, just call (if available) and exit
+ if (layer.autoflush && layer.isReady() && !blocked) {
+ if (handler) handler();
+ return null;
+ }
+
+ // If tasks are pending/executing, schedule a pending task
+ // and return a reference to it.
+ var task = new Task(handler, blocked);
+ tasks.push(task);
+ return task;
+
+ }
+
+ /**
+ * Whether all previous calls to flush() have completed. If a task was
+ * waiting in the queue when flush() was called but still blocked, the
+ * queue will continue to flush outside the original flush() call until
+ * the queue is empty.
+ *
+ * @private
+ */
+ var flushComplete = true;
+
+ /**
+ * Whether tasks are currently being actively flushed. As flush() is not
+ * reentrant, this flag prevents calls of flush() from overlapping.
+ * @private
+ */
+ var tasksInProgress = false;
+
+ /**
+ * Run any Tasks which were pending but are now ready to run and are not
+ * blocked by other Tasks.
+ */
+ this.flush = function() {
+
+ if (tasksInProgress)
+ return;
+
+ tasksInProgress = true;
+ flushComplete = false;
+
+ // Draw all pending tasks.
+ var task;
+ while ((task = tasks[0]) != null && !task.blocked) {
+ tasks.shift();
+ if (task.handler) task.handler();
+ }
+
+ // If all pending draws have been flushed
+ if (layer.isReady())
+ flushComplete = true;
+
+ tasksInProgress = false;
+
+ };
+
+ /**
+ * Schedules a task within the current layer just as scheduleTast() does,
+ * except that another specified layer will be blocked until this task
+ * completes, and this task will not start until the other layer is
+ * ready.
+ *
+ * Essentially, a task is scheduled in both layers, and the specified task
+ * will only be performed once both layers are ready, and neither layer may
+ * proceed until this task completes.
+ *
+ * Note that there is no way to specify whether the task starts blocked,
+ * as whether the task is blocked depends completely on whether the
+ * other layer is currently ready.
+ *
+ * @private
+ * @param {Guacamole.Layer} otherLayer The other layer which must be blocked
+ * until this task completes.
+ * @param {function} handler The function to call when possible.
+ */
+ function scheduleTaskSynced(otherLayer, handler) {
+
+ // If we ARE the other layer, no need to sync.
+ // Syncing would result in deadlock.
+ if (layer === otherLayer)
+ scheduleTask(handler);
+
+ // Otherwise synchronize operation with other layer
+ else {
+
+ var drawComplete = false;
+ var layerLock = null;
+
+ function performTask() {
+
+ // Perform task
+ handler();
+
+ // Unblock the other layer now that draw is complete
+ if (layerLock != null)
+ layerLock.unblock();
+
+ // Flag operation as done
+ drawComplete = true;
+
+ }
+
+ // Currently blocked draw task
+ var task = scheduleTask(performTask, true);
+
+ // Unblock draw task once source layer is ready
+ otherLayer.sync(task.unblock);
+
+ // Block other layer until draw completes
+ // Note that the draw MAY have already been performed at this point,
+ // in which case creating a lock on the other layer will lead to
+ // deadlock (the draw task has already run and will thus never
+ // clear the lock)
+ if (!drawComplete)
+ layerLock = otherLayer.sync(null, true);
+
+ }
+ }
+
+ /**
+ * Set to true if this Layer should resize itself to accomodate the
+ * dimensions of any drawing operation, and false (the default) otherwise.
+ *
+ * Note that setting this property takes effect immediately, and thus may
+ * take effect on operations that were started in the past but have not
+ * yet completed. If you wish the setting of this flag to only modify
+ * future operations, you will need to make the setting of this flag an
+ * operation with sync().
+ *
+ * @example
+ * // Set autosize to true for all future operations
+ * layer.sync(function() {
+ * layer.autosize = true;
+ * });
+ *
+ * @type Boolean
+ * @default false
+ */
+ this.autosize = false;
+
+ /**
+ * Set to true to allow operations to flush automatically, instantly
+ * affecting the layer. By default, operations are buffered and only
+ * drawn when flush() is called.
+ *
+ * @type Boolean
+ * @default false
+ */
+ this.autoflush = false;
+
+ /**
+ * Returns the canvas element backing this Layer.
+ * @returns {Element} The canvas element backing this Layer.
+ */
+ this.getCanvas = function() {
+ return display;
+ };
+
+ /**
+ * Returns whether this Layer is ready. A Layer is ready if it has no
+ * pending operations and no operations in-progress.
+ *
+ * @returns {Boolean} true if this Layer is ready, false otherwise.
+ */
+ this.isReady = function() {
+ return tasks.length == 0;
+ };
+
+ /**
+ * Changes the size of this Layer to the given width and height. Resizing
+ * is only attempted if the new size provided is actually different from
+ * the current size.
+ *
+ * @param {Number} newWidth The new width to assign to this Layer.
+ * @param {Number} newHeight The new height to assign to this Layer.
+ */
+ this.resize = function(newWidth, newHeight) {
+ scheduleTask(function() {
+ if (newWidth != width || newHeight != height)
+ resize(newWidth, newHeight);
+ });
+ };
+
+ /**
+ * Draws the specified image at the given coordinates. The image specified
+ * must already be loaded.
+ *
+ * @param {Number} x The destination X coordinate.
+ * @param {Number} y The destination Y coordinate.
+ * @param {Image} image The image to draw. Note that this is an Image
+ * object - not a URL.
+ */
+ this.drawImage = function(x, y, image) {
+ scheduleTask(function() {
+ if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
+ displayContext.drawImage(image, x, y);
+ });
+ };
+
+ /**
+ * Draws the image at the specified URL at the given coordinates. The image
+ * will be loaded automatically, and this and any future operations will
+ * wait for the image to finish loading.
+ *
+ * @param {Number} x The destination X coordinate.
+ * @param {Number} y The destination Y coordinate.
+ * @param {String} url The URL of the image to draw.
+ */
+ this.draw = function(x, y, url) {
+
+ var task = scheduleTask(function() {
+ if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
+ displayContext.drawImage(image, x, y);
+ }, true);
+
+ var image = new Image();
+ image.onload = task.unblock;
+ image.src = url;
+
+ };
+
+ /**
+ * Plays the video at the specified URL within this layer. The video
+ * will be loaded automatically, and this and any future operations will
+ * wait for the video to finish loading. Future operations will not be
+ * executed until the video finishes playing.
+ *
+ * @param {String} mimetype The mimetype of the video to play.
+ * @param {Number} duration The duration of the video in milliseconds.
+ * @param {String} url The URL of the video to play.
+ */
+ this.play = function(mimetype, duration, url) {
+
+ // Start loading the video
+ var video = document.createElement("video");
+ video.type = mimetype;
+ video.src = url;
+
+ // Main task - playing the video
+ var task = scheduleTask(function() {
+ video.play();
+ }, true);
+
+ // Lock which will be cleared after video ends
+ var lock = scheduleTask(null, true);
+
+ // Start copying frames when playing
+ video.addEventListener("play", function() {
+
+ function render_callback() {
+ displayContext.drawImage(video, 0, 0, width, height);
+ if (!video.ended)
+ window.setTimeout(render_callback, 20);
+ else
+ lock.unblock();
+ }
+
+ render_callback();
+
+ }, false);
+
+ // Unblock future operations after an error
+ video.addEventListener("error", lock.unblock, false);
+
+ // Play video as soon as current tasks are complete, now that the
+ // lock has been set up.
+ task.unblock();
+
+ };
+
+ /**
+ * Run an arbitrary function as soon as currently pending operations
+ * are complete.
+ *
+ * @param {function} handler The function to call once all currently
+ * pending operations are complete.
+ * @param {boolean} blocked Whether the task should start blocked.
+ */
+ this.sync = scheduleTask;
+
+ /**
+ * Transfer a rectangle of image data from one Layer to this Layer using the
+ * specified transfer function.
+ *
+ * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
+ * @param {Number} srcx The X coordinate of the upper-left corner of the
+ * rectangle within the source Layer's coordinate
+ * space to copy data from.
+ * @param {Number} srcy The Y coordinate of the upper-left corner of the
+ * rectangle within the source Layer's coordinate
+ * space to copy data from.
+ * @param {Number} srcw The width of the rectangle within the source Layer's
+ * coordinate space to copy data from.
+ * @param {Number} srch The height of the rectangle within the source
+ * Layer's coordinate space to copy data from.
+ * @param {Number} x The destination X coordinate.
+ * @param {Number} y The destination Y coordinate.
+ * @param {Function} transferFunction The transfer function to use to
+ * transfer data from source to
+ * destination.
+ */
+ this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
+ scheduleTaskSynced(srcLayer, function() {
+
+ var srcCanvas = srcLayer.getCanvas();
+
+ // If entire rectangle outside source canvas, stop
+ if (srcx >= srcCanvas.width || srcy >= srcCanvas.height) return;
+
+ // Otherwise, clip rectangle to area
+ if (srcx + srcw > srcCanvas.width)
+ srcw = srcCanvas.width - srcx;
+
+ if (srcy + srch > srcCanvas.height)
+ srch = srcCanvas.height - srcy;
+
+ // Stop if nothing to draw.
+ if (srcw == 0 || srch == 0) return;
+
+ if (layer.autosize != 0) fitRect(x, y, srcw, srch);
+
+ // Get image data from src and dst
+ var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
+ var dst = displayContext.getImageData(x , y, srcw, srch);
+
+ // Apply transfer for each pixel
+ for (var i=0; i<srcw*srch*4; i+=4) {
+
+ // Get source pixel environment
+ var src_pixel = new Guacamole.Layer.Pixel(
+ src.data[i],
+ src.data[i+1],
+ src.data[i+2],
+ src.data[i+3]
+ );
+
+ // Get destination pixel environment
+ var dst_pixel = new Guacamole.Layer.Pixel(
+ dst.data[i],
+ dst.data[i+1],
+ dst.data[i+2],
+ dst.data[i+3]
+ );
+
+ // Apply transfer function
+ transferFunction(src_pixel, dst_pixel);
+
+ // Save pixel data
+ dst.data[i ] = dst_pixel.red;
+ dst.data[i+1] = dst_pixel.green;
+ dst.data[i+2] = dst_pixel.blue;
+ dst.data[i+3] = dst_pixel.alpha;
+
+ }
+
+ // Draw image data
+ displayContext.putImageData(dst, x, y);
+
+ });
+ };
+
+ /**
+ * Copy a rectangle of image data from one Layer to this Layer. This
+ * operation will copy exactly the image data that will be drawn once all
+ * operations of the source Layer that were pending at the time this
+ * function was called are complete. This operation will not alter the
+ * size of the source Layer even if its autosize property is set to true.
+ *
+ * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
+ * @param {Number} srcx The X coordinate of the upper-left corner of the
+ * rectangle within the source Layer's coordinate
+ * space to copy data from.
+ * @param {Number} srcy The Y coordinate of the upper-left corner of the
+ * rectangle within the source Layer's coordinate
+ * space to copy data from.
+ * @param {Number} srcw The width of the rectangle within the source Layer's
+ * coordinate space to copy data from.
+ * @param {Number} srch The height of the rectangle within the source
+ * Layer's coordinate space to copy data from.
+ * @param {Number} x The destination X coordinate.
+ * @param {Number} y The destination Y coordinate.
+ */
+ this.copy = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
+ scheduleTaskSynced(srcLayer, function() {
+
+ var srcCanvas = srcLayer.getCanvas();
+
+ // If entire rectangle outside source canvas, stop
+ if (srcx >= srcCanvas.width || srcy >= srcCanvas.height) return;
+
+ // Otherwise, clip rectangle to area
+ if (srcx + srcw > srcCanvas.width)
+ srcw = srcCanvas.width - srcx;
+
+ if (srcy + srch > srcCanvas.height)
+ srch = srcCanvas.height - srcy;
+
+ // Stop if nothing to draw.
+ if (srcw == 0 || srch == 0) return;
+
+ if (layer.autosize != 0) fitRect(x, y, srcw, srch);
+ displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
+
+ });
+ };
+
+ /**
+ * Starts a new path at the specified point.
+ *
+ * @param {Number} x The X coordinate of the point to draw.
+ * @param {Number} y The Y coordinate of the point to draw.
+ */
+ this.moveTo = function(x, y) {
+ scheduleTask(function() {
+
+ // Start a new path if current path is closed
+ if (pathClosed) {
+ displayContext.beginPath();
+ pathClosed = false;
+ }
+
+ if (layer.autosize != 0) fitRect(x, y, 0, 0);
+ displayContext.moveTo(x, y);
+
+ });
+ };
+
+ /**
+ * Add the specified line to the current path.
+ *
+ * @param {Number} x The X coordinate of the endpoint of the line to draw.
+ * @param {Number} y The Y coordinate of the endpoint of the line to draw.
+ */
+ this.lineTo = function(x, y) {
+ scheduleTask(function() {
+
+ // Start a new path if current path is closed
+ if (pathClosed) {
+ displayContext.beginPath();
+ pathClosed = false;
+ }
+
+ if (layer.autosize != 0) fitRect(x, y, 0, 0);
+ displayContext.lineTo(x, y);
+
+ });
+ };
+
+ /**
+ * Add the specified arc to the current path.
+ *
+ * @param {Number} x The X coordinate of the center of the circle which
+ * will contain the arc.
+ * @param {Number} y The Y coordinate of the center of the circle which
+ * will contain the arc.
+ * @param {Number} radius The radius of the circle.
+ * @param {Number} startAngle The starting angle of the arc, in radians.
+ * @param {Number} endAngle The ending angle of the arc, in radians.
+ * @param {Boolean} negative Whether the arc should be drawn in order of
+ * decreasing angle.
+ */
+ this.arc = function(x, y, radius, startAngle, endAngle, negative) {
+ scheduleTask(function() {
+
+ // Start a new path if current path is closed
+ if (pathClosed) {
+ displayContext.beginPath();
+ pathClosed = false;
+ }
+
+ if (layer.autosize != 0) fitRect(x, y, 0, 0);
+ displayContext.arc(x, y, radius, startAngle, endAngle, negative);
+
+ });
+ };
+
+ /**
+ * Starts a new path at the specified point.
+ *
+ * @param {Number} cp1x The X coordinate of the first control point.
+ * @param {Number} cp1y The Y coordinate of the first control point.
+ * @param {Number} cp2x The X coordinate of the second control point.
+ * @param {Number} cp2y The Y coordinate of the second control point.
+ * @param {Number} x The X coordinate of the endpoint of the curve.
+ * @param {Number} y The Y coordinate of the endpoint of the curve.
+ */
+ this.curveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
+ scheduleTask(function() {
+
+ // Start a new path if current path is closed
+ if (pathClosed) {
+ displayContext.beginPath();
+ pathClosed = false;
+ }
+
+ if (layer.autosize != 0) fitRect(x, y, 0, 0);
+ displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
+
+ });
+ };
+
+ /**
+ * Closes the current path by connecting the end point with the start
+ * point (if any) with a straight line.
+ */
+ this.close = function() {
+ scheduleTask(function() {
+
+ // Close path
+ displayContext.closePath();
+ pathClosed = true;
+
+ });
+ };
+
+ /**
+ * Add the specified rectangle to the current path.
+ *
+ * @param {Number} x The X coordinate of the upper-left corner of the
+ * rectangle to draw.
+ * @param {Number} y The Y coordinate of the upper-left corner of the
+ * rectangle to draw.
+ * @param {Number} w The width of the rectangle to draw.
+ * @param {Number} h The height of the rectangle to draw.
+ */
+ this.rect = function(x, y, w, h) {
+ scheduleTask(function() {
+
+ // Start a new path if current path is closed
+ if (pathClosed) {
+ displayContext.beginPath();
+ pathClosed = false;
+ }
+
+ if (layer.autosize != 0) fitRect(x, y, w, h);
+ displayContext.rect(x, y, w, h);
+
+ });
+ };
+
+ /**
+ * Clip all future drawing operations by the current path. The current path
+ * is implicitly closed. The current path can continue to be reused
+ * for other operations (such as fillColor()) but a new path will be started
+ * once a path drawing operation (path() or rect()) is used.
+ */
+ this.clip = function() {
+ scheduleTask(function() {
+
+ // Set new clipping region
+ displayContext.clip();
+
+ // Path now implicitly closed
+ pathClosed = true;
+
+ });
+ };
+
+ /**
+ * Stroke the current path with the specified color. The current path
+ * is implicitly closed. The current path can continue to be reused
+ * for other operations (such as clip()) but a new path will be started
+ * once a path drawing operation (path() or rect()) is used.
+ *
+ * @param {String} cap The line cap style. Can be "round", "square",
+ * or "butt".
+ * @param {String} join The line join style. Can be "round", "bevel",
+ * or "miter".
+ * @param {Number} thickness The line thickness in pixels.
+ * @param {Number} r The red component of the color to fill.
+ * @param {Number} g The green component of the color to fill.
+ * @param {Number} b The blue component of the color to fill.
+ * @param {Number} a The alpha component of the color to fill.
+ */
+ this.strokeColor = function(cap, join, thickness, r, g, b, a) {
+ scheduleTask(function() {
+
+ // Stroke with color
+ displayContext.lineCap = cap;
+ displayContext.lineJoin = join;
+ displayContext.lineWidth = thickness;
+ displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
+ displayContext.stroke();
+
+ // Path now implicitly closed
+ pathClosed = true;
+
+ });
+ };
+
+ /**
+ * Fills the current path with the specified color. The current path
+ * is implicitly closed. The current path can continue to be reused
+ * for other operations (such as clip()) but a new path will be started
+ * once a path drawing operation (path() or rect()) is used.
+ *
+ * @param {Number} r The red component of the color to fill.
+ * @param {Number} g The green component of the color to fill.
+ * @param {Number} b The blue component of the color to fill.
+ * @param {Number} a The alpha component of the color to fill.
+ */
+ this.fillColor = function(r, g, b, a) {
+ scheduleTask(function() {
+
+ // Fill with color
+ displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
+ displayContext.fill();
+
+ // Path now implicitly closed
+ pathClosed = true;
+
+ });
+ };
+
+ /**
+ * Stroke the current path with the image within the specified layer. The
+ * image data will be tiled infinitely within the stroke. The current path
+ * is implicitly closed. The current path can continue to be reused
+ * for other operations (such as clip()) but a new path will be started
+ * once a path drawing operation (path() or rect()) is used.
+ *
+ * @param {String} cap The line cap style. Can be "round", "square",
+ * or "butt".
+ * @param {String} join The line join style. Can be "round", "bevel",
+ * or "miter".
+ * @param {Number} thickness The line thickness in pixels.
+ * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
+ * within the stroke.
+ */
+ this.strokeLayer = function(cap, join, thickness, srcLayer) {
+ scheduleTaskSynced(srcLayer, function() {
+
+ // Stroke with image data
+ displayContext.lineCap = cap;
+ displayContext.lineJoin = join;
+ displayContext.lineWidth = thickness;
+ displayContext.strokeStyle = displayContext.createPattern(
+ srcLayer.getCanvas(),
+ "repeat"
+ );
+ displayContext.stroke();
+
+ // Path now implicitly closed
+ pathClosed = true;
+
+ });
+ };
+
+ /**
+ * Fills the current path with the image within the specified layer. The
+ * image data will be tiled infinitely within the stroke. The current path
+ * is implicitly closed. The current path can continue to be reused
+ * for other operations (such as clip()) but a new path will be started
+ * once a path drawing operation (path() or rect()) is used.
+ *
+ * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
+ * within the fill.
+ */
+ this.fillLayer = function(srcLayer) {
+ scheduleTask(function() {
+
+ // Fill with image data
+ displayContext.fillStyle = displayContext.createPattern(
+ srcLayer.getCanvas(),
+ "repeat"
+ );
+ displayContext.fill();
+
+ // Path now implicitly closed
+ pathClosed = true;
+
+ });
+ };
+
+ /**
+ * Push current layer state onto stack.
+ */
+ this.push = function() {
+ scheduleTask(function() {
+
+ // Save current state onto stack
+ displayContext.save();
+ stackSize++;
+
+ });
+ };
+
+ /**
+ * Pop layer state off stack.
+ */
+ this.pop = function() {
+ scheduleTask(function() {
+
+ // Restore current state from stack
+ if (stackSize > 0) {
+ displayContext.restore();
+ stackSize--;
+ }
+
+ });
+ };
+
+ /**
+ * Reset the layer, clearing the stack, the current path, and any transform
+ * matrix.
+ */
+ this.reset = function() {
+ scheduleTask(function() {
+
+ // Clear stack
+ while (stackSize > 0) {
+ displayContext.restore();
+ stackSize--;
+ }
+
+ // Restore to initial state
+ displayContext.restore();
+ displayContext.save();
+
+ // Clear path
+ displayContext.beginPath();
+ pathClosed = false;
+
+ });
+ };
+
+ /**
+ * Sets the given affine transform (defined with six values from the
+ * transform's matrix).
+ *
+ * @param {Number} a The first value in the affine transform's matrix.
+ * @param {Number} b The second value in the affine transform's matrix.
+ * @param {Number} c The third value in the affine transform's matrix.
+ * @param {Number} d The fourth value in the affine transform's matrix.
+ * @param {Number} e The fifth value in the affine transform's matrix.
+ * @param {Number} f The sixth value in the affine transform's matrix.
+ */
+ this.setTransform = function(a, b, c, d, e, f) {
+ scheduleTask(function() {
+
+ // Set transform
+ displayContext.setTransform(
+ a, b, c,
+ d, e, f
+ /*0, 0, 1*/
+ );
+
+ });
+ };
+
+
+ /**
+ * Applies the given affine transform (defined with six values from the
+ * transform's matrix).
+ *
+ * @param {Number} a The first value in the affine transform's matrix.
+ * @param {Number} b The second value in the affine transform's matrix.
+ * @param {Number} c The third value in the affine transform's matrix.
+ * @param {Number} d The fourth value in the affine transform's matrix.
+ * @param {Number} e The fifth value in the affine transform's matrix.
+ * @param {Number} f The sixth value in the affine transform's matrix.
+ */
+ this.transform = function(a, b, c, d, e, f) {
+ scheduleTask(function() {
+
+ // Apply transform
+ displayContext.transform(
+ a, b, c,
+ d, e, f
+ /*0, 0, 1*/
+ );
+
+ });
+ };
+
+
+ /**
+ * Sets the channel mask for future operations on this Layer.
+ *
+ * The channel mask is a Guacamole-specific compositing operation identifier
+ * with a single bit representing each of four channels (in order): source
+ * image where destination transparent, source where destination opaque,
+ * destination where source transparent, and destination where source
+ * opaque.
+ *
+ * @param {Number} mask The channel mask for future operations on this
+ * Layer.
+ */
+ this.setChannelMask = function(mask) {
+ scheduleTask(function() {
+ displayContext.globalCompositeOperation = compositeOperation[mask];
+ });
+ };
+
+ /**
+ * Sets the miter limit for stroke operations using the miter join. This
+ * limit is the maximum ratio of the size of the miter join to the stroke
+ * width. If this ratio is exceeded, the miter will not be drawn for that
+ * joint of the path.
+ *
+ * @param {Number} limit The miter limit for stroke operations using the
+ * miter join.
+ */
+ this.setMiterLimit = function(limit) {
+ scheduleTask(function() {
+ displayContext.miterLimit = limit;
+ });
+ };
+
+ // Initialize canvas dimensions
+ display.width = width;
+ display.height = height;
+
+};
+
+/**
+ * Channel mask for the composite operation "rout".
+ */
+Guacamole.Layer.ROUT = 0x2;
+
+/**
+ * Channel mask for the composite operation "atop".
+ */
+Guacamole.Layer.ATOP = 0x6;
+
+/**
+ * Channel mask for the composite operation "xor".
+ */
+Guacamole.Layer.XOR = 0xA;
+
+/**
+ * Channel mask for the composite operation "rover".
+ */
+Guacamole.Layer.ROVER = 0xB;
+
+/**
+ * Channel mask for the composite operation "over".
+ */
+Guacamole.Layer.OVER = 0xE;
+
+/**
+ * Channel mask for the composite operation "plus".
+ */
+Guacamole.Layer.PLUS = 0xF;
+
+/**
+ * Channel mask for the composite operation "rin".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.RIN = 0x1;
+
+/**
+ * Channel mask for the composite operation "in".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.IN = 0x4;
+
+/**
+ * Channel mask for the composite operation "out".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.OUT = 0x8;
+
+/**
+ * Channel mask for the composite operation "ratop".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.RATOP = 0x9;
+
+/**
+ * Channel mask for the composite operation "src".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.SRC = 0xC;
+
+
+/**
+ * Represents a single pixel of image data. All components have a minimum value
+ * of 0 and a maximum value of 255.
+ *
+ * @constructor
+ *
+ * @param {Number} r The red component of this pixel.
+ * @param {Number} g The green component of this pixel.
+ * @param {Number} b The blue component of this pixel.
+ * @param {Number} a The alpha component of this pixel.
+ */
+Guacamole.Layer.Pixel = function(r, g, b, a) {
+
+ /**
+ * The red component of this pixel, where 0 is the minimum value,
+ * and 255 is the maximum.
+ */
+ this.red = r;
+
+ /**
+ * The green component of this pixel, where 0 is the minimum value,
+ * and 255 is the maximum.
+ */
+ this.green = g;
+
+ /**
+ * The blue component of this pixel, where 0 is the minimum value,
+ * and 255 is the maximum.
+ */
+ this.blue = b;
+
+ /**
+ * The alpha component of this pixel, where 0 is the minimum value,
+ * and 255 is the maximum.
+ */
+ this.alpha = a;
+
+};
diff --git a/guacamole-common-js/src/main/resources/mouse.js b/guacamole-common-js/src/main/resources/mouse.js
new file mode 100644
index 0000000..33637ff
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/mouse.js
@@ -0,0 +1,836 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Provides cross-browser mouse events for a given element. The events of
+ * the given element are automatically populated with handlers that translate
+ * mouse events into a non-browser-specific event provided by the
+ * Guacamole.Mouse instance.
+ *
+ * @constructor
+ * @param {Element} element The Element to use to provide mouse events.
+ */
+Guacamole.Mouse = function(element) {
+
+ /**
+ * Reference to this Guacamole.Mouse.
+ * @private
+ */
+ var guac_mouse = this;
+
+ /**
+ * The number of mousemove events to require before re-enabling mouse
+ * event handling after receiving a touch event.
+ */
+ this.touchMouseThreshold = 3;
+
+ /**
+ * The minimum amount of pixels scrolled required for a single scroll button
+ * click.
+ */
+ this.scrollThreshold = 120;
+
+ /**
+ * The number of pixels to scroll per line.
+ */
+ this.PIXELS_PER_LINE = 40;
+
+ /**
+ * The number of pixels to scroll per page.
+ */
+ this.PIXELS_PER_PAGE = 640;
+
+ /**
+ * The current mouse state. The properties of this state are updated when
+ * mouse events fire. This state object is also passed in as a parameter to
+ * the handler of any mouse events.
+ *
+ * @type Guacamole.Mouse.State
+ */
+ this.currentState = new Guacamole.Mouse.State(
+ 0, 0,
+ false, false, false, false, false
+ );
+
+ /**
+ * Fired whenever the user presses a mouse button down over the element
+ * associated with this Guacamole.Mouse.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmousedown = null;
+
+ /**
+ * Fired whenever the user releases a mouse button down over the element
+ * associated with this Guacamole.Mouse.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmouseup = null;
+
+ /**
+ * Fired whenever the user moves the mouse over the element associated with
+ * this Guacamole.Mouse.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmousemove = null;
+
+ /**
+ * Counter of mouse events to ignore. This decremented by mousemove, and
+ * while non-zero, mouse events will have no effect.
+ * @private
+ */
+ var ignore_mouse = 0;
+
+ /**
+ * Cumulative scroll delta amount. This value is accumulated through scroll
+ * events and results in scroll button clicks if it exceeds a certain
+ * threshold.
+ */
+ var scroll_delta = 0;
+
+ function cancelEvent(e) {
+ e.stopPropagation();
+ if (e.preventDefault) e.preventDefault();
+ e.returnValue = false;
+ }
+
+ // Block context menu so right-click gets sent properly
+ element.addEventListener("contextmenu", function(e) {
+ cancelEvent(e);
+ }, false);
+
+ element.addEventListener("mousemove", function(e) {
+
+ cancelEvent(e);
+
+ // If ignoring events, decrement counter
+ if (ignore_mouse) {
+ ignore_mouse--;
+ return;
+ }
+
+ guac_mouse.currentState.fromClientPosition(element, e.clientX, e.clientY);
+
+ if (guac_mouse.onmousemove)
+ guac_mouse.onmousemove(guac_mouse.currentState);
+
+ }, false);
+
+ element.addEventListener("mousedown", function(e) {
+
+ cancelEvent(e);
+
+ // Do not handle if ignoring events
+ if (ignore_mouse)
+ return;
+
+ switch (e.button) {
+ case 0:
+ guac_mouse.currentState.left = true;
+ break;
+ case 1:
+ guac_mouse.currentState.middle = true;
+ break;
+ case 2:
+ guac_mouse.currentState.right = true;
+ break;
+ }
+
+ if (guac_mouse.onmousedown)
+ guac_mouse.onmousedown(guac_mouse.currentState);
+
+ }, false);
+
+ element.addEventListener("mouseup", function(e) {
+
+ cancelEvent(e);
+
+ // Do not handle if ignoring events
+ if (ignore_mouse)
+ return;
+
+ switch (e.button) {
+ case 0:
+ guac_mouse.currentState.left = false;
+ break;
+ case 1:
+ guac_mouse.currentState.middle = false;
+ break;
+ case 2:
+ guac_mouse.currentState.right = false;
+ break;
+ }
+
+ if (guac_mouse.onmouseup)
+ guac_mouse.onmouseup(guac_mouse.currentState);
+
+ }, false);
+
+ element.addEventListener("mouseout", function(e) {
+
+ // Get parent of the element the mouse pointer is leaving
+ if (!e) e = window.event;
+
+ // Check that mouseout is due to actually LEAVING the element
+ var target = e.relatedTarget || e.toElement;
+ while (target != null) {
+ if (target === element)
+ return;
+ target = target.parentNode;
+ }
+
+ cancelEvent(e);
+
+ // Release all buttons
+ if (guac_mouse.currentState.left
+ || guac_mouse.currentState.middle
+ || guac_mouse.currentState.right) {
+
+ guac_mouse.currentState.left = false;
+ guac_mouse.currentState.middle = false;
+ guac_mouse.currentState.right = false;
+
+ if (guac_mouse.onmouseup)
+ guac_mouse.onmouseup(guac_mouse.currentState);
+ }
+
+ }, false);
+
+ // Override selection on mouse event element.
+ element.addEventListener("selectstart", function(e) {
+ cancelEvent(e);
+ }, false);
+
+ // Ignore all pending mouse events when touch events are the apparent source
+ function ignorePendingMouseEvents() { ignore_mouse = guac_mouse.touchMouseThreshold; }
+
+ element.addEventListener("touchmove", ignorePendingMouseEvents, false);
+ element.addEventListener("touchstart", ignorePendingMouseEvents, false);
+ element.addEventListener("touchend", ignorePendingMouseEvents, false);
+
+ // Scroll wheel support
+ function mousewheel_handler(e) {
+
+ // Determine approximate scroll amount (in pixels)
+ var delta = e.deltaY || -e.wheelDeltaY || -e.wheelDelta;
+
+ // If successfully retrieved scroll amount, convert to pixels if not
+ // already in pixels
+ if (delta) {
+
+ // Convert to pixels if delta was lines
+ if (e.deltaMode === 1)
+ delta = e.deltaY * guac_mouse.PIXELS_PER_LINE;
+
+ // Convert to pixels if delta was pages
+ else if (e.deltaMode === 2)
+ delta = e.deltaY * guac_mouse.PIXELS_PER_PAGE;
+
+ }
+
+ // Otherwise, assume legacy mousewheel event and line scrolling
+ else
+ delta = e.detail * guac_mouse.PIXELS_PER_LINE;
+
+ // Update overall delta
+ scroll_delta += delta;
+
+ // Up
+ while (scroll_delta <= -guac_mouse.scrollThreshold) {
+
+ if (guac_mouse.onmousedown) {
+ guac_mouse.currentState.up = true;
+ guac_mouse.onmousedown(guac_mouse.currentState);
+ }
+
+ if (guac_mouse.onmouseup) {
+ guac_mouse.currentState.up = false;
+ guac_mouse.onmouseup(guac_mouse.currentState);
+ }
+
+ scroll_delta += guac_mouse.scrollThreshold;
+
+ }
+
+ // Down
+ while (scroll_delta >= guac_mouse.scrollThreshold) {
+
+ if (guac_mouse.onmousedown) {
+ guac_mouse.currentState.down = true;
+ guac_mouse.onmousedown(guac_mouse.currentState);
+ }
+
+ if (guac_mouse.onmouseup) {
+ guac_mouse.currentState.down = false;
+ guac_mouse.onmouseup(guac_mouse.currentState);
+ }
+
+ scroll_delta -= guac_mouse.scrollThreshold;
+
+ }
+
+ cancelEvent(e);
+
+ }
+
+ element.addEventListener('DOMMouseScroll', mousewheel_handler, false);
+ element.addEventListener('mousewheel', mousewheel_handler, false);
+ element.addEventListener('wheel', mousewheel_handler, false);
+
+};
+
+
+/**
+ * Provides cross-browser relative touch event translation for a given element.
+ *
+ * Touch events are translated into mouse events as if the touches occurred
+ * on a touchpad (drag to push the mouse pointer, tap to click).
+ *
+ * @constructor
+ * @param {Element} element The Element to use to provide touch events.
+ */
+Guacamole.Mouse.Touchpad = function(element) {
+
+ /**
+ * Reference to this Guacamole.Mouse.Touchpad.
+ * @private
+ */
+ var guac_touchpad = this;
+
+ /**
+ * The distance a two-finger touch must move per scrollwheel event, in
+ * pixels.
+ */
+ this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
+
+ /**
+ * The maximum number of milliseconds to wait for a touch to end for the
+ * gesture to be considered a click.
+ */
+ this.clickTimingThreshold = 250;
+
+ /**
+ * The maximum number of pixels to allow a touch to move for the gesture to
+ * be considered a click.
+ */
+ this.clickMoveThreshold = 10 * (window.devicePixelRatio || 1);
+
+ /**
+ * The current mouse state. The properties of this state are updated when
+ * mouse events fire. This state object is also passed in as a parameter to
+ * the handler of any mouse events.
+ *
+ * @type Guacamole.Mouse.State
+ */
+ this.currentState = new Guacamole.Mouse.State(
+ 0, 0,
+ false, false, false, false, false
+ );
+
+ /**
+ * Fired whenever a mouse button is effectively pressed. This can happen
+ * as part of a "click" gesture initiated by the user by tapping one
+ * or more fingers over the touchpad element, as part of a "scroll"
+ * gesture initiated by dragging two fingers up or down, etc.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmousedown = null;
+
+ /**
+ * Fired whenever a mouse button is effectively released. This can happen
+ * as part of a "click" gesture initiated by the user by tapping one
+ * or more fingers over the touchpad element, as part of a "scroll"
+ * gesture initiated by dragging two fingers up or down, etc.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmouseup = null;
+
+ /**
+ * Fired whenever the user moves the mouse by dragging their finger over
+ * the touchpad element.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmousemove = null;
+
+ var touch_count = 0;
+ var last_touch_x = 0;
+ var last_touch_y = 0;
+ var last_touch_time = 0;
+ var pixels_moved = 0;
+
+ var touch_buttons = {
+ 1: "left",
+ 2: "right",
+ 3: "middle"
+ };
+
+ var gesture_in_progress = false;
+ var click_release_timeout = null;
+
+ element.addEventListener("touchend", function(e) {
+
+ e.stopPropagation();
+ e.preventDefault();
+
+ // If we're handling a gesture AND this is the last touch
+ if (gesture_in_progress && e.touches.length == 0) {
+
+ var time = new Date().getTime();
+
+ // Get corresponding mouse button
+ var button = touch_buttons[touch_count];
+
+ // If mouse already down, release anad clear timeout
+ if (guac_touchpad.currentState[button]) {
+
+ // Fire button up event
+ guac_touchpad.currentState[button] = false;
+ if (guac_touchpad.onmouseup)
+ guac_touchpad.onmouseup(guac_touchpad.currentState);
+
+ // Clear timeout, if set
+ if (click_release_timeout) {
+ window.clearTimeout(click_release_timeout);
+ click_release_timeout = null;
+ }
+
+ }
+
+ // If single tap detected (based on time and distance)
+ if (time - last_touch_time <= guac_touchpad.clickTimingThreshold
+ && pixels_moved < guac_touchpad.clickMoveThreshold) {
+
+ // Fire button down event
+ guac_touchpad.currentState[button] = true;
+ if (guac_touchpad.onmousedown)
+ guac_touchpad.onmousedown(guac_touchpad.currentState);
+
+ // Delay mouse up - mouse up should be canceled if
+ // touchstart within timeout.
+ click_release_timeout = window.setTimeout(function() {
+
+ // Fire button up event
+ guac_touchpad.currentState[button] = false;
+ if (guac_touchpad.onmouseup)
+ guac_touchpad.onmouseup(guac_touchpad.currentState);
+
+ // Gesture now over
+ gesture_in_progress = false;
+
+ }, guac_touchpad.clickTimingThreshold);
+
+ }
+
+ // If we're not waiting to see if this is a click, stop gesture
+ if (!click_release_timeout)
+ gesture_in_progress = false;
+
+ }
+
+ }, false);
+
+ element.addEventListener("touchstart", function(e) {
+
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Track number of touches, but no more than three
+ touch_count = Math.min(e.touches.length, 3);
+
+ // Clear timeout, if set
+ if (click_release_timeout) {
+ window.clearTimeout(click_release_timeout);
+ click_release_timeout = null;
+ }
+
+ // Record initial touch location and time for touch movement
+ // and tap gestures
+ if (!gesture_in_progress) {
+
+ // Stop mouse events while touching
+ gesture_in_progress = true;
+
+ // Record touch location and time
+ var starting_touch = e.touches[0];
+ last_touch_x = starting_touch.clientX;
+ last_touch_y = starting_touch.clientY;
+ last_touch_time = new Date().getTime();
+ pixels_moved = 0;
+
+ }
+
+ }, false);
+
+ element.addEventListener("touchmove", function(e) {
+
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Get change in touch location
+ var touch = e.touches[0];
+ var delta_x = touch.clientX - last_touch_x;
+ var delta_y = touch.clientY - last_touch_y;
+
+ // Track pixels moved
+ pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
+
+ // If only one touch involved, this is mouse move
+ if (touch_count == 1) {
+
+ // Calculate average velocity in Manhatten pixels per millisecond
+ var velocity = pixels_moved / (new Date().getTime() - last_touch_time);
+
+ // Scale mouse movement relative to velocity
+ var scale = 1 + velocity;
+
+ // Update mouse location
+ guac_touchpad.currentState.x += delta_x*scale;
+ guac_touchpad.currentState.y += delta_y*scale;
+
+ // Prevent mouse from leaving screen
+
+ if (guac_touchpad.currentState.x < 0)
+ guac_touchpad.currentState.x = 0;
+ else if (guac_touchpad.currentState.x >= element.offsetWidth)
+ guac_touchpad.currentState.x = element.offsetWidth - 1;
+
+ if (guac_touchpad.currentState.y < 0)
+ guac_touchpad.currentState.y = 0;
+ else if (guac_touchpad.currentState.y >= element.offsetHeight)
+ guac_touchpad.currentState.y = element.offsetHeight - 1;
+
+ // Fire movement event, if defined
+ if (guac_touchpad.onmousemove)
+ guac_touchpad.onmousemove(guac_touchpad.currentState);
+
+ // Update touch location
+ last_touch_x = touch.clientX;
+ last_touch_y = touch.clientY;
+
+ }
+
+ // Interpret two-finger swipe as scrollwheel
+ else if (touch_count == 2) {
+
+ // If change in location passes threshold for scroll
+ if (Math.abs(delta_y) >= guac_touchpad.scrollThreshold) {
+
+ // Decide button based on Y movement direction
+ var button;
+ if (delta_y > 0) button = "down";
+ else button = "up";
+
+ // Fire button down event
+ guac_touchpad.currentState[button] = true;
+ if (guac_touchpad.onmousedown)
+ guac_touchpad.onmousedown(guac_touchpad.currentState);
+
+ // Fire button up event
+ guac_touchpad.currentState[button] = false;
+ if (guac_touchpad.onmouseup)
+ guac_touchpad.onmouseup(guac_touchpad.currentState);
+
+ // Only update touch location after a scroll has been
+ // detected
+ last_touch_x = touch.clientX;
+ last_touch_y = touch.clientY;
+
+ }
+
+ }
+
+ }, false);
+
+};
+
+/**
+ * Provides cross-browser absolute touch event translation for a given element.
+ *
+ * Touch events are translated into mouse events as if the touches occurred
+ * on a touchscreen (tapping anywhere on the screen clicks at that point,
+ * long-press to right-click).
+ *
+ * @constructor
+ * @param {Element} element The Element to use to provide touch events.
+ */
+Guacamole.Mouse.Touchscreen = function(element) {
+
+ /**
+ * Reference to this Guacamole.Mouse.Touchscreen.
+ * @private
+ */
+ var guac_touchscreen = this;
+
+ /**
+ * The distance a two-finger touch must move per scrollwheel event, in
+ * pixels.
+ */
+ this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
+
+ /**
+ * The current mouse state. The properties of this state are updated when
+ * mouse events fire. This state object is also passed in as a parameter to
+ * the handler of any mouse events.
+ *
+ * @type Guacamole.Mouse.State
+ */
+ this.currentState = new Guacamole.Mouse.State(
+ 0, 0,
+ false, false, false, false, false
+ );
+
+ /**
+ * Fired whenever a mouse button is effectively pressed. This can happen
+ * as part of a "mousedown" gesture initiated by the user by pressing one
+ * finger over the touchscreen element, as part of a "scroll" gesture
+ * initiated by dragging two fingers up or down, etc.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmousedown = null;
+
+ /**
+ * Fired whenever a mouse button is effectively released. This can happen
+ * as part of a "mouseup" gesture initiated by the user by removing the
+ * finger pressed against the touchscreen element, or as part of a "scroll"
+ * gesture initiated by dragging two fingers up or down, etc.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmouseup = null;
+
+ /**
+ * Fired whenever the user moves the mouse by dragging their finger over
+ * the touchscreen element. Note that unlike Guacamole.Mouse.Touchpad,
+ * dragging a finger over the touchscreen element will always cause
+ * the mouse button to be effectively down, as if clicking-and-dragging.
+ *
+ * @event
+ * @param {Guacamole.Mouse.State} state The current mouse state.
+ */
+ this.onmousemove = null;
+
+ element.addEventListener("touchend", function(e) {
+
+ // Ignore if more than one touch
+ if (e.touches.length + e.changedTouches.length != 1)
+ return;
+
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Release button
+ guac_touchscreen.currentState.left = false;
+
+ // Fire release event when the last touch is released, if event defined
+ if (e.touches.length == 0 && guac_touchscreen.onmouseup)
+ guac_touchscreen.onmouseup(guac_touchscreen.currentState);
+
+ }, false);
+
+ element.addEventListener("touchstart", function(e) {
+
+ // Ignore if more than one touch
+ if (e.touches.length != 1)
+ return;
+
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Get touch
+ var touch = e.touches[0];
+
+ // Update state
+ guac_touchscreen.currentState.left = true;
+ guac_touchscreen.currentState.fromClientPosition(element, touch.clientX, touch.clientY);
+
+ // Fire press event, if defined
+ if (guac_touchscreen.onmousedown)
+ guac_touchscreen.onmousedown(guac_touchscreen.currentState);
+
+
+ }, false);
+
+ element.addEventListener("touchmove", function(e) {
+
+ // Ignore if more than one touch
+ if (e.touches.length != 1)
+ return;
+
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Get touch
+ var touch = e.touches[0];
+
+ // Update state
+ guac_touchscreen.currentState.fromClientPosition(element, touch.clientX, touch.clientY);
+
+ // Fire movement event, if defined
+ if (guac_touchscreen.onmousemove)
+ guac_touchscreen.onmousemove(guac_touchscreen.currentState);
+
+ }, false);
+
+};
+
+/**
+ * Simple container for properties describing the state of a mouse.
+ *
+ * @constructor
+ * @param {Number} x The X position of the mouse pointer in pixels.
+ * @param {Number} y The Y position of the mouse pointer in pixels.
+ * @param {Boolean} left Whether the left mouse button is pressed.
+ * @param {Boolean} middle Whether the middle mouse button is pressed.
+ * @param {Boolean} right Whether the right mouse button is pressed.
+ * @param {Boolean} up Whether the up mouse button is pressed (the fourth
+ * button, usually part of a scroll wheel).
+ * @param {Boolean} down Whether the down mouse button is pressed (the fifth
+ * button, usually part of a scroll wheel).
+ */
+Guacamole.Mouse.State = function(x, y, left, middle, right, up, down) {
+
+ /**
+ * Reference to this Guacamole.Mouse.State.
+ * @private
+ */
+ var guac_state = this;
+
+ /**
+ * The current X position of the mouse pointer.
+ * @type Number
+ */
+ this.x = x;
+
+ /**
+ * The current Y position of the mouse pointer.
+ * @type Number
+ */
+ this.y = y;
+
+ /**
+ * Whether the left mouse button is currently pressed.
+ * @type Boolean
+ */
+ this.left = left;
+
+ /**
+ * Whether the middle mouse button is currently pressed.
+ * @type Boolean
+ */
+ this.middle = middle
+
+ /**
+ * Whether the right mouse button is currently pressed.
+ * @type Boolean
+ */
+ this.right = right;
+
+ /**
+ * Whether the up mouse button is currently pressed. This is the fourth
+ * mouse button, associated with upward scrolling of the mouse scroll
+ * wheel.
+ * @type Boolean
+ */
+ this.up = up;
+
+ /**
+ * Whether the down mouse button is currently pressed. This is the fifth
+ * mouse button, associated with downward scrolling of the mouse scroll
+ * wheel.
+ * @type Boolean
+ */
+ this.down = down;
+
+ /**
+ * Updates the position represented within this state object by the given
+ * element and clientX/clientY coordinates (commonly available within event
+ * objects). Position is translated from clientX/clientY (relative to
+ * viewport) to element-relative coordinates.
+ *
+ * @param {Element} element The element the coordinates should be relative
+ * to.
+ * @param {Number} clientX The X coordinate to translate, viewport-relative.
+ * @param {Number} clientY The Y coordinate to translate, viewport-relative.
+ */
+ this.fromClientPosition = function(element, clientX, clientY) {
+
+ guac_state.x = clientX - element.offsetLeft;
+ guac_state.y = clientY - element.offsetTop;
+
+ // This is all JUST so we can get the mouse position within the element
+ var parent = element.offsetParent;
+ while (parent && !(parent === document.body)) {
+ guac_state.x -= parent.offsetLeft - parent.scrollLeft;
+ guac_state.y -= parent.offsetTop - parent.scrollTop;
+
+ parent = parent.offsetParent;
+ }
+
+ // Element ultimately depends on positioning within document body,
+ // take document scroll into account.
+ if (parent) {
+ var documentScrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
+ var documentScrollTop = document.body.scrollTop || document.documentElement.scrollTop;
+
+ guac_state.x -= parent.offsetLeft - documentScrollLeft;
+ guac_state.y -= parent.offsetTop - documentScrollTop;
+ }
+
+ };
+
+};
+
diff --git a/guacamole-common-js/src/main/resources/oskeyboard.js b/guacamole-common-js/src/main/resources/oskeyboard.js
new file mode 100644
index 0000000..7da6b4b
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/oskeyboard.js
@@ -0,0 +1,653 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guac-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Dynamic on-screen keyboard. Given the URL to an XML keyboard layout file,
+ * this object will download and use the XML to construct a clickable on-screen
+ * keyboard with its own key events.
+ *
+ * @constructor
+ * @param {String} url The URL of an XML keyboard layout file.
+ */
+Guacamole.OnScreenKeyboard = function(url) {
+
+ var on_screen_keyboard = this;
+
+ /**
+ * State of all modifiers. This is the bitwise OR of all active modifier
+ * values.
+ *
+ * @private
+ */
+ var modifiers = 0;
+
+ var scaledElements = [];
+
+ var modifier_masks = {};
+ var next_mask = 1;
+
+ /**
+ * Adds a class to an element.
+ *
+ * @private
+ * @function
+ * @param {Element} element The element to add a class to.
+ * @param {String} classname The name of the class to add.
+ */
+ var addClass;
+
+ /**
+ * Removes a class from an element.
+ *
+ * @private
+ * @function
+ * @param {Element} element The element to remove a class from.
+ * @param {String} classname The name of the class to remove.
+ */
+ var removeClass;
+
+ /**
+ * The number of mousemove events to require before re-enabling mouse
+ * event handling after receiving a touch event.
+ */
+ this.touchMouseThreshold = 3;
+
+ /**
+ * Counter of mouse events to ignore. This decremented by mousemove, and
+ * while non-zero, mouse events will have no effect.
+ * @private
+ */
+ var ignore_mouse = 0;
+
+ // Ignore all pending mouse events when touch events are the apparent source
+ function ignorePendingMouseEvents() { ignore_mouse = on_screen_keyboard.touchMouseThreshold; }
+
+ // If Node.classList is supported, implement addClass/removeClass using that
+ if (Node.classList) {
+
+ /** @ignore */
+ addClass = function(element, classname) {
+ element.classList.add(classname);
+ };
+
+ /** @ignore */
+ removeClass = function(element, classname) {
+ element.classList.remove(classname);
+ };
+
+ }
+
+ // Otherwise, implement own
+ else {
+
+ /** @ignore */
+ addClass = function(element, classname) {
+
+ // Simply add new class
+ element.className += " " + classname;
+
+ };
+
+ /** @ignore */
+ removeClass = function(element, classname) {
+
+ // Filter out classes with given name
+ element.className = element.className.replace(/([^ ]+)[ ]*/g,
+ function(match, testClassname, spaces, offset, string) {
+
+ // If same class, remove
+ if (testClassname == classname)
+ return "";
+
+ // Otherwise, allow
+ return match;
+
+ }
+ );
+
+ };
+
+ }
+
+ // Returns a unique power-of-two value for the modifier with the
+ // given name. The same value will be returned for the same modifier.
+ function getModifierMask(name) {
+
+ var value = modifier_masks[name];
+ if (!value) {
+
+ // Get current modifier, advance to next
+ value = next_mask;
+ next_mask <<= 1;
+
+ // Store value of this modifier
+ modifier_masks[name] = value;
+
+ }
+
+ return value;
+
+ }
+
+ function ScaledElement(element, width, height, scaleFont) {
+
+ this.width = width;
+ this.height = height;
+
+ this.scale = function(pixels) {
+ element.style.width = (width * pixels) + "px";
+ element.style.height = (height * pixels) + "px";
+
+ if (scaleFont) {
+ element.style.lineHeight = (height * pixels) + "px";
+ element.style.fontSize = pixels + "px";
+ }
+ }
+
+ }
+
+ // For each child of element, call handler defined in next
+ function parseChildren(element, next) {
+
+ var children = element.childNodes;
+ for (var i=0; i<children.length; i++) {
+
+ // Get child node
+ var child = children[i];
+
+ // Do not parse text nodes
+ if (!child.tagName)
+ continue;
+
+ // Get handler for node
+ var handler = next[child.tagName];
+
+ // Call handler if defined
+ if (handler)
+ handler(child);
+
+ // Throw exception if no handler
+ else
+ throw new Error(
+ "Unexpected " + child.tagName
+ + " within " + element.tagName
+ );
+
+ }
+
+ }
+
+ // Create keyboard
+ var keyboard = document.createElement("div");
+ keyboard.className = "guac-keyboard";
+
+ // Retrieve keyboard XML
+ var xmlhttprequest = new XMLHttpRequest();
+ xmlhttprequest.open("GET", url, false);
+ xmlhttprequest.send(null);
+
+ var xml = xmlhttprequest.responseXML;
+
+ if (xml) {
+
+ function parse_row(e) {
+
+ var row = document.createElement("div");
+ row.className = "guac-keyboard-row";
+
+ parseChildren(e, {
+
+ "column": function(e) {
+ row.appendChild(parse_column(e));
+ },
+
+ "gap": function parse_gap(e) {
+
+ // Create element
+ var gap = document.createElement("div");
+ gap.className = "guac-keyboard-gap";
+
+ // Set gap size
+ var gap_units = 1;
+ if (e.getAttribute("size"))
+ gap_units = parseFloat(e.getAttribute("size"));
+
+ scaledElements.push(new ScaledElement(gap, gap_units, gap_units));
+ row.appendChild(gap);
+
+ },
+
+ "key": function parse_key(e) {
+
+ // Create element
+ var key_element = document.createElement("div");
+ key_element.className = "guac-keyboard-key";
+
+ // Append class if specified
+ if (e.getAttribute("class"))
+ key_element.className += " " + e.getAttribute("class");
+
+ // Position keys using container div
+ var key_container_element = document.createElement("div");
+ key_container_element.className = "guac-keyboard-key-container";
+ key_container_element.appendChild(key_element);
+
+ // Create key
+ var key = new Guacamole.OnScreenKeyboard.Key();
+
+ // Set key size
+ var key_units = 1;
+ if (e.getAttribute("size"))
+ key_units = parseFloat(e.getAttribute("size"));
+
+ key.size = key_units;
+
+ parseChildren(e, {
+ "cap": function parse_cap(e) {
+
+ // TODO: Handle "sticky" attribute
+
+ // Get content of key cap
+ var content = e.textContent || e.text;
+
+ // If read as blank, assume cap is a single space.
+ if (content.length == 0)
+ content = " ";
+
+ // Get keysym
+ var real_keysym = null;
+ if (e.getAttribute("keysym"))
+ real_keysym = parseInt(e.getAttribute("keysym"));
+
+ // If no keysym specified, try to get from key content
+ else if (content.length == 1) {
+
+ var charCode = content.charCodeAt(0);
+ if (charCode >= 0x0000 && charCode <= 0x00FF)
+ real_keysym = charCode;
+ else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
+ real_keysym = 0x01000000 | charCode;
+
+ }
+
+ // Create cap
+ var cap = new Guacamole.OnScreenKeyboard.Cap(content, real_keysym);
+
+ if (e.getAttribute("modifier"))
+ cap.modifier = e.getAttribute("modifier");
+
+ // Create cap element
+ var cap_element = document.createElement("div");
+ cap_element.className = "guac-keyboard-cap";
+ cap_element.textContent = content;
+ key_element.appendChild(cap_element);
+
+ // Append class if specified
+ if (e.getAttribute("class"))
+ cap_element.className += " " + e.getAttribute("class");
+
+ // Get modifier value
+ var modifierValue = 0;
+ if (e.getAttribute("if")) {
+
+ // Get modifier value for specified comma-delimited
+ // list of required modifiers.
+ var requirements = e.getAttribute("if").split(",");
+ for (var i=0; i<requirements.length; i++) {
+ modifierValue |= getModifierMask(requirements[i]);
+ addClass(cap_element, "guac-keyboard-requires-" + requirements[i]);
+ addClass(key_element, "guac-keyboard-uses-" + requirements[i]);
+ }
+
+ }
+
+ // Store cap
+ key.modifierMask |= modifierValue;
+ key.caps[modifierValue] = cap;
+
+ }
+ });
+
+ scaledElements.push(new ScaledElement(key_container_element, key_units, 1, true));
+ row.appendChild(key_container_element);
+
+ // Set up click handler for key
+ function press() {
+
+ // Press key if not yet pressed
+ if (!key.pressed) {
+
+ addClass(key_element, "guac-keyboard-pressed");
+
+ // Get current cap based on modifier state
+ var cap = key.getCap(modifiers);
+
+ // Update modifier state
+ if (cap.modifier) {
+
+ // Construct classname for modifier
+ var modifierClass = "guac-keyboard-modifier-" + cap.modifier;
+ var modifierMask = getModifierMask(cap.modifier);
+
+ // Toggle modifier state
+ modifiers ^= modifierMask;
+
+ // Activate modifier if pressed
+ if (modifiers & modifierMask) {
+
+ addClass(keyboard, modifierClass);
+
+ // Send key event
+ if (on_screen_keyboard.onkeydown && cap.keysym)
+ on_screen_keyboard.onkeydown(cap.keysym);
+
+ }
+
+ // Deactivate if not pressed
+ else {
+
+ removeClass(keyboard, modifierClass);
+
+ // Send key event
+ if (on_screen_keyboard.onkeyup && cap.keysym)
+ on_screen_keyboard.onkeyup(cap.keysym);
+
+ }
+
+ }
+
+ // If not modifier, send key event now
+ else if (on_screen_keyboard.onkeydown && cap.keysym)
+ on_screen_keyboard.onkeydown(cap.keysym);
+
+ // Mark key as pressed
+ key.pressed = true;
+
+ }
+
+ }
+
+ function release() {
+
+ // Release key if currently pressed
+ if (key.pressed) {
+
+ // Get current cap based on modifier state
+ var cap = key.getCap(modifiers);
+
+ removeClass(key_element, "guac-keyboard-pressed");
+
+ // Send key event if not a modifier key
+ if (!cap.modifier && on_screen_keyboard.onkeyup && cap.keysym)
+ on_screen_keyboard.onkeyup(cap.keysym);
+
+ // Mark key as released
+ key.pressed = false;
+
+ }
+
+ }
+
+ function touchPress(e) {
+ e.preventDefault();
+ ignore_mouse = on_screen_keyboard.touchMouseThreshold;
+ press();
+ }
+
+ function touchRelease(e) {
+ e.preventDefault();
+ ignore_mouse = on_screen_keyboard.touchMouseThreshold;
+ release();
+ }
+
+ function mousePress(e) {
+ e.preventDefault();
+ if (ignore_mouse == 0)
+ press();
+ }
+
+ function mouseRelease(e) {
+ e.preventDefault();
+ if (ignore_mouse == 0)
+ release();
+ }
+
+ key_element.addEventListener("touchstart", touchPress, true);
+ key_element.addEventListener("touchend", touchRelease, true);
+
+ key_element.addEventListener("mousedown", mousePress, true);
+ key_element.addEventListener("mouseup", mouseRelease, true);
+ key_element.addEventListener("mouseout", mouseRelease, true);
+
+ }
+
+ });
+
+ return row;
+
+ }
+
+ function parse_column(e) {
+
+ var col = document.createElement("div");
+ col.className = "guac-keyboard-column";
+
+ if (col.getAttribute("align"))
+ col.style.textAlign = col.getAttribute("align");
+
+ // Columns can only contain rows
+ parseChildren(e, {
+ "row": function(e) {
+ col.appendChild(parse_row(e));
+ }
+ });
+
+ return col;
+
+ }
+
+
+ // Parse document
+ var keyboard_element = xml.documentElement;
+ if (keyboard_element.tagName != "keyboard")
+ throw new Error("Root element must be keyboard");
+
+ // Get attributes
+ if (!keyboard_element.getAttribute("size"))
+ throw new Error("size attribute is required for keyboard");
+
+ var keyboard_size = parseFloat(keyboard_element.getAttribute("size"));
+
+ parseChildren(keyboard_element, {
+
+ "row": function(e) {
+ keyboard.appendChild(parse_row(e));
+ },
+
+ "column": function(e) {
+ keyboard.appendChild(parse_column(e));
+ }
+
+ });
+
+ }
+
+ // Do not allow selection or mouse movement to propagate/register.
+ keyboard.onselectstart =
+ keyboard.onmousemove =
+ keyboard.onmouseup =
+ keyboard.onmousedown =
+ function(e) {
+
+ // If ignoring events, decrement counter
+ if (ignore_mouse)
+ ignore_mouse--;
+
+ e.stopPropagation();
+ return false;
+
+ };
+
+ /**
+ * Fired whenever the user presses a key on this Guacamole.OnScreenKeyboard.
+ *
+ * @event
+ * @param {Number} keysym The keysym of the key being pressed.
+ */
+ this.onkeydown = null;
+
+ /**
+ * Fired whenever the user releases a key on this Guacamole.OnScreenKeyboard.
+ *
+ * @event
+ * @param {Number} keysym The keysym of the key being released.
+ */
+ this.onkeyup = null;
+
+ /**
+ * Returns the element containing the entire on-screen keyboard.
+ * @returns {Element} The element containing the entire on-screen keyboard.
+ */
+ this.getElement = function() {
+ return keyboard;
+ };
+
+ /**
+ * Resizes all elements within this Guacamole.OnScreenKeyboard such that
+ * the width is close to but does not exceed the specified width. The
+ * height of the keyboard is determined based on the width.
+ *
+ * @param {Number} width The width to resize this Guacamole.OnScreenKeyboard
+ * to, in pixels.
+ */
+ this.resize = function(width) {
+
+ // Get pixel size of a unit
+ var unit = Math.floor(width * 10 / keyboard_size) / 10;
+
+ // Resize all scaled elements
+ for (var i=0; i<scaledElements.length; i++) {
+ var scaledElement = scaledElements[i];
+ scaledElement.scale(unit)
+ }
+
+ };
+
+};
+
+
+/**
+ * Basic representation of a single key of a keyboard. Each key has a set of
+ * caps associated with tuples of modifiers. The cap determins what happens
+ * when a key is pressed, while it is the state of modifier keys that determines
+ * what cap is in effect on any particular key.
+ *
+ * @constructor
+ */
+Guacamole.OnScreenKeyboard.Key = function() {
+
+ var key = this;
+
+ /**
+ * Whether this key is currently pressed.
+ */
+ this.pressed = false;
+
+ /**
+ * Width of the key, relative to the size of the keyboard.
+ */
+ this.size = 1;
+
+ /**
+ * An associative map of all caps by modifier.
+ */
+ this.caps = {};
+
+ /**
+ * Bit mask with all modifiers that affect this key set.
+ */
+ this.modifierMask = 0;
+
+ /**
+ * Given the bitwise OR of all active modifiers, returns the key cap
+ * which applies.
+ */
+ this.getCap = function(modifier) {
+ return key.caps[modifier & key.modifierMask];
+ };
+
+};
+
+/**
+ * Basic representation of a cap of a key. The cap is the visible part of a key
+ * and determines the active behavior of a key when pressed. The state of all
+ * modifiers on the keyboard determines the active cap for all keys, thus
+ * each cap is associated with a set of modifiers.
+ *
+ * @constructor
+ * @param {String} text The text to be displayed within this cap.
+ * @param {Number} keysym The keysym this cap sends when its associated key is
+ * pressed or released.
+ * @param {String} modifier The modifier represented by this cap.
+ */
+Guacamole.OnScreenKeyboard.Cap = function(text, keysym, modifier) {
+
+ /**
+ * Modifier represented by this keycap
+ */
+ this.modifier = null;
+
+ /**
+ * The text to be displayed within this keycap
+ */
+ this.text = text;
+
+ /**
+ * The keysym this cap sends when its associated key is pressed/released
+ */
+ this.keysym = keysym;
+
+ // Set modifier if provided
+ if (modifier) this.modifier = modifier;
+
+};
diff --git a/guacamole-common-js/src/main/resources/tunnel.js b/guacamole-common-js/src/main/resources/tunnel.js
new file mode 100644
index 0000000..b66d830
--- /dev/null
+++ b/guacamole-common-js/src/main/resources/tunnel.js
@@ -0,0 +1,832 @@
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
+ */
+var Guacamole = Guacamole || {};
+
+/**
+ * Core object providing abstract communication for Guacamole. This object
+ * is a null implementation whose functions do nothing. Guacamole applications
+ * should use {@link Guacamole.HTTPTunnel} instead, or implement their own tunnel based
+ * on this one.
+ *
+ * @constructor
+ * @see Guacamole.HTTPTunnel
+ */
+Guacamole.Tunnel = function() {
+
+ /**
+ * Connect to the tunnel with the given optional data. This data is
+ * typically used for authentication. The format of data accepted is
+ * up to the tunnel implementation.
+ *
+ * @param {String} data The data to send to the tunnel when connecting.
+ */
+ this.connect = function(data) {};
+
+ /**
+ * Disconnect from the tunnel.
+ */
+ this.disconnect = function() {};
+
+ /**
+ * Send the given message through the tunnel to the service on the other
+ * side. All messages are guaranteed to be received in the order sent.
+ *
+ * @param {...} elements The elements of the message to send to the
+ * service on the other side of the tunnel.
+ */
+ this.sendMessage = function(elements) {};
+
+ /**
+ * Fired whenever an error is encountered by the tunnel.
+ *
+ * @event
+ * @param {String} message A human-readable description of the error that
+ * occurred.
+ */
+ this.onerror = null;
+
+ /**
+ * Fired once for every complete Guacamole instruction received, in order.
+ *
+ * @event
+ * @param {String} opcode The Guacamole instruction opcode.
+ * @param {Array} parameters The parameters provided for the instruction,
+ * if any.
+ */
+ this.oninstruction = null;
+
+};
+
+/**
+ * Guacamole Tunnel implemented over HTTP via XMLHttpRequest.
+ *
+ * @constructor
+ * @augments Guacamole.Tunnel
+ * @param {String} tunnelURL The URL of the HTTP tunneling service.
+ */
+Guacamole.HTTPTunnel = function(tunnelURL) {
+
+ /**
+ * Reference to this HTTP tunnel.
+ * @private
+ */
+ var tunnel = this;
+
+ var tunnel_uuid;
+
+ var TUNNEL_CONNECT = tunnelURL + "?connect";
+ var TUNNEL_READ = tunnelURL + "?read:";
+ var TUNNEL_WRITE = tunnelURL + "?write:";
+
+ var STATE_IDLE = 0;
+ var STATE_CONNECTED = 1;
+ var STATE_DISCONNECTED = 2;
+
+ var currentState = STATE_IDLE;
+
+ var POLLING_ENABLED = 1;
+ var POLLING_DISABLED = 0;
+
+ // Default to polling - will be turned off automatically if not needed
+ var pollingMode = POLLING_ENABLED;
+
+ var sendingMessages = false;
+ var outputMessageBuffer = "";
+
+ this.sendMessage = function() {
+
+ // Do not attempt to send messages if not connected
+ if (currentState != STATE_CONNECTED)
+ return;
+
+ // Do not attempt to send empty messages
+ if (arguments.length == 0)
+ return;
+
+ /**
+ * Converts the given value to a length/string pair for use as an
+ * element in a Guacamole instruction.
+ *
+ * @private
+ * @param value The value to convert.
+ * @return {String} The converted value.
+ */
+ function getElement(value) {
+ var string = new String(value);
+ return string.length + "." + string;
+ }
+
+ // Initialized message with first element
+ var message = getElement(arguments[0]);
+
+ // Append remaining elements
+ for (var i=1; i<arguments.length; i++)
+ message += "," + getElement(arguments[i]);
+
+ // Final terminator
+ message += ";";
+
+ // Add message to buffer
+ outputMessageBuffer += message;
+
+ // Send if not currently sending
+ if (!sendingMessages)
+ sendPendingMessages();
+
+ };
+
+ function sendPendingMessages() {
+
+ if (outputMessageBuffer.length > 0) {
+
+ sendingMessages = true;
+
+ var message_xmlhttprequest = new XMLHttpRequest();
+ message_xmlhttprequest.open("POST", TUNNEL_WRITE + tunnel_uuid);
+ message_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+
+ // Once response received, send next queued event.
+ message_xmlhttprequest.onreadystatechange = function() {
+ if (message_xmlhttprequest.readyState == 4) {
+
+ // If an error occurs during send, handle it
+ if (message_xmlhttprequest.status != 200)
+ handleHTTPTunnelError(message_xmlhttprequest);
+
+ // Otherwise, continue the send loop
+ else
+ sendPendingMessages();
+
+ }
+ }
+
+ message_xmlhttprequest.send(outputMessageBuffer);
+ outputMessageBuffer = ""; // Clear buffer
+
+ }
+ else
+ sendingMessages = false;
+
+ }
+
+ function getHTTPTunnelErrorMessage(xmlhttprequest) {
+
+ var status = xmlhttprequest.status;
+
+ // Special cases
+ if (status == 0) return "Disconnected";
+ if (status == 200) return "Success";
+ if (status == 403) return "Unauthorized";
+ if (status == 404) return "Connection closed"; /* While it may be more
+ * accurate to say the
+ * connection does not
+ * exist, it is confusing
+ * to the user.
+ *
+ * In general, this error
+ * will only happen when
+ * the tunnel does not
+ * exist, which happens
+ * after the connection
+ * is closed and the
+ * tunnel is detached.
+ */
+ // Internal server errors
+ if (status >= 500 && status <= 599) return "Server error";
+
+ // Otherwise, unknown
+ return "Unknown error";
+
+ }
+
+ function handleHTTPTunnelError(xmlhttprequest) {
+
+ // Get error message
+ var message = getHTTPTunnelErrorMessage(xmlhttprequest);
+
+ // Call error handler
+ if (tunnel.onerror) tunnel.onerror(message);
+
+ // Finish
+ tunnel.disconnect();
+
+ }
+
+
+ function handleResponse(xmlhttprequest) {
+
+ var interval = null;
+ var nextRequest = null;
+
+ var dataUpdateEvents = 0;
+
+ // The location of the last element's terminator
+ var elementEnd = -1;
+
+ // Where to start the next length search or the next element
+ var startIndex = 0;
+
+ // Parsed elements
+ var elements = new Array();
+
+ function parseResponse() {
+
+ // Do not handle responses if not connected
+ if (currentState != STATE_CONNECTED) {
+
+ // Clean up interval if polling
+ if (interval != null)
+ clearInterval(interval);
+
+ return;
+ }
+
+ // Do not parse response yet if not ready
+ if (xmlhttprequest.readyState < 2) return;
+
+ // Attempt to read status
+ var status;
+ try { status = xmlhttprequest.status; }
+
+ // If status could not be read, assume successful.
+ catch (e) { status = 200; }
+
+ // Start next request as soon as possible IF request was successful
+ if (nextRequest == null && status == 200)
+ nextRequest = makeRequest();
+
+ // Parse stream when data is received and when complete.
+ if (xmlhttprequest.readyState == 3 ||
+ xmlhttprequest.readyState == 4) {
+
+ // Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
+ if (pollingMode == POLLING_ENABLED) {
+ if (xmlhttprequest.readyState == 3 && interval == null)
+ interval = setInterval(parseResponse, 30);
+ else if (xmlhttprequest.readyState == 4 && interval != null)
+ clearInterval(interval);
+ }
+
+ // If canceled, stop transfer
+ if (xmlhttprequest.status == 0) {
+ tunnel.disconnect();
+ return;
+ }
+
+ // Halt on error during request
+ else if (xmlhttprequest.status != 200) {
+ handleHTTPTunnelError(xmlhttprequest);
+ return;
+ }
+
+ // Attempt to read in-progress data
+ var current;
+ try { current = xmlhttprequest.responseText; }
+
+ // Do not attempt to parse if data could not be read
+ catch (e) { return; }
+
+ // While search is within currently received data
+ while (elementEnd < current.length) {
+
+ // If we are waiting for element data
+ if (elementEnd >= startIndex) {
+
+ // We now have enough data for the element. Parse.
+ var element = current.substring(startIndex, elementEnd);
+ var terminator = current.substring(elementEnd, elementEnd+1);
+
+ // Add element to array
+ elements.push(element);
+
+ // If last element, handle instruction
+ if (terminator == ";") {
+
+ // Get opcode
+ var opcode = elements.shift();
+
+ // Call instruction handler.
+ if (tunnel.oninstruction != null)
+ tunnel.oninstruction(opcode, elements);
+
+ // Clear elements
+ elements.length = 0;
+
+ }
+
+ // Start searching for length at character after
+ // element terminator
+ startIndex = elementEnd + 1;
+
+ }
+
+ // Search for end of length
+ var lengthEnd = current.indexOf(".", startIndex);
+ if (lengthEnd != -1) {
+
+ // Parse length
+ var length = parseInt(current.substring(elementEnd+1, lengthEnd));
+
+ // If we're done parsing, handle the next response.
+ if (length == 0) {
+
+ // Clean up interval if polling
+ if (interval != null)
+ clearInterval(interval);
+
+ // Clean up object
+ xmlhttprequest.onreadystatechange = null;
+ xmlhttprequest.abort();
+
+ // Start handling next request
+ if (nextRequest)
+ handleResponse(nextRequest);
+
+ // Done parsing
+ break;
+
+ }
+
+ // Calculate start of element
+ startIndex = lengthEnd + 1;
+
+ // Calculate location of element terminator
+ elementEnd = startIndex + length;
+
+ }
+
+ // If no period yet, continue search when more data
+ // is received
+ else {
+ startIndex = current.length;
+ break;
+ }
+
+ } // end parse loop
+
+ }
+
+ }
+
+ // If response polling enabled, attempt to detect if still
+ // necessary (via wrapping parseResponse())
+ if (pollingMode == POLLING_ENABLED) {
+ xmlhttprequest.onreadystatechange = function() {
+
+ // If we receive two or more readyState==3 events,
+ // there is no need to poll.
+ if (xmlhttprequest.readyState == 3) {
+ dataUpdateEvents++;
+ if (dataUpdateEvents >= 2) {
+ pollingMode = POLLING_DISABLED;
+ xmlhttprequest.onreadystatechange = parseResponse;
+ }
+ }
+
+ parseResponse();
+ }
+ }
+
+ // Otherwise, just parse
+ else
+ xmlhttprequest.onreadystatechange = parseResponse;
+
+ parseResponse();
+
+ }
+
+ /**
+ * Arbitrary integer, unique for each tunnel read request.
+ * @private
+ */
+ var request_id = 0;
+
+ function makeRequest() {
+
+ // Make request, increment request ID
+ var xmlhttprequest = new XMLHttpRequest();
+ xmlhttprequest.open("GET", TUNNEL_READ + tunnel_uuid + ":" + (request_id++));
+ xmlhttprequest.send(null);
+
+ return xmlhttprequest;
+
+ }
+
+ this.connect = function(data) {
+
+ // Start tunnel and connect synchronously
+ var connect_xmlhttprequest = new XMLHttpRequest();
+ connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, false);
+ connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ connect_xmlhttprequest.send(data);
+
+ // If failure, throw error
+ if (connect_xmlhttprequest.status != 200) {
+ var message = getHTTPTunnelErrorMessage(connect_xmlhttprequest);
+ throw new Error(message);
+ }
+
+ // Get UUID from response
+ tunnel_uuid = connect_xmlhttprequest.responseText;
+
+ // Start reading data
+ currentState = STATE_CONNECTED;
+ handleResponse(makeRequest());
+
+ };
+
+ this.disconnect = function() {
+ currentState = STATE_DISCONNECTED;
+ };
+
+};
+
+Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
+
+
+/**
+ * Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
+ *
+ * @constructor
+ * @augments Guacamole.Tunnel
+ * @param {String} tunnelURL The URL of the WebSocket tunneling service.
+ */
+Guacamole.WebSocketTunnel = function(tunnelURL) {
+
+ /**
+ * Reference to this WebSocket tunnel.
+ * @private
+ */
+ var tunnel = this;
+
+ /**
+ * The WebSocket used by this tunnel.
+ * @private
+ */
+ var socket = null;
+
+ /**
+ * The WebSocket protocol corresponding to the protocol used for the current
+ * location.
+ * @private
+ */
+ var ws_protocol = {
+ "http:": "ws:",
+ "https:": "wss:"
+ };
+
+ var status_code = {
+ 1000: "Connection closed normally.",
+ 1001: "Connection shut down.",
+ 1002: "Protocol error.",
+ 1003: "Invalid data.",
+ 1004: "[UNKNOWN, RESERVED]",
+ 1005: "No status code present.",
+ 1006: "Connection closed abnormally.",
+ 1007: "Inconsistent data type.",
+ 1008: "Policy violation.",
+ 1009: "Message too large.",
+ 1010: "Extension negotiation failed."
+ };
+
+ var STATE_IDLE = 0;
+ var STATE_CONNECTED = 1;
+ var STATE_DISCONNECTED = 2;
+
+ var currentState = STATE_IDLE;
+
+ // Transform current URL to WebSocket URL
+
+ // If not already a websocket URL
+ if ( tunnelURL.substring(0, 3) != "ws:"
+ && tunnelURL.substring(0, 4) != "wss:") {
+
+ var protocol = ws_protocol[window.location.protocol];
+
+ // If absolute URL, convert to absolute WS URL
+ if (tunnelURL.substring(0, 1) == "/")
+ tunnelURL =
+ protocol
+ + "//" + window.location.host
+ + tunnelURL;
+
+ // Otherwise, construct absolute from relative URL
+ else {
+
+ // Get path from pathname
+ var slash = window.location.pathname.lastIndexOf("/");
+ var path = window.location.pathname.substring(0, slash + 1);
+
+ // Construct absolute URL
+ tunnelURL =
+ protocol
+ + "//" + window.location.host
+ + path
+ + tunnelURL;
+
+ }
+
+ }
+
+ this.sendMessage = function(elements) {
+
+ // Do not attempt to send messages if not connected
+ if (currentState != STATE_CONNECTED)
+ return;
+
+ // Do not attempt to send empty messages
+ if (arguments.length == 0)
+ return;
+
+ /**
+ * Converts the given value to a length/string pair for use as an
+ * element in a Guacamole instruction.
+ *
+ * @private
+ * @param value The value to convert.
+ * @return {String} The converted value.
+ */
+ function getElement(value) {
+ var string = new String(value);
+ return string.length + "." + string;
+ }
+
+ // Initialized message with first element
+ var message = getElement(arguments[0]);
+
+ // Append remaining elements
+ for (var i=1; i<arguments.length; i++)
+ message += "," + getElement(arguments[i]);
+
+ // Final terminator
+ message += ";";
+
+ socket.send(message);
+
+ };
+
+ this.connect = function(data) {
+
+ // Connect socket
+ socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
+
+ socket.onopen = function(event) {
+ currentState = STATE_CONNECTED;
+ };
+
+ socket.onclose = function(event) {
+
+ // If connection closed abnormally, signal error.
+ if (event.code != 1000 && tunnel.onerror)
+ tunnel.onerror(status_code[event.code]);
+
+ };
+
+ socket.onerror = function(event) {
+
+ // Call error handler
+ if (tunnel.onerror) tunnel.onerror(event.data);
+
+ };
+
+ socket.onmessage = function(event) {
+
+ var message = event.data;
+ var startIndex = 0;
+ var elementEnd;
+
+ var elements = [];
+
+ do {
+
+ // Search for end of length
+ var lengthEnd = message.indexOf(".", startIndex);
+ if (lengthEnd != -1) {
+
+ // Parse length
+ var length = parseInt(message.substring(elementEnd+1, lengthEnd));
+
+ // Calculate start of element
+ startIndex = lengthEnd + 1;
+
+ // Calculate location of element terminator
+ elementEnd = startIndex + length;
+
+ }
+
+ // If no period, incomplete instruction.
+ else
+ throw new Error("Incomplete instruction.");
+
+ // We now have enough data for the element. Parse.
+ var element = message.substring(startIndex, elementEnd);
+ var terminator = message.substring(elementEnd, elementEnd+1);
+
+ // Add element to array
+ elements.push(element);
+
+ // If last element, handle instruction
+ if (terminator == ";") {
+
+ // Get opcode
+ var opcode = elements.shift();
+
+ // Call instruction handler.
+ if (tunnel.oninstruction != null)
+ tunnel.oninstruction(opcode, elements);
+
+ // Clear elements
+ elements.length = 0;
+
+ }
+
+ // Start searching for length at character after
+ // element terminator
+ startIndex = elementEnd + 1;
+
+ } while (startIndex < message.length);
+
+ };
+
+ };
+
+ this.disconnect = function() {
+ currentState = STATE_DISCONNECTED;
+ socket.close();
+ };
+
+};
+
+Guacamole.WebSocketTunnel.prototype = new Guacamole.Tunnel();
+
+
+/**
+ * Guacamole Tunnel which cycles between all specified tunnels until
+ * no tunnels are left. Another tunnel is used if an error occurs but
+ * no instructions have been received. If an instruction has been
+ * received, or no tunnels remain, the error is passed directly out
+ * through the onerror handler (if defined).
+ *
+ * @constructor
+ * @augments Guacamole.Tunnel
+ * @param {...} tunnel_chain The tunnels to use, in order of priority.
+ */
+Guacamole.ChainedTunnel = function(tunnel_chain) {
+
+ /**
+ * Reference to this chained tunnel.
+ * @private
+ */
+ var chained_tunnel = this;
+
+ /**
+ * The currently wrapped tunnel, if any.
+ * @private
+ */
+ var current_tunnel = null;
+
+ /**
+ * Data passed in via connect(), to be used for
+ * wrapped calls to other tunnels' connect() functions.
+ * @private
+ */
+ var connect_data;
+
+ /**
+ * Array of all tunnels passed to this ChainedTunnel through the
+ * constructor arguments.
+ * @private
+ */
+ var tunnels = [];
+
+ // Load all tunnels into array
+ for (var i=0; i<arguments.length; i++)
+ tunnels.push(arguments[i]);
+
+ /**
+ * Sets the current tunnel.
+ *
+ * @private
+ * @param {Guacamole.Tunnel} tunnel The tunnel to set as the current tunnel.
+ */
+ function attach(tunnel) {
+
+ // Clear handlers of current tunnel, if any
+ if (current_tunnel) {
+ current_tunnel.onerror = null;
+ current_tunnel.oninstruction = null;
+ }
+
+ // Set own functions to tunnel's functions
+ chained_tunnel.disconnect = tunnel.disconnect;
+ chained_tunnel.sendMessage = tunnel.sendMessage;
+
+ // Record current tunnel
+ current_tunnel = tunnel;
+
+ // Wrap own oninstruction within current tunnel
+ current_tunnel.oninstruction = function(opcode, elements) {
+
+ // Invoke handler
+ chained_tunnel.oninstruction(opcode, elements);
+
+ // Use handler permanently from now on
+ current_tunnel.oninstruction = chained_tunnel.oninstruction;
+
+ // Pass through errors (without trying other tunnels)
+ current_tunnel.onerror = chained_tunnel.onerror;
+
+ }
+
+ // Attach next tunnel on error
+ current_tunnel.onerror = function(message) {
+
+ // Get next tunnel
+ var next_tunnel = tunnels.shift();
+
+ // If there IS a next tunnel, try using it.
+ if (next_tunnel)
+ attach(next_tunnel);
+
+ // Otherwise, call error handler
+ else if (chained_tunnel.onerror)
+ chained_tunnel.onerror(message);
+
+ };
+
+ try {
+
+ // Attempt connection
+ current_tunnel.connect(connect_data);
+
+ }
+ catch (e) {
+
+ // Call error handler of current tunnel on error
+ current_tunnel.onerror(e.message);
+
+ }
+
+
+ }
+
+ this.connect = function(data) {
+
+ // Remember connect data
+ connect_data = data;
+
+ // Get first tunnel
+ var next_tunnel = tunnels.shift();
+
+ // Attach first tunnel
+ if (next_tunnel)
+ attach(next_tunnel);
+
+ // If there IS no first tunnel, error
+ else if (chained_tunnel.onerror)
+ chained_tunnel.onerror("No tunnels to try.");
+
+ };
+
+};
+
+Guacamole.ChainedTunnel.prototype = new Guacamole.Tunnel();
diff --git a/guacamole-common-js/static.xml b/guacamole-common-js/static.xml
new file mode 100644
index 0000000..d3903dc
--- /dev/null
+++ b/guacamole-common-js/static.xml
@@ -0,0 +1,13 @@
+<assembly>
+ <baseDirectory>guacamole-common-js</baseDirectory>
+ <id>guacamole-common-js</id>
+ <formats>
+ <format>zip</format>
+ </formats>
+ <fileSets>
+ <fileSet>
+ <directory>src/main/resources</directory>
+ <outputDirectory></outputDirectory>
+ </fileSet>
+ </fileSets>
+</assembly>
diff --git a/guacamole-common/ChangeLog b/guacamole-common/ChangeLog
new file mode 100644
index 0000000..9ccf909
--- /dev/null
+++ b/guacamole-common/ChangeLog
@@ -0,0 +1,45 @@
+2012-10-24 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Implement audio/video/size preamble in handshake
+
+2012-10-16 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Ignore data after tunnel UUID (part of fix for ticket #201)
+
+2012-10-03 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix NPE in handshake if end-of-stream encountered (ticket #195)
+
+2012-08-09 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Improve documentation
+
+2012-07-24 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix Unicode bug
+
+2012-05-04 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Improved logging and exception handling
+ * Removed minor dependency on Apache Commons
+ * Improved API usability
+
+2011-12-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Implemented improved instruction format
+ * Fixed failed connections when using Konqueror
+ * Relicensed as Mozilla/LGPL/GPL
+
+2011-07-13 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fixed "no element found" errors
+ * Added timeouts
+ * Multiple tunnel support
+ * Better error handling
+ * Added JavaDoc
+ * Added logging
+
+2011-03-02 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Initial release
+
diff --git a/guacamole-common/LICENSE b/guacamole-common/LICENSE
new file mode 100644
index 0000000..7714141
--- /dev/null
+++ b/guacamole-common/LICENSE
@@ -0,0 +1,470 @@
+ MOZILLA PUBLIC LICENSE
+ Version 1.1
+
+ ---------------
+
+1. Definitions.
+
+ 1.0.1. "Commercial Use" means distribution or otherwise making the
+ Covered Code available to a third party.
+
+ 1.1. "Contributor" means each entity that creates or contributes to
+ the creation of Modifications.
+
+ 1.2. "Contributor Version" means the combination of the Original
+ Code, prior Modifications used by a Contributor, and the Modifications
+ made by that particular Contributor.
+
+ 1.3. "Covered Code" means the Original Code or Modifications or the
+ combination of the Original Code and Modifications, in each case
+ including portions thereof.
+
+ 1.4. "Electronic Distribution Mechanism" means a mechanism generally
+ accepted in the software development community for the electronic
+ transfer of data.
+
+ 1.5. "Executable" means Covered Code in any form other than Source
+ Code.
+
+ 1.6. "Initial Developer" means the individual or entity identified
+ as the Initial Developer in the Source Code notice required by Exhibit
+ A.
+
+ 1.7. "Larger Work" means a work which combines Covered Code or
+ portions thereof with code not governed by the terms of this License.
+
+ 1.8. "License" means this document.
+
+ 1.8.1. "Licensable" means having the right to grant, to the maximum
+ extent possible, whether at the time of the initial grant or
+ subsequently acquired, any and all of the rights conveyed herein.
+
+ 1.9. "Modifications" means any addition to or deletion from the
+ substance or structure of either the Original Code or any previous
+ Modifications. When Covered Code is released as a series of files, a
+ Modification is:
+ A. Any addition to or deletion from the contents of a file
+ containing Original Code or previous Modifications.
+
+ B. Any new file that contains any part of the Original Code or
+ previous Modifications.
+
+ 1.10. "Original Code" means Source Code of computer software code
+ which is described in the Source Code notice required by Exhibit A as
+ Original Code, and which, at the time of its release under this
+ License is not already Covered Code governed by this License.
+
+ 1.10.1. "Patent Claims" means any patent claim(s), now owned or
+ hereafter acquired, including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by grantor.
+
+ 1.11. "Source Code" means the preferred form of the Covered Code for
+ making modifications to it, including all modules it contains, plus
+ any associated interface definition files, scripts used to control
+ compilation and installation of an Executable, or source code
+ differential comparisons against either the Original Code or another
+ well known, available Covered Code of the Contributor's choice. The
+ Source Code can be in a compressed or archival form, provided the
+ appropriate decompression or de-archiving software is widely available
+ for no charge.
+
+ 1.12. "You" (or "Your") means an individual or a legal entity
+ exercising rights under, and complying with all of the terms of, this
+ License or a future version of this License issued under Section 6.1.
+ For legal entities, "You" includes any entity which controls, is
+ controlled by, or is under common control with You. For purposes of
+ this definition, "control" means (a) the power, direct or indirect,
+ to cause the direction or management of such entity, whether by
+ contract or otherwise, or (b) ownership of more than fifty percent
+ (50%) of the outstanding shares or beneficial ownership of such
+ entity.
+
+2. Source Code License.
+
+ 2.1. The Initial Developer Grant.
+ The Initial Developer hereby grants You a world-wide, royalty-free,
+ non-exclusive license, subject to third party intellectual property
+ claims:
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Initial Developer to use, reproduce,
+ modify, display, perform, sublicense and distribute the Original
+ Code (or portions thereof) with or without Modifications, and/or
+ as part of a Larger Work; and
+
+ (b) under Patents Claims infringed by the making, using or
+ selling of Original Code, to make, have made, use, practice,
+ sell, and offer for sale, and/or otherwise dispose of the
+ Original Code (or portions thereof).
+
+ (c) the licenses granted in this Section 2.1(a) and (b) are
+ effective on the date Initial Developer first distributes
+ Original Code under the terms of this License.
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is
+ granted: 1) for code that You delete from the Original Code; 2)
+ separate from the Original Code; or 3) for infringements caused
+ by: i) the modification of the Original Code or ii) the
+ combination of the Original Code with other software or devices.
+
+ 2.2. Contributor Grant.
+ Subject to third party intellectual property claims, each Contributor
+ hereby grants You a world-wide, royalty-free, non-exclusive license
+
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Contributor, to use, reproduce, modify,
+ display, perform, sublicense and distribute the Modifications
+ created by such Contributor (or portions thereof) either on an
+ unmodified basis, with other Modifications, as Covered Code
+ and/or as part of a Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using, or
+ selling of Modifications made by that Contributor either alone
+ and/or in combination with its Contributor Version (or portions
+ of such combination), to make, use, sell, offer for sale, have
+ made, and/or otherwise dispose of: 1) Modifications made by that
+ Contributor (or portions thereof); and 2) the combination of
+ Modifications made by that Contributor with its Contributor
+ Version (or portions of such combination).
+
+ (c) the licenses granted in Sections 2.2(a) and 2.2(b) are
+ effective on the date Contributor first makes Commercial Use of
+ the Covered Code.
+
+ (d) Notwithstanding Section 2.2(b) above, no patent license is
+ granted: 1) for any code that Contributor has deleted from the
+ Contributor Version; 2) separate from the Contributor Version;
+ 3) for infringements caused by: i) third party modifications of
+ Contributor Version or ii) the combination of Modifications made
+ by that Contributor with other software (except as part of the
+ Contributor Version) or other devices; or 4) under Patent Claims
+ infringed by Covered Code in the absence of Modifications made by
+ that Contributor.
+
+3. Distribution Obligations.
+
+ 3.1. Application of License.
+ The Modifications which You create or to which You contribute are
+ governed by the terms of this License, including without limitation
+ Section 2.2. The Source Code version of Covered Code may be
+ distributed only under the terms of this License or a future version
+ of this License released under Section 6.1, and You must include a
+ copy of this License with every copy of the Source Code You
+ distribute. You may not offer or impose any terms on any Source Code
+ version that alters or restricts the applicable version of this
+ License or the recipients' rights hereunder. However, You may include
+ an additional document offering the additional rights described in
+ Section 3.5.
+
+ 3.2. Availability of Source Code.
+ Any Modification which You create or to which You contribute must be
+ made available in Source Code form under the terms of this License
+ either on the same media as an Executable version or via an accepted
+ Electronic Distribution Mechanism to anyone to whom you made an
+ Executable version available; and if made available via Electronic
+ Distribution Mechanism, must remain available for at least twelve (12)
+ months after the date it initially became available, or at least six
+ (6) months after a subsequent version of that particular Modification
+ has been made available to such recipients. You are responsible for
+ ensuring that the Source Code version remains available even if the
+ Electronic Distribution Mechanism is maintained by a third party.
+
+ 3.3. Description of Modifications.
+ You must cause all Covered Code to which You contribute to contain a
+ file documenting the changes You made to create that Covered Code and
+ the date of any change. You must include a prominent statement that
+ the Modification is derived, directly or indirectly, from Original
+ Code provided by the Initial Developer and including the name of the
+ Initial Developer in (a) the Source Code, and (b) in any notice in an
+ Executable version or related documentation in which You describe the
+ origin or ownership of the Covered Code.
+
+ 3.4. Intellectual Property Matters
+ (a) Third Party Claims.
+ If Contributor has knowledge that a license under a third party's
+ intellectual property rights is required to exercise the rights
+ granted by such Contributor under Sections 2.1 or 2.2,
+ Contributor must include a text file with the Source Code
+ distribution titled "LEGAL" which describes the claim and the
+ party making the claim in sufficient detail that a recipient will
+ know whom to contact. If Contributor obtains such knowledge after
+ the Modification is made available as described in Section 3.2,
+ Contributor shall promptly modify the LEGAL file in all copies
+ Contributor makes available thereafter and shall take other steps
+ (such as notifying appropriate mailing lists or newsgroups)
+ reasonably calculated to inform those who received the Covered
+ Code that new knowledge has been obtained.
+
+ (b) Contributor APIs.
+ If Contributor's Modifications include an application programming
+ interface and Contributor has knowledge of patent licenses which
+ are reasonably necessary to implement that API, Contributor must
+ also include this information in the LEGAL file.
+
+ (c) Representations.
+ Contributor represents that, except as disclosed pursuant to
+ Section 3.4(a) above, Contributor believes that Contributor's
+ Modifications are Contributor's original creation(s) and/or
+ Contributor has sufficient rights to grant the rights conveyed by
+ this License.
+
+ 3.5. Required Notices.
+ You must duplicate the notice in Exhibit A in each file of the Source
+ Code. If it is not possible to put such notice in a particular Source
+ Code file due to its structure, then You must include such notice in a
+ location (such as a relevant directory) where a user would be likely
+ to look for such a notice. If You created one or more Modification(s)
+ You may add your name as a Contributor to the notice described in
+ Exhibit A. You must also duplicate this License in any documentation
+ for the Source Code where You describe recipients' rights or ownership
+ rights relating to Covered Code. You may choose to offer, and to
+ charge a fee for, warranty, support, indemnity or liability
+ obligations to one or more recipients of Covered Code. However, You
+ may do so only on Your own behalf, and not on behalf of the Initial
+ Developer or any Contributor. You must make it absolutely clear than
+ any such warranty, support, indemnity or liability obligation is
+ offered by You alone, and You hereby agree to indemnify the Initial
+ Developer and every Contributor for any liability incurred by the
+ Initial Developer or such Contributor as a result of warranty,
+ support, indemnity or liability terms You offer.
+
+ 3.6. Distribution of Executable Versions.
+ You may distribute Covered Code in Executable form only if the
+ requirements of Section 3.1-3.5 have been met for that Covered Code,
+ and if You include a notice stating that the Source Code version of
+ the Covered Code is available under the terms of this License,
+ including a description of how and where You have fulfilled the
+ obligations of Section 3.2. The notice must be conspicuously included
+ in any notice in an Executable version, related documentation or
+ collateral in which You describe recipients' rights relating to the
+ Covered Code. You may distribute the Executable version of Covered
+ Code or ownership rights under a license of Your choice, which may
+ contain terms different from this License, provided that You are in
+ compliance with the terms of this License and that the license for the
+ Executable version does not attempt to limit or alter the recipient's
+ rights in the Source Code version from the rights set forth in this
+ License. If You distribute the Executable version under a different
+ license You must make it absolutely clear that any terms which differ
+ from this License are offered by You alone, not by the Initial
+ Developer or any Contributor. You hereby agree to indemnify the
+ Initial Developer and every Contributor for any liability incurred by
+ the Initial Developer or such Contributor as a result of any such
+ terms You offer.
+
+ 3.7. Larger Works.
+ You may create a Larger Work by combining Covered Code with other code
+ not governed by the terms of this License and distribute the Larger
+ Work as a single product. In such a case, You must make sure the
+ requirements of this License are fulfilled for the Covered Code.
+
+4. Inability to Comply Due to Statute or Regulation.
+
+ If it is impossible for You to comply with any of the terms of this
+ License with respect to some or all of the Covered Code due to
+ statute, judicial order, or regulation then You must: (a) comply with
+ the terms of this License to the maximum extent possible; and (b)
+ describe the limitations and the code they affect. Such description
+ must be included in the LEGAL file described in Section 3.4 and must
+ be included with all distributions of the Source Code. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Application of this License.
+
+ This License applies to code to which the Initial Developer has
+ attached the notice in Exhibit A and to related Covered Code.
+
+6. Versions of the License.
+
+ 6.1. New Versions.
+ Netscape Communications Corporation ("Netscape") may publish revised
+ and/or new versions of the License from time to time. Each version
+ will be given a distinguishing version number.
+
+ 6.2. Effect of New Versions.
+ Once Covered Code has been published under a particular version of the
+ License, You may always continue to use it under the terms of that
+ version. You may also choose to use such Covered Code under the terms
+ of any subsequent version of the License published by Netscape. No one
+ other than Netscape has the right to modify the terms applicable to
+ Covered Code created under this License.
+
+ 6.3. Derivative Works.
+ If You create or use a modified version of this License (which you may
+ only do in order to apply it to code which is not already Covered Code
+ governed by this License), You must (a) rename Your license so that
+ the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
+ "MPL", "NPL" or any confusingly similar phrase do not appear in your
+ license (except to note that your license differs from this License)
+ and (b) otherwise make it clear that Your version of the license
+ contains terms which differ from the Mozilla Public License and
+ Netscape Public License. (Filling in the name of the Initial
+ Developer, Original Code or Contributor in the notice described in
+ Exhibit A shall not of themselves be deemed to be modifications of
+ this License.)
+
+7. DISCLAIMER OF WARRANTY.
+
+ COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+ WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
+ DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
+ THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
+ IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
+ YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
+ COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
+ OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
+ ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+8. TERMINATION.
+
+ 8.1. This License and the rights granted hereunder will terminate
+ automatically if You fail to comply with terms herein and fail to cure
+ such breach within 30 days of becoming aware of the breach. All
+ sublicenses to the Covered Code which are properly granted shall
+ survive any termination of this License. Provisions which, by their
+ nature, must remain in effect beyond the termination of this License
+ shall survive.
+
+ 8.2. If You initiate litigation by asserting a patent infringement
+ claim (excluding declatory judgment actions) against Initial Developer
+ or a Contributor (the Initial Developer or Contributor against whom
+ You file such action is referred to as "Participant") alleging that:
+
+ (a) such Participant's Contributor Version directly or indirectly
+ infringes any patent, then any and all rights granted by such
+ Participant to You under Sections 2.1 and/or 2.2 of this License
+ shall, upon 60 days notice from Participant terminate prospectively,
+ unless if within 60 days after receipt of notice You either: (i)
+ agree in writing to pay Participant a mutually agreeable reasonable
+ royalty for Your past and future use of Modifications made by such
+ Participant, or (ii) withdraw Your litigation claim with respect to
+ the Contributor Version against such Participant. If within 60 days
+ of notice, a reasonable royalty and payment arrangement are not
+ mutually agreed upon in writing by the parties or the litigation claim
+ is not withdrawn, the rights granted by Participant to You under
+ Sections 2.1 and/or 2.2 automatically terminate at the expiration of
+ the 60 day notice period specified above.
+
+ (b) any software, hardware, or device, other than such Participant's
+ Contributor Version, directly or indirectly infringes any patent, then
+ any rights granted to You by such Participant under Sections 2.1(b)
+ and 2.2(b) are revoked effective as of the date You first made, used,
+ sold, distributed, or had made, Modifications made by that
+ Participant.
+
+ 8.3. If You assert a patent infringement claim against Participant
+ alleging that such Participant's Contributor Version directly or
+ indirectly infringes any patent where such claim is resolved (such as
+ by license or settlement) prior to the initiation of patent
+ infringement litigation, then the reasonable value of the licenses
+ granted by such Participant under Sections 2.1 or 2.2 shall be taken
+ into account in determining the amount or value of any payment or
+ license.
+
+ 8.4. In the event of termination under Sections 8.1 or 8.2 above,
+ all end user license agreements (excluding distributors and resellers)
+ which have been validly granted by You or any distributor hereunder
+ prior to termination shall survive termination.
+
+9. LIMITATION OF LIABILITY.
+
+ UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
+ (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
+ DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
+ OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
+ ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
+ CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
+ WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
+ COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
+ INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
+ LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
+ RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
+ PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
+ EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
+ THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+10. U.S. GOVERNMENT END USERS.
+
+ The Covered Code is a "commercial item," as that term is defined in
+ 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
+ software" and "commercial computer software documentation," as such
+ terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
+ C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
+ all U.S. Government End Users acquire Covered Code with only those
+ rights set forth herein.
+
+11. MISCELLANEOUS.
+
+ This License represents the complete agreement concerning subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. This License shall be governed by
+ California law provisions (except to the extent applicable law, if
+ any, provides otherwise), excluding its conflict-of-law provisions.
+ With respect to disputes in which at least one party is a citizen of,
+ or an entity chartered or registered to do business in the United
+ States of America, any litigation relating to this License shall be
+ subject to the jurisdiction of the Federal Courts of the Northern
+ District of California, with venue lying in Santa Clara County,
+ California, with the losing party responsible for costs, including
+ without limitation, court costs and reasonable attorneys' fees and
+ expenses. The application of the United Nations Convention on
+ Contracts for the International Sale of Goods is expressly excluded.
+ Any law or regulation which provides that the language of a contract
+ shall be construed against the drafter shall not apply to this
+ License.
+
+12. RESPONSIBILITY FOR CLAIMS.
+
+ As between Initial Developer and the Contributors, each party is
+ responsible for claims and damages arising, directly or indirectly,
+ out of its utilization of rights under this License and You agree to
+ work with Initial Developer and Contributors to distribute such
+ responsibility on an equitable basis. Nothing herein is intended or
+ shall be deemed to constitute any admission of liability.
+
+13. MULTIPLE-LICENSED CODE.
+
+ Initial Developer may designate portions of the Covered Code as
+ "Multiple-Licensed". "Multiple-Licensed" means that the Initial
+ Developer permits you to utilize portions of the Covered Code under
+ Your choice of the NPL or the alternative licenses, if any, specified
+ by the Initial Developer in the file described in Exhibit A.
+
+EXHIBIT A -Mozilla Public License.
+
+ ``The contents of this file are subject to the Mozilla Public License
+ Version 1.1 (the "License"); you may not use this file except in
+ compliance with the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS"
+ basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ License for the specific language governing rights and limitations
+ under the License.
+
+ The Original Code is ______________________________________.
+
+ The Initial Developer of the Original Code is ________________________.
+ Portions created by ______________________ are Copyright (C) ______
+ _______________________. All Rights Reserved.
+
+ Contributor(s): ______________________________________.
+
+ Alternatively, the contents of this file may be used under the terms
+ of the _____ license (the "[___] License"), in which case the
+ provisions of [______] License are applicable instead of those
+ above. If you wish to allow use of your version of this file only
+ under the terms of the [____] License and not to allow others to use
+ your version of this file under the MPL, indicate your decision by
+ deleting the provisions above and replace them with the notice and
+ other provisions required by the [___] License. If you do not delete
+ the provisions above, a recipient may use your version of this file
+ under either the MPL or the [___] License."
+
+ [NOTE: The text of this Exhibit A may differ slightly from the text of
+ the notices in the Source Code files of the Original Code. You should
+ use the text of this Exhibit A rather than the text found in the
+ Original Code Source Code for Your Modifications.]
+
diff --git a/guacamole-common/README b/guacamole-common/README
new file mode 100644
index 0000000..68bf723
--- /dev/null
+++ b/guacamole-common/README
@@ -0,0 +1,76 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-common?
+------------------------------------------------------------
+
+guacamole-common is the core Java library used by the Guacamole web
+application.
+
+guacamole-common provides abstract means of connecting to guacd, interfacing
+with the JavaScript client and tunnel provided by guacamole-common-js, and
+reading configuration from a standard location (guacamole.properties).
+
+
+------------------------------------------------------------
+ Compiling and installing guacamole-common
+------------------------------------------------------------
+
+guacamole-common is built using Maven. Building guacamole-common
+compiles all classes and packages them into a redistributable .jar file. This
+.jar file can be easily included in other Maven-based projects (like Guacamole).
+
+Note that prebuilt versions of guacamole-common are available from the
+main guac-dev.org Maven repository which is referenced in all Maven
+projects in Guacamole. Unless you want to make changes to guacamole-common
+or you want to use a newer, unreleased version (such as the unstable branch),
+you do not need to build this manually. You can let Maven download it for
+you when you build Guacamole.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .jar file will be
+ created in the target/ subdirectory of the current directory.
+
+2) Run mvn install
+
+ $ mvn install
+
+ DO NOT RUN THIS AS ROOT!
+
+ Maven will install guacamole-common to your user's local Maven
+ repository where it can be used in future builds. It will not install
+ into a system-wide repository and does not require root privileges.
+
+ Once installed, building other Maven projects that depend on
+ guacamole-common (such as Guacamole) will be possible.
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/guacamole-common/doc/Doxyfile b/guacamole-common/doc/Doxyfile
new file mode 100644
index 0000000..8319dd9
--- /dev/null
+++ b/guacamole-common/doc/Doxyfile
@@ -0,0 +1,1551 @@
+# Doxyfile 1.6.3
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME = guacamole-common
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER = 0.5.0
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY = doxygen-output
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH = ../src
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA = YES
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it parses.
+# With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this tag.
+# The format is ext=language, where ext is a file extension, and language is one of
+# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
+# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
+# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
+# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT = NO
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT = YES
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penality.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will rougly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES = YES
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or define consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and defines in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES = YES
+
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
+# doxygen. The layout file controls the global structure of the generated output files
+# in an output format independent way. The create the layout file that represents
+# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
+# file name after the option, if omitted DoxygenLayout.xml will be used as the name
+# of the layout file.
+
+LAYOUT_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = ../src
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+FILE_PATTERNS =
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+
+EXCLUDE =
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH = example
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE = YES
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX = NO
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header.
+
+HTML_HEADER =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET =
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP = YES
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
+# files or namespaces will be aligned in HTML using tables. If set to
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
+
+GENERATE_DOCSET = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
+# are set, an additional index file will be generated that can be used as input for
+# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
+# HTML documentation.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
+# For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears.
+
+GENERATE_ECLIPSEHELP = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
+# top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it.
+
+DISABLE_INDEX = NO
+
+# This tag can be used to set the number of enum values (range [1..20])
+# that doxygen will group on one line in the generated HTML documentation.
+
+ENUM_VALUES_PER_LINE = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW = NO
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH = 250
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE = 10
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = YES
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT = NO
+
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME = FreeSans
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK = NO
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are png, jpg, or gif
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT = png
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS = YES
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP = YES
diff --git a/guacamole-common/doc/example/ExampleTunnelServlet.java b/guacamole-common/doc/example/ExampleTunnelServlet.java
new file mode 100644
index 0000000..00f4098
--- /dev/null
+++ b/guacamole-common/doc/example/ExampleTunnelServlet.java
@@ -0,0 +1,49 @@
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import net.sourceforge.guacamole.GuacamoleException;
+import net.sourceforge.guacamole.properties.GuacamoleProperties;
+import net.sourceforge.guacamole.net.GuacamoleSocket;
+import net.sourceforge.guacamole.net.GuacamoleTunnel;
+import net.sourceforge.guacamole.net.InetGuacamoleSocket;
+import net.sourceforge.guacamole.protocol.GuacamoleConfiguration;
+import net.sourceforge.guacamole.protocol.ConfiguredGuacamoleSocket;
+import net.sourceforge.guacamole.servlet.GuacamoleSession;
+import net.sourceforge.guacamole.servlet.GuacamoleHTTPTunnelServlet;
+
+public class ExampleTunnelServlet extends GuacamoleHTTPTunnelServlet {
+
+ @Override
+ protected GuacamoleTunnel doConnect(HttpServletRequest request)
+ throws GuacamoleException {
+
+ HttpSession httpSession = request.getSession(true);
+
+ String hostname = GuacamoleProperties.getProperty(
+ GuacamoleProperties.GUACD_HOSTNAME);
+
+ int port = GuacamoleProperties.getProperty(
+ GuacamoleProperties.GUACD_PORT);
+
+ GuacamoleConfiguration config = new GuacamoleConfiguration();
+ config.setProtocol("vnc");
+ config.setParameter("hostname", "localhost");
+ config.setParameter("port", "5901");
+ config.setParameter("password", "potato");
+
+ GuacamoleSocket socket = new ConfiguredGuacamoleSocket(
+ new InetGuacamoleSocket(hostname, port),
+ config
+ );
+
+ GuacamoleTunnel tunnel = new GuacamoleTunnel(socket);
+
+ // Attach tunnel
+ GuacamoleSession session = new GuacamoleSession(httpSession);
+ session.attachTunnel(tunnel);
+
+ return tunnel;
+
+ }
+
+}
diff --git a/guacamole-common/pom.xml b/guacamole-common/pom.xml
new file mode 100644
index 0000000..a5b6223
--- /dev/null
+++ b/guacamole-common/pom.xml
@@ -0,0 +1,126 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <packaging>jar</packaging>
+ <version>0.8.0</version>
+ <name>guacamole-common</name>
+ <url>http://guac-dev.org/</url>
+
+ <description>
+ The base Java API of the Guacamole project, providing Java support for
+ the Guacamole stack.
+ </description>
+
+ <!-- All applicable licenses -->
+ <licenses>
+ <license>
+ <name>Mozilla Public License Version 1.1</name>
+ <url>http://www.mozilla.org/MPL/1.1/</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>GNU General Public License, version 2</name>
+ <url>http://www.gnu.org/licenses/gpl-2.0.html</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>GNU Lesser General Public License, version 2.1</name>
+ <url>http://www.gnu.org/licenses/lgpl-2.1.html</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <!-- Git repository -->
+ <scm>
+ <url>https://github.com/glyptodon/guacamole-client</url>
+ <connection>scm:git:git://github.com/glyptodon/guacamole-client.git</connection>
+ </scm>
+
+ <!-- Developers -->
+ <developers>
+ <developer>
+ <id>mike.jumper</id>
+ <name>Michael Jumper</name>
+ <email>mike.jumper at guac-dev.org</email>
+ </developer>
+ <developer>
+ <id>james.muehlner</id>
+ <name>James Muehlner</name>
+ <email>james.muehlner at guac-dev.org</email>
+ </developer>
+ </developers>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Written for 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <!-- Attach source jar -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <!-- Attach JavaDoc jar -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <detectOfflineLinks>false</detectOfflineLinks>
+ </configuration>
+ <executions>
+ <execution>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <!-- Java servlet API -->
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- SLF4J - logging -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.6.1</version>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleClientException.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleClientException.java
new file mode 100644
index 0000000..bf98aa3
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleClientException.java
@@ -0,0 +1,79 @@
+
+package org.glyptodon.guacamole;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A generic exception thrown when part of the Guacamole API encounters
+ * an error in the client's request. Such an error, if correctable, usually
+ * requires correction on the client side, not the server.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleClientException extends GuacamoleException {
+
+ /**
+ * Creates a new GuacamoleException with the given message and cause.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleClientException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new GuacamoleException with the given message.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ */
+ public GuacamoleClientException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new GuacamoleException with the given cause.
+ *
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleClientException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleException.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleException.java
new file mode 100644
index 0000000..a2eb28a
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleException.java
@@ -0,0 +1,78 @@
+
+package org.glyptodon.guacamole;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A generic exception thrown when parts of the Guacamole API encounter
+ * errors.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleException extends Exception {
+
+ /**
+ * Creates a new GuacamoleException with the given message and cause.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new GuacamoleException with the given message.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ */
+ public GuacamoleException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new GuacamoleException with the given cause.
+ *
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleResourceNotFoundException.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleResourceNotFoundException.java
new file mode 100644
index 0000000..cb90a41
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleResourceNotFoundException.java
@@ -0,0 +1,79 @@
+
+package org.glyptodon.guacamole;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A generic exception thrown when part of the Guacamole API fails to find
+ * a requested resource, such as a configuration or tunnel.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleResourceNotFoundException extends GuacamoleClientException {
+
+ /**
+ * Creates a new GuacamoleResourceNotFoundException with the given message
+ * and cause.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleResourceNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new GuacamoleResourceNotFoundException with the given message.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ */
+ public GuacamoleResourceNotFoundException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new GuacamoleResourceNotFoundException with the given cause.
+ *
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleResourceNotFoundException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleSecurityException.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleSecurityException.java
new file mode 100644
index 0000000..e40bcff
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleSecurityException.java
@@ -0,0 +1,78 @@
+
+package org.glyptodon.guacamole;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A security-related exception thrown when parts of the Guacamole API is
+ * denying access to a resource.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleSecurityException extends GuacamoleClientException {
+
+ /**
+ * Creates a new GuacamoleSecurityException with the given message and cause.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleSecurityException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new GuacamoleSecurityException with the given message.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ */
+ public GuacamoleSecurityException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new GuacamoleSecurityException with the given cause.
+ *
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleSecurityException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleServerException.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleServerException.java
new file mode 100644
index 0000000..24057ba
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/GuacamoleServerException.java
@@ -0,0 +1,79 @@
+
+package org.glyptodon.guacamole;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A generic exception thrown when part of the Guacamole API encounters
+ * an unexpected, internal error. An internal error, if correctable, would
+ * require correction on the server side, not the client.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleServerException extends GuacamoleException {
+
+ /**
+ * Creates a new GuacamoleException with the given message and cause.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleServerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new GuacamoleException with the given message.
+ *
+ * @param message A human readable description of the exception that
+ * occurred.
+ */
+ public GuacamoleServerException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new GuacamoleException with the given cause.
+ *
+ * @param cause The cause of this exception.
+ */
+ public GuacamoleServerException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/io/GuacamoleReader.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/GuacamoleReader.java
new file mode 100644
index 0000000..23fca3d
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/GuacamoleReader.java
@@ -0,0 +1,89 @@
+
+package org.glyptodon.guacamole.io;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.protocol.GuacamoleInstruction;
+
+/**
+ * Provides abstract and raw character read access to a stream of Guacamole
+ * instructions.
+ *
+ * @author Michael Jumper
+ */
+public interface GuacamoleReader {
+
+ /**
+ * Returns whether instruction data is available for reading. Note that
+ * this does not guarantee an entire instruction is available. If a full
+ * instruction is not available, this function can return true, and a call
+ * to read() will still block.
+ *
+ * @return true if instruction data is available for reading, false
+ * otherwise.
+ * @throws GuacamoleException If an error occurs while checking for
+ * available data.
+ */
+ public boolean available() throws GuacamoleException;
+
+ /**
+ * Reads at least one complete Guacamole instruction, returning a buffer
+ * containing one or more complete Guacamole instructions and no
+ * incomplete Guacamole instructions. This function will block until at
+ * least one complete instruction is available.
+ *
+ * @return A buffer containing at least one complete Guacamole instruction,
+ * or null if no more instructions are available for reading.
+ * @throws GuacamoleException If an error occurs while reading from the
+ * stream.
+ */
+ public char[] read() throws GuacamoleException;
+
+ /**
+ * Reads exactly one complete Guacamole instruction and returns the fully
+ * parsed instruction.
+ *
+ * @return The next complete instruction from the stream, fully parsed, or
+ * null if no more instructions are available for reading.
+ * @throws GuacamoleException If an error occurs while reading from the
+ * stream, or if the instruction cannot be
+ * parsed.
+ */
+ public GuacamoleInstruction readInstruction() throws GuacamoleException;
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/io/GuacamoleWriter.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/GuacamoleWriter.java
new file mode 100644
index 0000000..ad80296
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/GuacamoleWriter.java
@@ -0,0 +1,85 @@
+
+package org.glyptodon.guacamole.io;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.protocol.GuacamoleInstruction;
+
+/**
+ * Provides abstract and raw character write access to a stream of Guacamole
+ * instructions.
+ *
+ * @author Michael Jumper
+ */
+public interface GuacamoleWriter {
+
+ /**
+ * Writes a portion of the given array of characters to the Guacamole
+ * instruction stream. The portion must contain only complete Guacamole
+ * instructions.
+ *
+ * @param chunk An array of characters containing Guacamole instructions.
+ * @param off The start offset of the portion of the array to write.
+ * @param len The length of the portion of the array to write.
+ * @throws GuacamoleException If an error occurred while writing the
+ * portion of the array specified.
+ */
+ public void write(char[] chunk, int off, int len) throws GuacamoleException;
+
+ /**
+ * Writes the entire given array of characters to the Guacamole instruction
+ * stream. The array must consist only of complete Guacamole instructions.
+ *
+ * @param chunk An array of characters consisting only of complete
+ * Guacamole instructions.
+ * @throws GuacamoleException If an error occurred while writing the
+ * the specified array.
+ */
+ public void write(char[] chunk) throws GuacamoleException;
+
+ /**
+ * Writes the given fully parsed instruction to the Guacamole instruction
+ * stream.
+ *
+ * @param instruction The Guacamole instruction to write.
+ * @throws GuacamoleException If an error occurred while writing the
+ * instruction.
+ */
+ public void writeInstruction(GuacamoleInstruction instruction) throws GuacamoleException;
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/io/ReaderGuacamoleReader.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/ReaderGuacamoleReader.java
new file mode 100644
index 0000000..d525f68
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/ReaderGuacamoleReader.java
@@ -0,0 +1,276 @@
+
+package org.glyptodon.guacamole.io;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.IOException;
+import java.io.Reader;
+import java.util.Deque;
+import java.util.LinkedList;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.protocol.GuacamoleInstruction;
+
+/**
+ * A GuacamoleReader which wraps a standard Java Reader, using that Reader as
+ * the Guacamole instruction stream.
+ *
+ * @author Michael Jumper
+ */
+public class ReaderGuacamoleReader implements GuacamoleReader {
+
+ /**
+ * Wrapped Reader to be used for all input.
+ */
+ private Reader input;
+
+ /**
+ * Creates a new ReaderGuacamoleReader which will use the given Reader as
+ * the Guacamole instruction stream.
+ *
+ * @param input The Reader to use as the Guacamole instruction stream.
+ */
+ public ReaderGuacamoleReader(Reader input) {
+ this.input = input;
+ }
+
+ /**
+ * The location within the received data buffer that parsing should begin
+ * when more data is read.
+ */
+ private int parseStart;
+
+ /**
+ * The buffer holding all received, unparsed data.
+ */
+ private char[] buffer = new char[20480];
+
+ /**
+ * The number of characters currently used within the data buffer. All
+ * other characters within the buffer are free space available for
+ * future reads.
+ */
+ private int usedLength = 0;
+
+ @Override
+ public boolean available() throws GuacamoleException {
+ try {
+ return input.ready() || usedLength != 0;
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+ }
+
+ @Override
+ public char[] read() throws GuacamoleException {
+
+ try {
+
+ // While we're blocking, or input is available
+ for (;;) {
+
+ // Length of element
+ int elementLength = 0;
+
+ // Resume where we left off
+ int i = parseStart;
+
+ // Parse instruction in buffer
+ while (i < usedLength) {
+
+ // Read character
+ char readChar = buffer[i++];
+
+ // If digit, update length
+ if (readChar >= '0' && readChar <= '9')
+ elementLength = elementLength * 10 + readChar - '0';
+
+ // If not digit, check for end-of-length character
+ else if (readChar == '.') {
+
+ // Check if element present in buffer
+ if (i + elementLength < usedLength) {
+
+ // Get terminator
+ char terminator = buffer[i + elementLength];
+
+ // Move to character after terminator
+ i += elementLength + 1;
+
+ // Reset length
+ elementLength = 0;
+
+ // Continue here if necessary
+ parseStart = i;
+
+ // If terminator is semicolon, we have a full
+ // instruction.
+ if (terminator == ';') {
+
+ // Copy instruction data
+ char[] instruction = new char[i];
+ System.arraycopy(buffer, 0, instruction, 0, i);
+
+ // Update buffer
+ usedLength -= i;
+ parseStart = 0;
+ System.arraycopy(buffer, i, buffer, 0, usedLength);
+
+ return instruction;
+
+ }
+
+ // Handle invalid terminator characters
+ else if (terminator != ',')
+ throw new GuacamoleServerException("Element terminator of instruction was not ';' nor ','");
+
+ }
+
+ // Otherwise, read more data
+ else
+ break;
+
+ }
+
+ // Otherwise, parse error
+ else
+ throw new GuacamoleServerException("Non-numeric character in element length.");
+
+ }
+
+ // If past threshold, resize buffer before reading
+ if (usedLength > buffer.length/2) {
+ char[] biggerBuffer = new char[buffer.length*2];
+ System.arraycopy(buffer, 0, biggerBuffer, 0, usedLength);
+ buffer = biggerBuffer;
+ }
+
+ // Attempt to fill buffer
+ int numRead = input.read(buffer, usedLength, buffer.length - usedLength);
+ if (numRead == -1)
+ return null;
+
+ // Update used length
+ usedLength += numRead;
+
+ } // End read loop
+
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+
+ }
+
+ @Override
+ public GuacamoleInstruction readInstruction() throws GuacamoleException {
+
+ // Get instruction
+ char[] instructionBuffer = read();
+
+ // If EOF, return EOF
+ if (instructionBuffer == null)
+ return null;
+
+ // Start of element
+ int elementStart = 0;
+
+ // Build list of elements
+ Deque<String> elements = new LinkedList<String>();
+ while (elementStart < instructionBuffer.length) {
+
+ // Find end of length
+ int lengthEnd = -1;
+ for (int i=elementStart; i<instructionBuffer.length; i++) {
+ if (instructionBuffer[i] == '.') {
+ lengthEnd = i;
+ break;
+ }
+ }
+
+ // read() is required to return a complete instruction. If it does
+ // not, this is a severe internal error.
+ if (lengthEnd == -1)
+ throw new GuacamoleServerException("Read returned incomplete instruction.");
+
+ // Parse length
+ int length = Integer.parseInt(new String(
+ instructionBuffer,
+ elementStart,
+ lengthEnd - elementStart
+ ));
+
+ // Parse element from just after period
+ elementStart = lengthEnd + 1;
+ String element = new String(
+ instructionBuffer,
+ elementStart,
+ length
+ );
+
+ // Append element to list of elements
+ elements.addLast(element);
+
+ // Read terminator after element
+ elementStart += length;
+ char terminator = instructionBuffer[elementStart];
+
+ // Continue reading instructions after terminator
+ elementStart++;
+
+ // If we've reached the end of the instruction
+ if (terminator == ';')
+ break;
+
+ }
+
+ // Pull opcode off elements list
+ String opcode = elements.removeFirst();
+
+ // Create instruction
+ GuacamoleInstruction instruction = new GuacamoleInstruction(
+ opcode,
+ elements.toArray(new String[elements.size()])
+ );
+
+ // Return parsed instruction
+ return instruction;
+
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/io/WriterGuacamoleWriter.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/WriterGuacamoleWriter.java
new file mode 100644
index 0000000..169159a
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/WriterGuacamoleWriter.java
@@ -0,0 +1,90 @@
+
+package org.glyptodon.guacamole.io;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.IOException;
+import java.io.Writer;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.protocol.GuacamoleInstruction;
+
+/**
+ * A GuacamoleWriter which wraps a standard Java Writer, using that Writer as
+ * the Guacamole instruction stream.
+ *
+ * @author Michael Jumper
+ */
+public class WriterGuacamoleWriter implements GuacamoleWriter {
+
+ /**
+ * Wrapped Writer to be used for all output.
+ */
+ private Writer output;
+
+ /**
+ * Creates a new WriterGuacamoleWriter which will use the given Writer as
+ * the Guacamole instruction stream.
+ *
+ * @param output The Writer to use as the Guacamole instruction stream.
+ */
+ public WriterGuacamoleWriter(Writer output) {
+ this.output = output;
+ }
+
+ @Override
+ public void write(char[] chunk, int off, int len) throws GuacamoleException {
+ try {
+ output.write(chunk, off, len);
+ output.flush();
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+ }
+
+ @Override
+ public void write(char[] chunk) throws GuacamoleException {
+ write(chunk, 0, chunk.length);
+ }
+
+ @Override
+ public void writeInstruction(GuacamoleInstruction instruction) throws GuacamoleException {
+ write(instruction.toString().toCharArray());
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/io/package-info.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/package-info.java
new file mode 100644
index 0000000..531531a
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/io/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * All classes relating directly to data input or output.
+ */
+package org.glyptodon.guacamole.io;
+
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/net/GuacamoleSocket.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/GuacamoleSocket.java
new file mode 100644
index 0000000..0d4d389
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/GuacamoleSocket.java
@@ -0,0 +1,87 @@
+
+package org.glyptodon.guacamole.net;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+
+/**
+ * Provides abstract socket-like access to a Guacamole connection.
+ *
+ * @author Michael Jumper
+ */
+public interface GuacamoleSocket {
+
+ /**
+ * Returns a GuacamoleReader which can be used to read from the
+ * Guacamole instruction stream associated with the connection
+ * represented by this GuacamoleSocket.
+ *
+ * @return A GuacamoleReader which can be used to read from the
+ * Guacamole instruction stream.
+ */
+ public GuacamoleReader getReader();
+
+ /**
+ * Returns a GuacamoleWriter which can be used to write to the
+ * Guacamole instruction stream associated with the connection
+ * represented by this GuacamoleSocket.
+ *
+ * @return A GuacamoleWriter which can be used to write to the
+ * Guacamole instruction stream.
+ */
+ public GuacamoleWriter getWriter();
+
+ /**
+ * Releases all resources in use by the connection represented by this
+ * GuacamoleSocket.
+ *
+ * @throws GuacamoleException If an error occurs while releasing resources.
+ */
+ public void close() throws GuacamoleException;
+
+ /**
+ * Returns whether this GuacamoleSocket is open and can be used for reading
+ * and writing.
+ *
+ * @return true if this GuacamoleSocket is open, false otherwise.
+ */
+ public boolean isOpen();
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/net/GuacamoleTunnel.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/GuacamoleTunnel.java
new file mode 100644
index 0000000..d2e3c38
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/GuacamoleTunnel.java
@@ -0,0 +1,195 @@
+
+package org.glyptodon.guacamole.net;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.UUID;
+import java.util.concurrent.locks.ReentrantLock;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+
+/**
+ * Provides a unique identifier and synchronized access to the GuacamoleReader
+ * and GuacamoleWriter associated with a GuacamoleSocket.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleTunnel {
+
+ /**
+ * The UUID associated with this tunnel. Every tunnel must have a
+ * corresponding UUID such that tunnel read/write requests can be
+ * directed to the proper tunnel.
+ */
+ private UUID uuid;
+
+ /**
+ * The GuacamoleSocket that tunnel should use for communication on
+ * behalf of the connecting user.
+ */
+ private GuacamoleSocket socket;
+
+ /**
+ * Lock acquired when a read operation is in progress.
+ */
+ private ReentrantLock readerLock;
+
+ /**
+ * Lock acquired when a write operation is in progress.
+ */
+ private ReentrantLock writerLock;
+
+ /**
+ * Creates a new GuacamoleTunnel which synchronizes access to the
+ * Guacamole instruction stream associated with the given GuacamoleSocket.
+ *
+ * @param socket The GuacamoleSocket to provide synchronized access for.
+ */
+ public GuacamoleTunnel(GuacamoleSocket socket) {
+
+ this.socket = socket;
+ uuid = UUID.randomUUID();
+
+ readerLock = new ReentrantLock();
+ writerLock = new ReentrantLock();
+
+ }
+
+ /**
+ * Acquires exclusive read access to the Guacamole instruction stream
+ * and returns a GuacamoleReader for reading from that stream.
+ *
+ * @return A GuacamoleReader for reading from the Guacamole instruction
+ * stream.
+ */
+ public GuacamoleReader acquireReader() {
+ readerLock.lock();
+ return socket.getReader();
+ }
+
+ /**
+ * Relinquishes exclusive read access to the Guacamole instruction
+ * stream. This function should be called whenever a thread finishes using
+ * a GuacamoleTunnel's GuacamoleReader.
+ */
+ public void releaseReader() {
+ readerLock.unlock();
+ }
+
+ /**
+ * Returns whether there are threads waiting for read access to the
+ * Guacamole instruction stream.
+ *
+ * @return true if threads are waiting for read access the Guacamole
+ * instruction stream, false otherwise.
+ */
+ public boolean hasQueuedReaderThreads() {
+ return readerLock.hasQueuedThreads();
+ }
+
+ /**
+ * Acquires exclusive write access to the Guacamole instruction stream
+ * and returns a GuacamoleWriter for writing to that stream.
+ *
+ * @return A GuacamoleWriter for writing to the Guacamole instruction
+ * stream.
+ */
+ public GuacamoleWriter acquireWriter() {
+ writerLock.lock();
+ return socket.getWriter();
+ }
+
+ /**
+ * Relinquishes exclusive write access to the Guacamole instruction
+ * stream. This function should be called whenever a thread finishes using
+ * a GuacamoleTunnel's GuacamoleWriter.
+ */
+ public void releaseWriter() {
+ writerLock.unlock();
+ }
+
+ /**
+ * Returns whether there are threads waiting for write access to the
+ * Guacamole instruction stream.
+ *
+ * @return true if threads are waiting for write access the Guacamole
+ * instruction stream, false otherwise.
+ */
+ public boolean hasQueuedWriterThreads() {
+ return writerLock.hasQueuedThreads();
+ }
+
+ /**
+ * Returns the unique identifier associated with this GuacamoleTunnel.
+ *
+ * @return The unique identifier associated with this GuacamoleTunnel.
+ */
+ public UUID getUUID() {
+ return uuid;
+ }
+
+ /**
+ * Returns the GuacamoleSocket used by this GuacamoleTunnel for reading
+ * and writing.
+ *
+ * @return The GuacamoleSocket used by this GuacamoleTunnel.
+ */
+ public GuacamoleSocket getSocket() {
+ return socket;
+ }
+
+ /**
+ * Release all resources allocated to this GuacamoleTunnel.
+ *
+ * @throws GuacamoleException if an error occurs while releasing
+ * resources.
+ */
+ public void close() throws GuacamoleException {
+ socket.close();
+ }
+
+ /**
+ * Returns whether this GuacamoleTunnel is open, or has been closed.
+ *
+ * @return true if this GuacamoleTunnel is open, false if it is closed.
+ */
+ public boolean isOpen() {
+ return socket.isOpen();
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/net/InetGuacamoleSocket.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/InetGuacamoleSocket.java
new file mode 100644
index 0000000..df28f4e
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/InetGuacamoleSocket.java
@@ -0,0 +1,160 @@
+
+package org.glyptodon.guacamole.net;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.ReaderGuacamoleReader;
+import org.glyptodon.guacamole.io.WriterGuacamoleWriter;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+
+import java.io.InputStreamReader;
+
+import java.io.OutputStreamWriter;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Provides abstract socket-like access to a Guacamole connection over a given
+ * hostname and port.
+ *
+ * @author Michael Jumper
+ */
+public class InetGuacamoleSocket implements GuacamoleSocket {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(InetGuacamoleSocket.class);
+
+ /**
+ * The GuacamoleReader this socket should read from.
+ */
+ private GuacamoleReader reader;
+
+ /**
+ * The GuacamoleWriter this socket should write to.
+ */
+ private GuacamoleWriter writer;
+
+ /**
+ * The number of milliseconds to wait for data on the TCP socket before
+ * timing out.
+ */
+ private static final int SOCKET_TIMEOUT = 15000;
+
+ /**
+ * The TCP socket that the GuacamoleReader and GuacamoleWriter exposed
+ * by this class should affect.
+ */
+ private Socket sock;
+
+ /**
+ * Creates a new InetGuacamoleSocket which reads and writes instructions
+ * to the Guacamole instruction stream of the Guacamole proxy server
+ * running at the given hostname and port.
+ *
+ * @param hostname The hostname of the Guacamole proxy server to connect to.
+ * @param port The port of the Guacamole proxy server to connect to.
+ * @throws GuacamoleException If an error occurs while connecting to the
+ * Guacamole proxy server.
+ */
+ public InetGuacamoleSocket(String hostname, int port) throws GuacamoleException {
+
+ try {
+
+ logger.debug("Connecting to guacd at {}:{}.", hostname, port);
+
+ // Get address
+ SocketAddress address = new InetSocketAddress(
+ InetAddress.getByName(hostname),
+ port
+ );
+
+ // Connect with timeout
+ sock = new Socket();
+ sock.connect(address, SOCKET_TIMEOUT);
+
+ // Set read timeout
+ sock.setSoTimeout(SOCKET_TIMEOUT);
+
+ // On successful connect, retrieve I/O streams
+ reader = new ReaderGuacamoleReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
+ writer = new WriterGuacamoleWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
+
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+
+ }
+
+ @Override
+ public void close() throws GuacamoleException {
+ try {
+ logger.debug("Closing socket to guacd.");
+ sock.close();
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+ }
+
+ @Override
+ public GuacamoleReader getReader() {
+ return reader;
+ }
+
+ @Override
+ public GuacamoleWriter getWriter() {
+ return writer;
+ }
+
+ @Override
+ public boolean isOpen() {
+ return !sock.isClosed();
+ }
+
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/net/SSLGuacamoleSocket.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/SSLGuacamoleSocket.java
new file mode 100644
index 0000000..44c2f3f
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/SSLGuacamoleSocket.java
@@ -0,0 +1,164 @@
+
+package org.glyptodon.guacamole.net;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLSocketFactory;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+import org.glyptodon.guacamole.io.ReaderGuacamoleReader;
+import org.glyptodon.guacamole.io.WriterGuacamoleWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Provides abstract socket-like access to a Guacamole connection over SSL to
+ * a given hostname and port.
+ *
+ * @author Michael Jumper
+ */
+public class SSLGuacamoleSocket implements GuacamoleSocket {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(SSLGuacamoleSocket.class);
+
+ /**
+ * The GuacamoleReader this socket should read from.
+ */
+ private GuacamoleReader reader;
+
+ /**
+ * The GuacamoleWriter this socket should write to.
+ */
+ private GuacamoleWriter writer;
+
+ /**
+ * The number of milliseconds to wait for data on the TCP socket before
+ * timing out.
+ */
+ private static final int SOCKET_TIMEOUT = 15000;
+
+ /**
+ * The TCP socket that the GuacamoleReader and GuacamoleWriter exposed
+ * by this class should affect.
+ */
+ private Socket sock;
+
+ /**
+ * Creates a new SSLGuacamoleSocket which reads and writes instructions
+ * to the Guacamole instruction stream of the Guacamole proxy server
+ * running at the given hostname and port using SSL.
+ *
+ * @param hostname The hostname of the Guacamole proxy server to connect to.
+ * @param port The port of the Guacamole proxy server to connect to.
+ * @throws GuacamoleException If an error occurs while connecting to the
+ * Guacamole proxy server.
+ */
+ public SSLGuacamoleSocket(String hostname, int port) throws GuacamoleException {
+
+ // Get factory for SSL sockets
+ SocketFactory socket_factory = SSLSocketFactory.getDefault();
+
+ try {
+
+ logger.debug("Connecting to guacd at {}:{} via SSL/TLS.",
+ hostname, port);
+
+ // Get address
+ SocketAddress address = new InetSocketAddress(
+ InetAddress.getByName(hostname),
+ port
+ );
+
+ // Connect with timeout
+ sock = socket_factory.createSocket();
+ sock.connect(address, SOCKET_TIMEOUT);
+
+ // Set read timeout
+ sock.setSoTimeout(SOCKET_TIMEOUT);
+
+ // On successful connect, retrieve I/O streams
+ reader = new ReaderGuacamoleReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
+ writer = new WriterGuacamoleWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
+
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+
+ }
+
+ @Override
+ public void close() throws GuacamoleException {
+ try {
+ logger.debug("Closing socket to guacd.");
+ sock.close();
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+ }
+
+ @Override
+ public GuacamoleReader getReader() {
+ return reader;
+ }
+
+ @Override
+ public GuacamoleWriter getWriter() {
+ return writer;
+ }
+
+ @Override
+ public boolean isOpen() {
+ return !sock.isClosed();
+ }
+
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/net/package-info.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/package-info.java
new file mode 100644
index 0000000..ae1a8d0
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/net/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes which apply to network-specific concepts, such as low-level sockets
+ * and tunnels.
+ */
+package org.glyptodon.guacamole.net;
+
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/package-info.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/package-info.java
new file mode 100644
index 0000000..d947b5c
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/package-info.java
@@ -0,0 +1,8 @@
+
+/**
+ * All classes which apply generally across the Guacamole web application
+ * and all other web applications which use the API provided by the
+ * Guacamole project.
+ */
+package org.glyptodon.guacamole;
+
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/ConfiguredGuacamoleSocket.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/ConfiguredGuacamoleSocket.java
new file mode 100644
index 0000000..06308f4
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/ConfiguredGuacamoleSocket.java
@@ -0,0 +1,206 @@
+
+package org.glyptodon.guacamole.protocol;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.List;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+
+/**
+ * A GuacamoleSocket which pre-configures the connection based on a given
+ * GuacamoleConfiguration, completing the initial protocol handshake before
+ * accepting data for read or write.
+ *
+ * This is useful for forcing a connection to the Guacamole proxy server with
+ * a specific configuration while disallowing the client that will be using
+ * this GuacamoleSocket from manually controlling the initial protocol
+ * handshake.
+ *
+ * @author Michael Jumper
+ */
+public class ConfiguredGuacamoleSocket implements GuacamoleSocket {
+
+ /**
+ * The wrapped socket.
+ */
+ private GuacamoleSocket socket;
+
+ /**
+ * The configuration to use when performing the Guacamole protocol
+ * handshake.
+ */
+ private GuacamoleConfiguration config;
+
+ /**
+ * Creates a new ConfiguredGuacamoleSocket which uses the given
+ * GuacamoleConfiguration to complete the initial protocol handshake over
+ * the given GuacamoleSocket. A default GuacamoleClientInformation object
+ * is used to provide basic client information.
+ *
+ * @param socket The GuacamoleSocket to wrap.
+ * @param config The GuacamoleConfiguration to use to complete the initial
+ * protocol handshake.
+ * @throws GuacamoleException If an error occurs while completing the
+ * initial protocol handshake.
+ */
+ public ConfiguredGuacamoleSocket(GuacamoleSocket socket,
+ GuacamoleConfiguration config) throws GuacamoleException {
+ this(socket, config, new GuacamoleClientInformation());
+ }
+
+
+ /**
+ * Creates a new ConfiguredGuacamoleSocket which uses the given
+ * GuacamoleConfiguration and GuacamoleClientInformation to complete the
+ * initial protocol handshake over the given GuacamoleSocket.
+ *
+ * @param socket The GuacamoleSocket to wrap.
+ * @param config The GuacamoleConfiguration to use to complete the initial
+ * protocol handshake.
+ * @param info The GuacamoleClientInformation to use to complete the initial
+ * protocol handshake.
+ * @throws GuacamoleException If an error occurs while completing the
+ * initial protocol handshake.
+ */
+ public ConfiguredGuacamoleSocket(GuacamoleSocket socket,
+ GuacamoleConfiguration config,
+ GuacamoleClientInformation info) throws GuacamoleException {
+
+ this.socket = socket;
+ this.config = config;
+
+ // Get reader and writer
+ GuacamoleReader reader = socket.getReader();
+ GuacamoleWriter writer = socket.getWriter();
+
+ // Send protocol
+ writer.writeInstruction(new GuacamoleInstruction("select", config.getProtocol()));
+
+ // Wait for server args
+ GuacamoleInstruction instruction;
+ do {
+
+ // Read instruction, fail if end-of-stream
+ instruction = reader.readInstruction();
+ if (instruction == null)
+ throw new GuacamoleServerException("End of stream during initial handshake.");
+
+ } while (!instruction.getOpcode().equals("args"));
+
+ // Build args list off provided names and config
+ List<String> arg_names = instruction.getArgs();
+ String[] arg_values = new String[arg_names.size()];
+ for (int i=0; i<arg_names.size(); i++) {
+
+ // Retrieve argument name
+ String arg_name = arg_names.get(i);
+
+ // Get defined value for name
+ String value = config.getParameter(arg_name);
+
+ // If value defined, set that value
+ if (value != null) arg_values[i] = value;
+
+ // Otherwise, leave value blank
+ else arg_values[i] = "";
+
+ }
+
+ // Send size
+ writer.writeInstruction(
+ new GuacamoleInstruction(
+ "size",
+ Integer.toString(info.getOptimalScreenWidth()),
+ Integer.toString(info.getOptimalScreenHeight())
+ )
+ );
+
+ // Send supported audio formats
+ writer.writeInstruction(
+ new GuacamoleInstruction(
+ "audio",
+ info.getAudioMimetypes().toArray(new String[0])
+ ));
+
+ // Send supported video formats
+ writer.writeInstruction(
+ new GuacamoleInstruction(
+ "video",
+ info.getVideoMimetypes().toArray(new String[0])
+ ));
+
+ // Send args
+ writer.writeInstruction(new GuacamoleInstruction("connect", arg_values));
+
+ }
+
+ /**
+ * Returns the GuacamoleConfiguration used to configure this
+ * ConfiguredGuacamoleSocket.
+ *
+ * @return The GuacamoleConfiguration used to configure this
+ * ConfiguredGuacamoleSocket.
+ */
+ public GuacamoleConfiguration getConfiguration() {
+ return config;
+ }
+
+ @Override
+ public GuacamoleWriter getWriter() {
+ return socket.getWriter();
+ }
+
+ @Override
+ public GuacamoleReader getReader() {
+ return socket.getReader();
+ }
+
+ @Override
+ public void close() throws GuacamoleException {
+ socket.close();
+ }
+
+ @Override
+ public boolean isOpen() {
+ return socket.isOpen();
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleClientInformation.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleClientInformation.java
new file mode 100644
index 0000000..6cb10a2
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleClientInformation.java
@@ -0,0 +1,125 @@
+
+package org.glyptodon.guacamole.protocol;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * An abstract representation of Guacamole client information, including all
+ * information required by the Guacamole protocol during the preamble.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleClientInformation {
+
+ /**
+ * The optimal screen width requested by the client, in pixels.
+ */
+ private int optimalScreenWidth = 1024;
+
+ /**
+ * The optimal screen height requested by the client, in pixels.
+ */
+ private int optimalScreenHeight = 768;
+
+ /**
+ * The list of audio mimetypes reported by the client to be supported.
+ */
+ private List<String> audioMimetypes = new ArrayList<String>();
+
+ /**
+ * The list of audio mimetypes reported by the client to be supported.
+ */
+ private List<String> videoMimetypes = new ArrayList<String>();
+
+ /**
+ * Returns the optimal screen width requested by the client, in pixels.
+ * @return The optimal screen width requested by the client, in pixels.
+ */
+ public int getOptimalScreenWidth() {
+ return optimalScreenWidth;
+ }
+
+ /**
+ * Sets the client's optimal screen width.
+ * @param optimalScreenWidth The optimal screen width of the client.
+ */
+ public void setOptimalScreenWidth(int optimalScreenWidth) {
+ this.optimalScreenWidth = optimalScreenWidth;
+ }
+
+ /**
+ * Returns the optimal screen height requested by the client, in pixels.
+ * @return The optimal screen height requested by the client, in pixels.
+ */
+ public int getOptimalScreenHeight() {
+ return optimalScreenHeight;
+ }
+
+ /**
+ * Sets the client's optimal screen height.
+ * @param optimalScreenHeight The optimal screen height of the client.
+ */
+ public void setOptimalScreenHeight(int optimalScreenHeight) {
+ this.optimalScreenHeight = optimalScreenHeight;
+ }
+
+ /**
+ * Returns the list of audio mimetypes supported by the client. To add or
+ * removed supported mimetypes, the list returned by this function can be
+ * modified.
+ *
+ * @return The set of audio mimetypes supported by the client.
+ */
+ public List<String> getAudioMimetypes() {
+ return audioMimetypes;
+ }
+
+ /**
+ * Returns the list of video mimetypes supported by the client. To add or
+ * removed supported mimetypes, the list returned by this function can be
+ * modified.
+ *
+ * @return The set of video mimetypes supported by the client.
+ */
+ public List<String> getVideoMimetypes() {
+ return videoMimetypes;
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleConfiguration.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleConfiguration.java
new file mode 100644
index 0000000..5b15a25
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleConfiguration.java
@@ -0,0 +1,125 @@
+
+package org.glyptodon.guacamole.protocol;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * All information necessary to complete the initial protocol handshake of a
+ * Guacamole session.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleConfiguration implements Serializable {
+
+ /**
+ * Identifier unique to this version of GuacamoleConfiguration.
+ */
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * The name of the protocol associated with this configuration.
+ */
+ private String protocol;
+
+ /**
+ * Map of all associated parameter values, indexed by parameter name.
+ */
+ private Map<String, String> parameters = new HashMap<String, String>();
+
+ /**
+ * Returns the name of the protocol to be used.
+ * @return The name of the protocol to be used.
+ */
+ public String getProtocol() {
+ return protocol;
+ }
+
+ /**
+ * Sets the name of the protocol to be used.
+ * @param protocol The name of the protocol to be used.
+ */
+ public void setProtocol(String protocol) {
+ this.protocol = protocol;
+ }
+
+ /**
+ * Returns the value set for the parameter with the given name, if any.
+ * @param name The name of the parameter to return the value for.
+ * @return The value of the parameter with the given name, or null if
+ * that parameter has not been set.
+ */
+ public String getParameter(String name) {
+ return parameters.get(name);
+ }
+
+ /**
+ * Sets the value for the parameter with the given name.
+ *
+ * @param name The name of the parameter to set the value for.
+ * @param value The value to set for the parameter with the given name.
+ */
+ public void setParameter(String name, String value) {
+ parameters.put(name, value);
+ }
+
+ /**
+ * Removes the value set for the parameter with the given name.
+ *
+ * @param name The name of the parameter to remove the value of.
+ */
+ public void unsetParameter(String name) {
+ parameters.remove(name);
+ }
+
+ /**
+ * Returns a set of all currently defined parameter names. Each name
+ * corresponds to a parameter that has a value set on this
+ * GuacamoleConfiguration via setParameter().
+ *
+ * @return A set of all currently defined parameter names.
+ */
+ public Set<String> getParameterNames() {
+ return Collections.unmodifiableSet(parameters.keySet());
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleInstruction.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleInstruction.java
new file mode 100644
index 0000000..8b94fa1
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/GuacamoleInstruction.java
@@ -0,0 +1,127 @@
+
+package org.glyptodon.guacamole.protocol;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * An abstract representation of a Guacamole instruction, as defined by the
+ * Guacamole protocol.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleInstruction {
+
+ /**
+ * The opcode of this instruction.
+ */
+ private String opcode;
+
+ /**
+ * All arguments of this instruction, in order.
+ */
+ private List<String> args;
+
+ /**
+ * Creates a new GuacamoleInstruction having the given Operation and
+ * list of arguments values.
+ *
+ * @param opcode The opcode of the instruction to create.
+ * @param args The list of argument values to provide in the new
+ * instruction if any.
+ */
+ public GuacamoleInstruction(String opcode, String... args) {
+ this.opcode = opcode;
+ this.args = Collections.unmodifiableList(Arrays.asList(args));
+ }
+
+ /**
+ * Returns the opcode associated with this GuacamoleInstruction.
+ * @return The opcode associated with this GuacamoleInstruction.
+ */
+ public String getOpcode() {
+ return opcode;
+ }
+
+ /**
+ * Returns a List of all argument values specified for this
+ * GuacamoleInstruction. Note that the List returned is immutable.
+ * Attempts to modify the list will result in exceptions.
+ *
+ * @return A List of all argument values specified for this
+ * GuacamoleInstruction.
+ */
+ public List<String> getArgs() {
+ return args;
+ }
+
+ /**
+ * Returns this GuacamoleInstruction in the form it would be sent over the
+ * Guacamole protocol.
+ *
+ * @return This GuacamoleInstruction in the form it would be sent over the
+ * Guacamole protocol.
+ */
+ @Override
+ public String toString() {
+
+ StringBuilder buff = new StringBuilder();
+
+ // Write opcode
+ buff.append(opcode.length());
+ buff.append('.');
+ buff.append(opcode);
+
+ // Write argument values
+ for (String value : args) {
+ buff.append(',');
+ buff.append(value.length());
+ buff.append('.');
+ buff.append(value);
+ }
+
+ // Write terminator
+ buff.append(';');
+
+ return buff.toString();
+
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/package-info.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/package-info.java
new file mode 100644
index 0000000..7b2b962
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/protocol/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Classes relating directly to the Guacamole protocol.
+ */
+package org.glyptodon.guacamole.protocol;
+
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/GuacamoleHTTPTunnelServlet.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/GuacamoleHTTPTunnelServlet.java
new file mode 100644
index 0000000..05e7781
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/GuacamoleHTTPTunnelServlet.java
@@ -0,0 +1,452 @@
+package org.glyptodon.guacamole.servlet;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleResourceNotFoundException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.io.GuacamoleReader;
+import org.glyptodon.guacamole.io.GuacamoleWriter;
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A HttpServlet implementing and abstracting the operations required by the
+ * HTTP implementation of the JavaScript Guacamole client's tunnel.
+ *
+ * @author Michael Jumper
+ */
+public abstract class GuacamoleHTTPTunnelServlet extends HttpServlet {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(GuacamoleHTTPTunnelServlet.class);
+
+ /**
+ * The prefix of the query string which denotes a tunnel read operation.
+ */
+ private static final String READ_PREFIX = "read:";
+
+ /**
+ * The prefix of the query string which denotes a tunnel write operation.
+ */
+ private static final String WRITE_PREFIX = "write:";
+
+ /**
+ * The length of the read prefix, in characters.
+ */
+ private static final int READ_PREFIX_LENGTH = READ_PREFIX.length();
+
+ /**
+ * The length of the write prefix, in characters.
+ */
+ private static final int WRITE_PREFIX_LENGTH = WRITE_PREFIX.length();
+
+ /**
+ * The length of every tunnel UUID, in characters.
+ */
+ private static final int UUID_LENGTH = 36;
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
+ handleTunnelRequest(request, response);
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
+ handleTunnelRequest(request, response);
+ }
+
+ /**
+ * Sends an error on the given HTTP response with the given integer error
+ * code.
+ *
+ * @param response The HTTP response to use to send the error.
+ * @param code The HTTP status code of the error.
+ * @throws ServletException If an error prevents sending of the error
+ * code.
+ */
+ private void sendError(HttpServletResponse response, int code) throws ServletException {
+
+ try {
+
+ // If response not committed, send error code
+ if (!response.isCommitted())
+ response.sendError(code);
+
+ }
+ catch (IOException ioe) {
+
+ // If unable to send error at all due to I/O problems,
+ // rethrow as servlet exception
+ throw new ServletException(ioe);
+
+ }
+
+ }
+
+
+
+ /**
+ * Dispatches every HTTP GET and POST request to the appropriate handler
+ * function based on the query string.
+ *
+ * @param request The HttpServletRequest associated with the GET or POST
+ * request received.
+ * @param response The HttpServletResponse associated with the GET or POST
+ * request received.
+ * @throws ServletException If an error occurs while servicing the request.
+ */
+ protected void handleTunnelRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
+
+ try {
+
+ String query = request.getQueryString();
+ if (query == null)
+ throw new GuacamoleClientException("No query string provided.");
+
+ // If connect operation, call doConnect() and return tunnel UUID
+ // in response.
+ if (query.equals("connect")) {
+
+ GuacamoleTunnel tunnel = doConnect(request);
+ if (tunnel != null) {
+
+ // Get session
+ HttpSession httpSession = request.getSession(true);
+ GuacamoleSession session = new GuacamoleSession(httpSession);
+
+ // Attach tunnel to session
+ session.attachTunnel(tunnel);
+
+ logger.info("Connection from {} succeeded.", request.getRemoteAddr());
+
+ try {
+ // Ensure buggy browsers do not cache response
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Send UUID to client
+ response.getWriter().print(tunnel.getUUID().toString());
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(e);
+ }
+
+ }
+
+ // Failed to connect
+ else {
+ logger.info("Connection from {} failed.", request.getRemoteAddr());
+ throw new GuacamoleResourceNotFoundException("No tunnel created.");
+ }
+
+ }
+
+ // If read operation, call doRead() with tunnel UUID, ignoring any
+ // characters following the tunnel UUID.
+ else if(query.startsWith(READ_PREFIX))
+ doRead(request, response, query.substring(
+ READ_PREFIX_LENGTH,
+ READ_PREFIX_LENGTH + UUID_LENGTH));
+
+ // If write operation, call doWrite() with tunnel UUID, ignoring any
+ // characters following the tunnel UUID.
+ else if(query.startsWith(WRITE_PREFIX))
+ doWrite(request, response, query.substring(
+ WRITE_PREFIX_LENGTH,
+ WRITE_PREFIX_LENGTH + UUID_LENGTH));
+
+ // Otherwise, invalid operation
+ else
+ throw new GuacamoleClientException("Invalid tunnel operation: " + query);
+ }
+
+ // Catch any thrown guacamole exception and attempt to pass within the
+ // HTTP response, logging each error appropriately.
+ catch (GuacamoleSecurityException e) {
+ logger.warn("Authorization failed.", e);
+ sendError(response, HttpServletResponse.SC_FORBIDDEN);
+ }
+ catch (GuacamoleResourceNotFoundException e) {
+ logger.debug("Resource not found.", e);
+ sendError(response, HttpServletResponse.SC_NOT_FOUND);
+ }
+ catch (GuacamoleClientException e) {
+ logger.warn("Error in client request.", e);
+ sendError(response, HttpServletResponse.SC_BAD_REQUEST);
+ }
+ catch (GuacamoleException e) {
+ logger.error("Server error in tunnel", e);
+ sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+
+ }
+
+ /**
+ * Called whenever the JavaScript Guacamole client makes a connection
+ * request. It it up to the implementor of this function to define what
+ * conditions must be met for a tunnel to be configured and returned as a
+ * result of this connection request (whether some sort of credentials must
+ * be specified, for example).
+ *
+ * @param request The HttpServletRequest associated with the connection
+ * request received. Any parameters specified along with
+ * the connection request can be read from this object.
+ * @return A newly constructed GuacamoleTunnel if successful,
+ * null otherwise.
+ * @throws GuacamoleException If an error occurs while constructing the
+ * GuacamoleTunnel, or if the conditions
+ * required for connection are not met.
+ */
+ protected abstract GuacamoleTunnel doConnect(HttpServletRequest request) throws GuacamoleException;
+
+ /**
+ * Called whenever the JavaScript Guacamole client makes a read request.
+ * This function should in general not be overridden, as it already
+ * contains a proper implementation of the read operation.
+ *
+ * @param request The HttpServletRequest associated with the read request
+ * received.
+ * @param response The HttpServletResponse associated with the write request
+ * received. Any data to be sent to the client in response
+ * to the write request should be written to the response
+ * body of this HttpServletResponse.
+ * @param tunnelUUID The UUID of the tunnel to read from, as specified in
+ * the write request. This tunnel must be attached to
+ * the Guacamole session.
+ * @throws GuacamoleException If an error occurs while handling the read
+ * request.
+ */
+ protected void doRead(HttpServletRequest request, HttpServletResponse response, String tunnelUUID) throws GuacamoleException {
+
+ HttpSession httpSession = request.getSession(false);
+ GuacamoleSession session = new GuacamoleSession(httpSession);
+
+ // Get tunnel, ensure tunnel exists
+ GuacamoleTunnel tunnel = session.getTunnel(tunnelUUID);
+ if (tunnel == null)
+ throw new GuacamoleResourceNotFoundException("No such tunnel.");
+
+ // Ensure tunnel is open
+ if (!tunnel.isOpen())
+ throw new GuacamoleResourceNotFoundException("Tunnel is closed.");
+
+ // Obtain exclusive read access
+ GuacamoleReader reader = tunnel.acquireReader();
+
+ try {
+
+ // Note that although we are sending text, Webkit browsers will
+ // buffer 1024 bytes before starting a normal stream if we use
+ // anything but application/octet-stream.
+ response.setContentType("application/octet-stream");
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Get writer for response
+ Writer out = new BufferedWriter(new OutputStreamWriter(
+ response.getOutputStream(), "UTF-8"));
+
+ // Stream data to response, ensuring output stream is closed
+ try {
+
+ // Detach tunnel and throw error if EOF (and we haven't sent any
+ // data yet.
+ char[] message = reader.read();
+ if (message == null)
+ throw new GuacamoleResourceNotFoundException("Tunnel reached end of stream.");
+
+ // For all messages, until another stream is ready (we send at least one message)
+ do {
+
+ // Get message output bytes
+ out.write(message, 0, message.length);
+
+ // Flush if we expect to wait
+ if (!reader.available()) {
+ out.flush();
+ response.flushBuffer();
+ }
+
+ // No more messages another stream can take over
+ if (tunnel.hasQueuedReaderThreads())
+ break;
+
+ } while (tunnel.isOpen() && (message = reader.read()) != null);
+
+ // Close tunnel immediately upon EOF
+ if (message == null)
+ tunnel.close();
+
+ // End-of-instructions marker
+ out.write("0.;");
+ out.flush();
+ response.flushBuffer();
+ }
+
+ // Always close output stream
+ finally {
+ out.close();
+ }
+
+ }
+ catch (GuacamoleException e) {
+
+ // Detach and close
+ session.detachTunnel(tunnel);
+ tunnel.close();
+
+ throw e;
+ }
+ catch (IOException e) {
+
+ // Log typically frequent I/O error if desired
+ logger.debug("Error writing to servlet output stream", e);
+
+ // Detach and close
+ session.detachTunnel(tunnel);
+ tunnel.close();
+
+ }
+ finally {
+ tunnel.releaseReader();
+ }
+
+ }
+
+ /**
+ * Called whenever the JavaScript Guacamole client makes a write request.
+ * This function should in general not be overridden, as it already
+ * contains a proper implementation of the write operation.
+ *
+ * @param request The HttpServletRequest associated with the write request
+ * received. Any data to be written will be specified within
+ * the body of this request.
+ * @param response The HttpServletResponse associated with the write request
+ * received.
+ * @param tunnelUUID The UUID of the tunnel to write to, as specified in
+ * the write request. This tunnel must be attached to
+ * the Guacamole session.
+ * @throws GuacamoleException If an error occurs while handling the write
+ * request.
+ */
+ protected void doWrite(HttpServletRequest request, HttpServletResponse response, String tunnelUUID) throws GuacamoleException {
+
+ HttpSession httpSession = request.getSession(false);
+ GuacamoleSession session = new GuacamoleSession(httpSession);
+
+ GuacamoleTunnel tunnel = session.getTunnel(tunnelUUID);
+ if (tunnel == null)
+ throw new GuacamoleResourceNotFoundException("No such tunnel.");
+
+ // We still need to set the content type to avoid the default of
+ // text/html, as such a content type would cause some browsers to
+ // attempt to parse the result, even though the JavaScript client
+ // does not explicitly request such parsing.
+ response.setContentType("application/octet-stream");
+ response.setHeader("Cache-Control", "no-cache");
+ response.setContentLength(0);
+
+ // Send data
+ try {
+
+ // Get writer from tunnel
+ GuacamoleWriter writer = tunnel.acquireWriter();
+
+ // Get input reader for HTTP stream
+ Reader input = new InputStreamReader(
+ request.getInputStream(), "UTF-8");
+
+ // Transfer data from input stream to tunnel output, ensuring
+ // input is always closed
+ try {
+
+ // Buffer
+ int length;
+ char[] buffer = new char[8192];
+
+ // Transfer data using buffer
+ while (tunnel.isOpen() &&
+ (length = input.read(buffer, 0, buffer.length)) != -1)
+ writer.write(buffer, 0, length);
+
+ }
+
+ // Close input stream in all cases
+ finally {
+ input.close();
+ }
+
+ }
+ catch (IOException e) {
+
+ // Detach and close
+ session.detachTunnel(tunnel);
+ tunnel.close();
+
+ throw new GuacamoleServerException("I/O Error sending data to server: " + e.getMessage(), e);
+ }
+ finally {
+ tunnel.releaseWriter();
+ }
+
+ }
+
+}
+
+/**
+ * \example ExampleTunnelServlet.java
+ *
+ * A basic example demonstrating extending GuacamoleTunnelServlet and
+ * implementing doConnect() to configure the Guacamole connection as
+ * desired.
+ */
+
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/GuacamoleSession.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/GuacamoleSession.java
new file mode 100644
index 0000000..1d8641f
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/GuacamoleSession.java
@@ -0,0 +1,125 @@
+
+package org.glyptodon.guacamole.servlet;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-common.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import javax.servlet.http.HttpSession;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Provides abstract access to the tunnels associated with a Guacamole session.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleSession {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(GuacamoleSession.class);
+
+ /**
+ * Map of all currently attached tunnels, indexed by tunnel UUID.
+ */
+ private ConcurrentMap<String, GuacamoleTunnel> tunnels;
+
+ /**
+ * Creates a new GuacamoleSession, storing and retrieving tunnels from the
+ * given HttpSession. Note that the true Guacamole session is tied to the
+ * HttpSession provided, thus creating a new GuacamoleSession does not
+ * create a new Guacamole session; it merely creates a new object for
+ * accessing the tunnels of an existing Guacamole session represented by
+ * the provided HttpSession.
+ *
+ * @param session The HttpSession to use as tunnel storage.
+ * @throws GuacamoleException If session is null.
+ */
+ @SuppressWarnings("unchecked")
+ public GuacamoleSession(HttpSession session) throws GuacamoleException {
+
+ if (session == null)
+ throw new GuacamoleSecurityException("User has no session.");
+
+ synchronized (session) {
+
+ tunnels = (ConcurrentMap<String, GuacamoleTunnel>) session.getAttribute("GUAC_TUNNELS");
+ if (tunnels == null) {
+ tunnels = new ConcurrentHashMap<String, GuacamoleTunnel>();
+ session.setAttribute("GUAC_TUNNELS", tunnels);
+ }
+
+ }
+
+ }
+
+ /**
+ * Attaches the given tunnel to this GuacamoleSession.
+ * @param tunnel The tunnel to attach to this GucacamoleSession.
+ */
+ public void attachTunnel(GuacamoleTunnel tunnel) {
+ tunnels.put(tunnel.getUUID().toString(), tunnel);
+ logger.debug("Attached tunnel {}.", tunnel.getUUID());
+ }
+
+ /**
+ * Detaches the given tunnel to this GuacamoleSession.
+ * @param tunnel The tunnel to detach to this GucacamoleSession.
+ */
+ public void detachTunnel(GuacamoleTunnel tunnel) {
+ tunnels.remove(tunnel.getUUID().toString());
+ logger.debug("Detached tunnel {}.", tunnel.getUUID());
+ }
+
+ /**
+ * Returns the tunnel with the given UUID attached to this GuacamoleSession,
+ * if any.
+ *
+ * @param tunnelUUID The UUID of an attached tunnel.
+ * @return The tunnel corresponding to the given UUID, if attached, or null
+ * if no such tunnel is attached.
+ */
+ public GuacamoleTunnel getTunnel(String tunnelUUID) {
+ return tunnels.get(tunnelUUID);
+ }
+
+}
diff --git a/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/package-info.java b/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/package-info.java
new file mode 100644
index 0000000..21e25a6
--- /dev/null
+++ b/guacamole-common/src/main/java/org/glyptodon/guacamole/servlet/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes which build upon the Java Servlet API, providing an HTTP-based
+ * tunnel and session management.
+ */
+package org.glyptodon.guacamole.servlet;
+
diff --git a/guacamole-ext/ChangeLog b/guacamole-ext/ChangeLog
new file mode 100644
index 0000000..53960ba
--- /dev/null
+++ b/guacamole-ext/ChangeLog
@@ -0,0 +1,18 @@
+2012-10-15 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Updated to latest guacamole-common
+
+2012-08-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Improved documentation
+
+2012-05-04 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Renamed to guacamole-ext
+ * Generic HTTP-based Credentials object
+ * Added support for listeners and hooks
+
+2011-12-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Initial release
+
diff --git a/guacamole-ext/LICENSE b/guacamole-ext/LICENSE
new file mode 100644
index 0000000..7714141
--- /dev/null
+++ b/guacamole-ext/LICENSE
@@ -0,0 +1,470 @@
+ MOZILLA PUBLIC LICENSE
+ Version 1.1
+
+ ---------------
+
+1. Definitions.
+
+ 1.0.1. "Commercial Use" means distribution or otherwise making the
+ Covered Code available to a third party.
+
+ 1.1. "Contributor" means each entity that creates or contributes to
+ the creation of Modifications.
+
+ 1.2. "Contributor Version" means the combination of the Original
+ Code, prior Modifications used by a Contributor, and the Modifications
+ made by that particular Contributor.
+
+ 1.3. "Covered Code" means the Original Code or Modifications or the
+ combination of the Original Code and Modifications, in each case
+ including portions thereof.
+
+ 1.4. "Electronic Distribution Mechanism" means a mechanism generally
+ accepted in the software development community for the electronic
+ transfer of data.
+
+ 1.5. "Executable" means Covered Code in any form other than Source
+ Code.
+
+ 1.6. "Initial Developer" means the individual or entity identified
+ as the Initial Developer in the Source Code notice required by Exhibit
+ A.
+
+ 1.7. "Larger Work" means a work which combines Covered Code or
+ portions thereof with code not governed by the terms of this License.
+
+ 1.8. "License" means this document.
+
+ 1.8.1. "Licensable" means having the right to grant, to the maximum
+ extent possible, whether at the time of the initial grant or
+ subsequently acquired, any and all of the rights conveyed herein.
+
+ 1.9. "Modifications" means any addition to or deletion from the
+ substance or structure of either the Original Code or any previous
+ Modifications. When Covered Code is released as a series of files, a
+ Modification is:
+ A. Any addition to or deletion from the contents of a file
+ containing Original Code or previous Modifications.
+
+ B. Any new file that contains any part of the Original Code or
+ previous Modifications.
+
+ 1.10. "Original Code" means Source Code of computer software code
+ which is described in the Source Code notice required by Exhibit A as
+ Original Code, and which, at the time of its release under this
+ License is not already Covered Code governed by this License.
+
+ 1.10.1. "Patent Claims" means any patent claim(s), now owned or
+ hereafter acquired, including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by grantor.
+
+ 1.11. "Source Code" means the preferred form of the Covered Code for
+ making modifications to it, including all modules it contains, plus
+ any associated interface definition files, scripts used to control
+ compilation and installation of an Executable, or source code
+ differential comparisons against either the Original Code or another
+ well known, available Covered Code of the Contributor's choice. The
+ Source Code can be in a compressed or archival form, provided the
+ appropriate decompression or de-archiving software is widely available
+ for no charge.
+
+ 1.12. "You" (or "Your") means an individual or a legal entity
+ exercising rights under, and complying with all of the terms of, this
+ License or a future version of this License issued under Section 6.1.
+ For legal entities, "You" includes any entity which controls, is
+ controlled by, or is under common control with You. For purposes of
+ this definition, "control" means (a) the power, direct or indirect,
+ to cause the direction or management of such entity, whether by
+ contract or otherwise, or (b) ownership of more than fifty percent
+ (50%) of the outstanding shares or beneficial ownership of such
+ entity.
+
+2. Source Code License.
+
+ 2.1. The Initial Developer Grant.
+ The Initial Developer hereby grants You a world-wide, royalty-free,
+ non-exclusive license, subject to third party intellectual property
+ claims:
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Initial Developer to use, reproduce,
+ modify, display, perform, sublicense and distribute the Original
+ Code (or portions thereof) with or without Modifications, and/or
+ as part of a Larger Work; and
+
+ (b) under Patents Claims infringed by the making, using or
+ selling of Original Code, to make, have made, use, practice,
+ sell, and offer for sale, and/or otherwise dispose of the
+ Original Code (or portions thereof).
+
+ (c) the licenses granted in this Section 2.1(a) and (b) are
+ effective on the date Initial Developer first distributes
+ Original Code under the terms of this License.
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is
+ granted: 1) for code that You delete from the Original Code; 2)
+ separate from the Original Code; or 3) for infringements caused
+ by: i) the modification of the Original Code or ii) the
+ combination of the Original Code with other software or devices.
+
+ 2.2. Contributor Grant.
+ Subject to third party intellectual property claims, each Contributor
+ hereby grants You a world-wide, royalty-free, non-exclusive license
+
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Contributor, to use, reproduce, modify,
+ display, perform, sublicense and distribute the Modifications
+ created by such Contributor (or portions thereof) either on an
+ unmodified basis, with other Modifications, as Covered Code
+ and/or as part of a Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using, or
+ selling of Modifications made by that Contributor either alone
+ and/or in combination with its Contributor Version (or portions
+ of such combination), to make, use, sell, offer for sale, have
+ made, and/or otherwise dispose of: 1) Modifications made by that
+ Contributor (or portions thereof); and 2) the combination of
+ Modifications made by that Contributor with its Contributor
+ Version (or portions of such combination).
+
+ (c) the licenses granted in Sections 2.2(a) and 2.2(b) are
+ effective on the date Contributor first makes Commercial Use of
+ the Covered Code.
+
+ (d) Notwithstanding Section 2.2(b) above, no patent license is
+ granted: 1) for any code that Contributor has deleted from the
+ Contributor Version; 2) separate from the Contributor Version;
+ 3) for infringements caused by: i) third party modifications of
+ Contributor Version or ii) the combination of Modifications made
+ by that Contributor with other software (except as part of the
+ Contributor Version) or other devices; or 4) under Patent Claims
+ infringed by Covered Code in the absence of Modifications made by
+ that Contributor.
+
+3. Distribution Obligations.
+
+ 3.1. Application of License.
+ The Modifications which You create or to which You contribute are
+ governed by the terms of this License, including without limitation
+ Section 2.2. The Source Code version of Covered Code may be
+ distributed only under the terms of this License or a future version
+ of this License released under Section 6.1, and You must include a
+ copy of this License with every copy of the Source Code You
+ distribute. You may not offer or impose any terms on any Source Code
+ version that alters or restricts the applicable version of this
+ License or the recipients' rights hereunder. However, You may include
+ an additional document offering the additional rights described in
+ Section 3.5.
+
+ 3.2. Availability of Source Code.
+ Any Modification which You create or to which You contribute must be
+ made available in Source Code form under the terms of this License
+ either on the same media as an Executable version or via an accepted
+ Electronic Distribution Mechanism to anyone to whom you made an
+ Executable version available; and if made available via Electronic
+ Distribution Mechanism, must remain available for at least twelve (12)
+ months after the date it initially became available, or at least six
+ (6) months after a subsequent version of that particular Modification
+ has been made available to such recipients. You are responsible for
+ ensuring that the Source Code version remains available even if the
+ Electronic Distribution Mechanism is maintained by a third party.
+
+ 3.3. Description of Modifications.
+ You must cause all Covered Code to which You contribute to contain a
+ file documenting the changes You made to create that Covered Code and
+ the date of any change. You must include a prominent statement that
+ the Modification is derived, directly or indirectly, from Original
+ Code provided by the Initial Developer and including the name of the
+ Initial Developer in (a) the Source Code, and (b) in any notice in an
+ Executable version or related documentation in which You describe the
+ origin or ownership of the Covered Code.
+
+ 3.4. Intellectual Property Matters
+ (a) Third Party Claims.
+ If Contributor has knowledge that a license under a third party's
+ intellectual property rights is required to exercise the rights
+ granted by such Contributor under Sections 2.1 or 2.2,
+ Contributor must include a text file with the Source Code
+ distribution titled "LEGAL" which describes the claim and the
+ party making the claim in sufficient detail that a recipient will
+ know whom to contact. If Contributor obtains such knowledge after
+ the Modification is made available as described in Section 3.2,
+ Contributor shall promptly modify the LEGAL file in all copies
+ Contributor makes available thereafter and shall take other steps
+ (such as notifying appropriate mailing lists or newsgroups)
+ reasonably calculated to inform those who received the Covered
+ Code that new knowledge has been obtained.
+
+ (b) Contributor APIs.
+ If Contributor's Modifications include an application programming
+ interface and Contributor has knowledge of patent licenses which
+ are reasonably necessary to implement that API, Contributor must
+ also include this information in the LEGAL file.
+
+ (c) Representations.
+ Contributor represents that, except as disclosed pursuant to
+ Section 3.4(a) above, Contributor believes that Contributor's
+ Modifications are Contributor's original creation(s) and/or
+ Contributor has sufficient rights to grant the rights conveyed by
+ this License.
+
+ 3.5. Required Notices.
+ You must duplicate the notice in Exhibit A in each file of the Source
+ Code. If it is not possible to put such notice in a particular Source
+ Code file due to its structure, then You must include such notice in a
+ location (such as a relevant directory) where a user would be likely
+ to look for such a notice. If You created one or more Modification(s)
+ You may add your name as a Contributor to the notice described in
+ Exhibit A. You must also duplicate this License in any documentation
+ for the Source Code where You describe recipients' rights or ownership
+ rights relating to Covered Code. You may choose to offer, and to
+ charge a fee for, warranty, support, indemnity or liability
+ obligations to one or more recipients of Covered Code. However, You
+ may do so only on Your own behalf, and not on behalf of the Initial
+ Developer or any Contributor. You must make it absolutely clear than
+ any such warranty, support, indemnity or liability obligation is
+ offered by You alone, and You hereby agree to indemnify the Initial
+ Developer and every Contributor for any liability incurred by the
+ Initial Developer or such Contributor as a result of warranty,
+ support, indemnity or liability terms You offer.
+
+ 3.6. Distribution of Executable Versions.
+ You may distribute Covered Code in Executable form only if the
+ requirements of Section 3.1-3.5 have been met for that Covered Code,
+ and if You include a notice stating that the Source Code version of
+ the Covered Code is available under the terms of this License,
+ including a description of how and where You have fulfilled the
+ obligations of Section 3.2. The notice must be conspicuously included
+ in any notice in an Executable version, related documentation or
+ collateral in which You describe recipients' rights relating to the
+ Covered Code. You may distribute the Executable version of Covered
+ Code or ownership rights under a license of Your choice, which may
+ contain terms different from this License, provided that You are in
+ compliance with the terms of this License and that the license for the
+ Executable version does not attempt to limit or alter the recipient's
+ rights in the Source Code version from the rights set forth in this
+ License. If You distribute the Executable version under a different
+ license You must make it absolutely clear that any terms which differ
+ from this License are offered by You alone, not by the Initial
+ Developer or any Contributor. You hereby agree to indemnify the
+ Initial Developer and every Contributor for any liability incurred by
+ the Initial Developer or such Contributor as a result of any such
+ terms You offer.
+
+ 3.7. Larger Works.
+ You may create a Larger Work by combining Covered Code with other code
+ not governed by the terms of this License and distribute the Larger
+ Work as a single product. In such a case, You must make sure the
+ requirements of this License are fulfilled for the Covered Code.
+
+4. Inability to Comply Due to Statute or Regulation.
+
+ If it is impossible for You to comply with any of the terms of this
+ License with respect to some or all of the Covered Code due to
+ statute, judicial order, or regulation then You must: (a) comply with
+ the terms of this License to the maximum extent possible; and (b)
+ describe the limitations and the code they affect. Such description
+ must be included in the LEGAL file described in Section 3.4 and must
+ be included with all distributions of the Source Code. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Application of this License.
+
+ This License applies to code to which the Initial Developer has
+ attached the notice in Exhibit A and to related Covered Code.
+
+6. Versions of the License.
+
+ 6.1. New Versions.
+ Netscape Communications Corporation ("Netscape") may publish revised
+ and/or new versions of the License from time to time. Each version
+ will be given a distinguishing version number.
+
+ 6.2. Effect of New Versions.
+ Once Covered Code has been published under a particular version of the
+ License, You may always continue to use it under the terms of that
+ version. You may also choose to use such Covered Code under the terms
+ of any subsequent version of the License published by Netscape. No one
+ other than Netscape has the right to modify the terms applicable to
+ Covered Code created under this License.
+
+ 6.3. Derivative Works.
+ If You create or use a modified version of this License (which you may
+ only do in order to apply it to code which is not already Covered Code
+ governed by this License), You must (a) rename Your license so that
+ the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
+ "MPL", "NPL" or any confusingly similar phrase do not appear in your
+ license (except to note that your license differs from this License)
+ and (b) otherwise make it clear that Your version of the license
+ contains terms which differ from the Mozilla Public License and
+ Netscape Public License. (Filling in the name of the Initial
+ Developer, Original Code or Contributor in the notice described in
+ Exhibit A shall not of themselves be deemed to be modifications of
+ this License.)
+
+7. DISCLAIMER OF WARRANTY.
+
+ COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+ WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
+ DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
+ THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
+ IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
+ YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
+ COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
+ OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
+ ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+8. TERMINATION.
+
+ 8.1. This License and the rights granted hereunder will terminate
+ automatically if You fail to comply with terms herein and fail to cure
+ such breach within 30 days of becoming aware of the breach. All
+ sublicenses to the Covered Code which are properly granted shall
+ survive any termination of this License. Provisions which, by their
+ nature, must remain in effect beyond the termination of this License
+ shall survive.
+
+ 8.2. If You initiate litigation by asserting a patent infringement
+ claim (excluding declatory judgment actions) against Initial Developer
+ or a Contributor (the Initial Developer or Contributor against whom
+ You file such action is referred to as "Participant") alleging that:
+
+ (a) such Participant's Contributor Version directly or indirectly
+ infringes any patent, then any and all rights granted by such
+ Participant to You under Sections 2.1 and/or 2.2 of this License
+ shall, upon 60 days notice from Participant terminate prospectively,
+ unless if within 60 days after receipt of notice You either: (i)
+ agree in writing to pay Participant a mutually agreeable reasonable
+ royalty for Your past and future use of Modifications made by such
+ Participant, or (ii) withdraw Your litigation claim with respect to
+ the Contributor Version against such Participant. If within 60 days
+ of notice, a reasonable royalty and payment arrangement are not
+ mutually agreed upon in writing by the parties or the litigation claim
+ is not withdrawn, the rights granted by Participant to You under
+ Sections 2.1 and/or 2.2 automatically terminate at the expiration of
+ the 60 day notice period specified above.
+
+ (b) any software, hardware, or device, other than such Participant's
+ Contributor Version, directly or indirectly infringes any patent, then
+ any rights granted to You by such Participant under Sections 2.1(b)
+ and 2.2(b) are revoked effective as of the date You first made, used,
+ sold, distributed, or had made, Modifications made by that
+ Participant.
+
+ 8.3. If You assert a patent infringement claim against Participant
+ alleging that such Participant's Contributor Version directly or
+ indirectly infringes any patent where such claim is resolved (such as
+ by license or settlement) prior to the initiation of patent
+ infringement litigation, then the reasonable value of the licenses
+ granted by such Participant under Sections 2.1 or 2.2 shall be taken
+ into account in determining the amount or value of any payment or
+ license.
+
+ 8.4. In the event of termination under Sections 8.1 or 8.2 above,
+ all end user license agreements (excluding distributors and resellers)
+ which have been validly granted by You or any distributor hereunder
+ prior to termination shall survive termination.
+
+9. LIMITATION OF LIABILITY.
+
+ UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
+ (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
+ DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
+ OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
+ ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
+ CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
+ WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
+ COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
+ INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
+ LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
+ RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
+ PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
+ EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
+ THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+10. U.S. GOVERNMENT END USERS.
+
+ The Covered Code is a "commercial item," as that term is defined in
+ 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
+ software" and "commercial computer software documentation," as such
+ terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
+ C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
+ all U.S. Government End Users acquire Covered Code with only those
+ rights set forth herein.
+
+11. MISCELLANEOUS.
+
+ This License represents the complete agreement concerning subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. This License shall be governed by
+ California law provisions (except to the extent applicable law, if
+ any, provides otherwise), excluding its conflict-of-law provisions.
+ With respect to disputes in which at least one party is a citizen of,
+ or an entity chartered or registered to do business in the United
+ States of America, any litigation relating to this License shall be
+ subject to the jurisdiction of the Federal Courts of the Northern
+ District of California, with venue lying in Santa Clara County,
+ California, with the losing party responsible for costs, including
+ without limitation, court costs and reasonable attorneys' fees and
+ expenses. The application of the United Nations Convention on
+ Contracts for the International Sale of Goods is expressly excluded.
+ Any law or regulation which provides that the language of a contract
+ shall be construed against the drafter shall not apply to this
+ License.
+
+12. RESPONSIBILITY FOR CLAIMS.
+
+ As between Initial Developer and the Contributors, each party is
+ responsible for claims and damages arising, directly or indirectly,
+ out of its utilization of rights under this License and You agree to
+ work with Initial Developer and Contributors to distribute such
+ responsibility on an equitable basis. Nothing herein is intended or
+ shall be deemed to constitute any admission of liability.
+
+13. MULTIPLE-LICENSED CODE.
+
+ Initial Developer may designate portions of the Covered Code as
+ "Multiple-Licensed". "Multiple-Licensed" means that the Initial
+ Developer permits you to utilize portions of the Covered Code under
+ Your choice of the NPL or the alternative licenses, if any, specified
+ by the Initial Developer in the file described in Exhibit A.
+
+EXHIBIT A -Mozilla Public License.
+
+ ``The contents of this file are subject to the Mozilla Public License
+ Version 1.1 (the "License"); you may not use this file except in
+ compliance with the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS"
+ basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ License for the specific language governing rights and limitations
+ under the License.
+
+ The Original Code is ______________________________________.
+
+ The Initial Developer of the Original Code is ________________________.
+ Portions created by ______________________ are Copyright (C) ______
+ _______________________. All Rights Reserved.
+
+ Contributor(s): ______________________________________.
+
+ Alternatively, the contents of this file may be used under the terms
+ of the _____ license (the "[___] License"), in which case the
+ provisions of [______] License are applicable instead of those
+ above. If you wish to allow use of your version of this file only
+ under the terms of the [____] License and not to allow others to use
+ your version of this file under the MPL, indicate your decision by
+ deleting the provisions above and replace them with the notice and
+ other provisions required by the [___] License. If you do not delete
+ the provisions above, a recipient may use your version of this file
+ under either the MPL or the [___] License."
+
+ [NOTE: The text of this Exhibit A may differ slightly from the text of
+ the notices in the Source Code files of the Original Code. You should
+ use the text of this Exhibit A rather than the text found in the
+ Original Code Source Code for Your Modifications.]
+
diff --git a/guacamole-ext/README b/guacamole-ext/README
new file mode 100644
index 0000000..3bb3cef
--- /dev/null
+++ b/guacamole-ext/README
@@ -0,0 +1,79 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is guacamole-common-auth?
+------------------------------------------------------------
+
+guacamole-common-auth is a Java library used by the Guacamole web
+application to allow its built-in authentication to be extended or
+modified and reused.
+
+guacamole-common-auth provides an interface for retrieving a set of
+authorized connection configurations for a given set of arbitrary
+credentials. Classes implementing this interface can be referenced in
+guacamole.properties to allow different authentication mechanisms
+(such as LDAP) to be used.
+
+
+------------------------------------------------------------
+ Compiling and installing guacamole-common-auth
+------------------------------------------------------------
+
+guacamole-common-auth is built using Maven. Building guacamole-common-auth
+compiles all classes and packages them into a redistributable .jar file. This
+.jar file can be easily included in other Maven-based projects (like Guacamole).
+
+Note that prebuilt versions of guacamole-common-auth are available from the
+main guac-dev.org Maven repository which is referenced in all Maven
+projects in Guacamole. Unless you want to make changes to guacamole-common-auth
+or you want to use a newer, unreleased version (such as the unstable branch),
+you do not need to build this manually. You can let Maven download it for
+you when you build Guacamole.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .jar file will be
+ created in the target/ subdirectory of the current directory.
+
+2) Run mvn install
+
+ $ mvn install
+
+ DO NOT RUN THIS AS ROOT!
+
+ Maven will install guacamole-common-auth to your user's local Maven
+ repository where it can be used in future builds. It will not install
+ into a system-wide repository and does not require root privileges.
+
+ Once installed, building other Maven projects that depend on
+ guacamole-common-auth (such as Guacamole) will be possible.
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/guacamole-ext/pom.xml b/guacamole-ext/pom.xml
new file mode 100644
index 0000000..4ea7647
--- /dev/null
+++ b/guacamole-ext/pom.xml
@@ -0,0 +1,127 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-ext</artifactId>
+ <packaging>jar</packaging>
+ <version>0.8.1</version>
+ <name>guacamole-ext</name>
+ <url>http://guac-dev.org/</url>
+
+ <description>
+ The Java API for extending the main Guacamole web application. This
+ is not needed for authoring a new Guacamole-based web application.
+ </description>
+
+ <!-- All applicable licenses -->
+ <licenses>
+ <license>
+ <name>Mozilla Public License Version 1.1</name>
+ <url>http://www.mozilla.org/MPL/1.1/</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>GNU General Public License, version 2</name>
+ <url>http://www.gnu.org/licenses/gpl-2.0.html</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>GNU Lesser General Public License, version 2.1</name>
+ <url>http://www.gnu.org/licenses/lgpl-2.1.html</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <!-- Git repository -->
+ <scm>
+ <url>https://github.com/glyptodon/guacamole-client</url>
+ <connection>scm:git:git://github.com/glyptodon/guacamole-client.git</connection>
+ </scm>
+
+ <!-- Developers -->
+ <developers>
+ <developer>
+ <id>mike.jumper</id>
+ <name>Michael Jumper</name>
+ <email>mike.jumper at guac-dev.org</email>
+ </developer>
+ <developer>
+ <id>james.muehlner</id>
+ <name>James Muehlner</name>
+ <email>james.muehlner at guac-dev.org</email>
+ </developer>
+ </developers>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Written for 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <!-- Attach source jar -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <!-- Attach JavaDoc jar -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <detectOfflineLinks>false</detectOfflineLinks>
+ </configuration>
+ <executions>
+ <execution>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <!-- Java servlet API -->
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Guacamole Java API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <version>0.8.0</version>
+ <scope>compile</scope>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractConnection.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractConnection.java
new file mode 100644
index 0000000..e08bdc6
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractConnection.java
@@ -0,0 +1,119 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+
+/**
+ * Basic implementation of a Guacamole connection.
+ *
+ * @author Michael Jumper
+ */
+public abstract class AbstractConnection implements Connection {
+
+ /**
+ * The name associated with this connection.
+ */
+ private String name;
+
+ /**
+ * The unique identifier associated with this connection.
+ */
+ private String identifier;
+
+ /**
+ * The GuacamoleConfiguration associated with this connection.
+ */
+ private GuacamoleConfiguration configuration;
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String getIdentifier() {
+ return identifier;
+ }
+
+ @Override
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ @Override
+ public GuacamoleConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ @Override
+ public void setConfiguration(GuacamoleConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ @Override
+ public int hashCode() {
+ if (identifier == null) return 0;
+ return identifier.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or not a Connection
+ if (obj == null) return false;
+ if (!(obj instanceof AbstractConnection)) return false;
+
+ // Get identifier
+ String objIdentifier = ((AbstractConnection) obj).identifier;
+
+ // If null, equal only if this identifier is null
+ if (objIdentifier == null) return identifier == null;
+
+ // Otherwise, equal only if strings are identical
+ return objIdentifier.equals(identifier);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractConnectionGroup.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractConnectionGroup.java
new file mode 100644
index 0000000..c9b3d31
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractConnectionGroup.java
@@ -0,0 +1,117 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): James Muehlner
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * Basic implementation of a Guacamole connection group.
+ *
+ * @author James Muehlner
+ */
+public abstract class AbstractConnectionGroup implements ConnectionGroup {
+
+ /**
+ * The name associated with this connection group.
+ */
+ private String name;
+
+ /**
+ * The unique identifier associated with this connection group.
+ */
+ private String identifier;
+
+ /**
+ * The type of this connection group.
+ */
+ private ConnectionGroup.Type type;
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String getIdentifier() {
+ return identifier;
+ }
+
+ @Override
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ @Override
+ public ConnectionGroup.Type getType() {
+ return type;
+ }
+
+ @Override
+ public void setType(ConnectionGroup.Type type) {
+ this.type = type;
+ }
+
+ @Override
+ public int hashCode() {
+ if (identifier == null) return 0;
+ return identifier.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or not a ConnectionGroup
+ if (obj == null) return false;
+ if (!(obj instanceof AbstractConnectionGroup)) return false;
+
+ // Get identifier
+ String objIdentifier = ((AbstractConnectionGroup) obj).identifier;
+
+ // If null, equal only if this identifier is null
+ if (objIdentifier == null) return identifier == null;
+
+ // Otherwise, equal only if strings are identical
+ return objIdentifier.equals(identifier);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractUser.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractUser.java
new file mode 100644
index 0000000..04d0f2f
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AbstractUser.java
@@ -0,0 +1,105 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * Basic implementation of a Guacamole user which uses the username to
+ * determine equality. Username comparison is case-sensitive.
+ *
+ * @author Michael Jumper
+ */
+public abstract class AbstractUser implements User {
+
+ /**
+ * The name of this user.
+ */
+ private String username;
+
+ /**
+ * This user's password. Note that while this provides a means for the
+ * password to be set, the data stored in this String is not necessarily
+ * the user's actual password. It may be hashed, it may be arbitrary.
+ */
+ private String password;
+
+ @Override
+ public String getUsername() {
+ return username;
+ }
+
+ @Override
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ @Override
+ public String getPassword() {
+ return password;
+ }
+
+ @Override
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ @Override
+ public int hashCode() {
+ if (username == null) return 0;
+ return username.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or not a User
+ if (obj == null) return false;
+ if (!(obj instanceof AbstractUser)) return false;
+
+ // Get username
+ String objUsername = ((AbstractUser) obj).username;
+
+ // If null, equal only if this username is null
+ if (objUsername == null) return username == null;
+
+ // Otherwise, equal only if strings are identical
+ return objUsername.equals(username);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AuthenticationProvider.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AuthenticationProvider.java
new file mode 100644
index 0000000..547628e
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/AuthenticationProvider.java
@@ -0,0 +1,86 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+
+
+/**
+ * Provides means of accessing and managing the available
+ * GuacamoleConfiguration objects and User objects. Access to each configuration
+ * and each user is limited by a given Credentials object.
+ *
+ * @author Michael Jumper
+ */
+public interface AuthenticationProvider {
+
+ /**
+ * Returns the UserContext of the user authorized by the given credentials.
+ *
+ * @param credentials The credentials to use to retrieve the environment.
+ * @return The UserContext of the user authorized by the given credentials,
+ * or null if the credentials are not authorized.
+ *
+ * @throws GuacamoleException If an error occurs while creating the
+ * UserContext.
+ */
+ UserContext getUserContext(Credentials credentials)
+ throws GuacamoleException;
+
+ /**
+ * Returns a new or updated UserContext for the user authorized by the
+ * give credentials and having the given existing UserContext. Note that
+ * because this function will be called for all future requests after
+ * initial authentication, including tunnel requests, care must be taken
+ * to avoid using functions of HttpServletRequest which invalidate the
+ * entire request body, such as getParameter().
+ *
+ * @param context The existing UserContext belonging to the user in
+ * question.
+ * @param credentials The credentials to use to retrieve or update the
+ * environment.
+ * @return The updated UserContext, which need not be the same as the
+ * UserContext given, or null if the user is no longer authorized.
+ *
+ * @throws GuacamoleException If an error occurs while updating the
+ * UserContext.
+ */
+ UserContext updateUserContext(UserContext context, Credentials credentials)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Connection.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Connection.java
new file mode 100644
index 0000000..42bdd39
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Connection.java
@@ -0,0 +1,131 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.List;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+
+/**
+ * Represents a pairing of a GuacamoleConfiguration with a unique,
+ * human-readable identifier, and abstracts the connection process. The
+ * backing GuacamoleConfiguration may be intentionally obfuscated or tokenized
+ * to protect sensitive configuration information.
+ *
+ * @author Michael Jumper
+ */
+public interface Connection {
+
+ /**
+ * Returns the name assigned to this Connection.
+ * @return The name assigned to this Connection.
+ */
+ public String getName();
+
+ /**
+ * Sets the name assigned to this Connection.
+ *
+ * @param identifier The name to assign.
+ */
+ public void setName(String name);
+
+ /**
+ * Returns the unique identifier assigned to this Connection.
+ * @return The unique identifier assigned to this Connection.
+ */
+ public String getIdentifier();
+
+ /**
+ * Sets the identifier assigned to this Connection.
+ *
+ * @param identifier The identifier to assign.
+ */
+ public void setIdentifier(String identifier);
+
+ /**
+ * Returns the GuacamoleConfiguration associated with this Connection. Note
+ * that because configurations may contain sensitive information, some data
+ * in this configuration may be omitted or tokenized.
+ *
+ * @return The GuacamoleConfiguration associated with this Connection.
+ */
+ public GuacamoleConfiguration getConfiguration();
+
+ /**
+ * Sets the GuacamoleConfiguration associated with this Connection.
+ *
+ * @param config The GuacamoleConfiguration to associate with this
+ * Connection.
+ */
+ public void setConfiguration(GuacamoleConfiguration config);
+
+ /**
+ * Establishes a connection to guacd using the GuacamoleConfiguration
+ * associated with this Connection, and returns the resulting, connected
+ * GuacamoleSocket. The GuacamoleSocket will be pre-configured and will
+ * already have passed the handshake stage.
+ *
+ * @param info Information associated with the connecting client.
+ * @return A fully-established GuacamoleSocket.
+ *
+ * @throws GuacamoleException If an error occurs while connecting to guacd,
+ * or if permission to connect is denied.
+ */
+ public GuacamoleSocket connect(GuacamoleClientInformation info)
+ throws GuacamoleException;
+
+ /**
+ * Returns a list of ConnectionRecords representing the usage history
+ * of this Connection, including any active users. ConnectionRecords
+ * in this list will be sorted in descending order of end time (active
+ * connections are first), and then in descending order of start time
+ * (newer connections are first).
+ *
+ * @return A list of ConnectionRecrods representing the usage history
+ * of this Connection.
+ *
+ * @throws GuacamoleException If an error occurs while reading the history
+ * of this connection, or if permission is
+ * denied.
+ */
+ public List<? extends ConnectionRecord> getHistory() throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/ConnectionGroup.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/ConnectionGroup.java
new file mode 100644
index 0000000..35bc4b9
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/ConnectionGroup.java
@@ -0,0 +1,138 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): James Muehlner
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+
+
+/**
+ * Represents a connection group, which can contain both other connection groups
+ * as well as connections.
+ *
+ * @author James Muehlner
+ */
+public interface ConnectionGroup {
+
+ public enum Type {
+ ORGANIZATIONAL, BALANCING
+ };
+
+ /**
+ * Returns the name assigned to this ConnectionGroup.
+ * @return The name assigned to this ConnectionGroup.
+ */
+ public String getName();
+
+ /**
+ * Sets the name assigned to this ConnectionGroup.
+ *
+ * @param identifier The name to assign.
+ */
+ public void setName(String name);
+
+ /**
+ * Returns the unique identifier assigned to this ConnectionGroup.
+ * @return The unique identifier assigned to this ConnectionGroup.
+ */
+ public String getIdentifier();
+
+ /**
+ * Sets the identifier assigned to this ConnectionGroup.
+ *
+ * @param identifier The identifier to assign.
+ */
+ public void setIdentifier(String identifier);
+
+ /**
+ * Set the type of this ConnectionGroup.
+ *
+ * @param type The type of this ConnectionGroup.
+ */
+ public void setType(Type type);
+
+ /**
+ * Returns the type of this connection.
+ * @return the type of this connection.
+ */
+ public Type getType();
+
+ /**
+ * Retrieves a Directory which can be used to view and manipulate
+ * connections and their configurations, but only as allowed by the
+ * permissions given to the user.
+ *
+ * @return A Directory whose operations are bound by the permissions of
+ * the user.
+ *
+ * @throws GuacamoleException If an error occurs while creating the
+ * Directory.
+ */
+ Directory<String, Connection> getConnectionDirectory()
+ throws GuacamoleException;
+
+ /**
+ * Retrieves a Directory which can be used to view and manipulate
+ * connection groups and their members, but only as allowed by the
+ * permissions given to the user.
+ *
+ * @return A Directory whose operations are bound by the permissions of
+ * the user.
+ *
+ * @throws GuacamoleException If an error occurs while creating the
+ * Directory.
+ */
+ Directory<String, ConnectionGroup> getConnectionGroupDirectory()
+ throws GuacamoleException;
+
+ /**
+ * Establishes a connection to guacd using a connection chosen from among
+ * the connections in this ConnectionGroup, and returns the resulting,
+ * connected GuacamoleSocket.
+ *
+ * @param info Information associated with the connecting client.
+ * @return A fully-established GuacamoleSocket.
+ *
+ * @throws GuacamoleException If an error occurs while connecting to guacd,
+ * or if permission to connect is denied.
+ */
+ public GuacamoleSocket connect(GuacamoleClientInformation info)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/ConnectionRecord.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/ConnectionRecord.java
new file mode 100644
index 0000000..5284560
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/ConnectionRecord.java
@@ -0,0 +1,83 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth-mock.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Date;
+
+/**
+ * A logging record describing when a user started and ended usage of a
+ * particular connection.
+ *
+ * @author Michael Jumper
+ */
+public interface ConnectionRecord {
+
+ /**
+ * Returns the date and time the connection began.
+ *
+ * @return The date and time the connection began.
+ */
+ public Date getStartDate();
+
+ /**
+ * Returns the date and time the connection ended, if applicable.
+ *
+ * @return The date and time the connection ended, or null if the
+ * connection is still running or if the end time is unknown.
+ */
+ public Date getEndDate();
+
+ /**
+ * Returns the name of the user who used or is using the connection at the
+ * times given by this connection record.
+ *
+ * @return The name of the user who used or is using the associated
+ * connection.
+ */
+ public String getUsername();
+
+ /**
+ * Returns whether the connection associated with this record is still
+ * active.
+ *
+ * @return true if the connection associated with this record is still
+ * active, false otherwise.
+ */
+ public boolean isActive();
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Credentials.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Credentials.java
new file mode 100644
index 0000000..63b5e89
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Credentials.java
@@ -0,0 +1,152 @@
+package org.glyptodon.guacamole.net.auth;
+
+import java.io.Serializable;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Simple arbitrary set of credentials, including a username/password pair,
+ * the HttpServletRequest associated with the request for authorization
+ * (if any) and the HttpSession associated with that request.
+ *
+ * This class is used along with AuthenticationProvider to provide arbitrary
+ * HTTP-based authentication for Guacamole.
+ *
+ * @author Michael Jumper
+ */
+public class Credentials implements Serializable {
+
+ /**
+ * Unique identifier associated with this specific version of Credentials.
+ */
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * An arbitrary username.
+ */
+ private String username;
+
+ /**
+ * An arbitrary password.
+ */
+ private String password;
+
+ /**
+ * The HttpServletRequest carrying additional credentials, if any.
+ */
+ private transient HttpServletRequest request;
+
+ /**
+ * The HttpSession carrying additional credentials, if any.
+ */
+ private transient HttpSession session;
+
+ /**
+ * Returns the password associated with this set of credentials.
+ * @return The password associated with this username/password pair, or
+ * null if no password has been set.
+ */
+ public String getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the password associated with this set of credentials.
+ * @param password The password to associate with this username/password
+ * pair.
+ */
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ /**
+ * Returns the username associated with this set of credentials.
+ * @return The username associated with this username/password pair, or
+ * null if no username has been set.
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * Sets the username associated with this set of credentials.
+ * @param username The username to associate with this username/password
+ * pair.
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ /**
+ * Returns the HttpServletRequest associated with this set of credentials.
+ * @return The HttpServletRequest associated with this set of credentials,
+ * or null if no such request exists.
+ */
+ public HttpServletRequest getRequest() {
+ return request;
+ }
+
+ /**
+ * Sets the HttpServletRequest associated with this set of credentials.
+ * @param request The HttpServletRequest to associated with this set of
+ * credentials.
+ */
+ public void setRequest(HttpServletRequest request) {
+ this.request = request;
+ }
+
+ /**
+ * Returns the HttpSession associated with this set of credentials.
+ * @return The HttpSession associated with this set of credentials, or null
+ * if no such request exists.
+ */
+ public HttpSession getSession() {
+ return session;
+ }
+
+ /**
+ * Sets the HttpSession associated with this set of credentials.
+ * @param session The HttpSession to associated with this set of
+ * credentials.
+ */
+ public void setSession(HttpSession session) {
+ this.session = session;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Directory.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Directory.java
new file mode 100644
index 0000000..95866e8
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/Directory.java
@@ -0,0 +1,129 @@
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+
+
+/**
+ * Provides access to a collection of all objects with associated identifiers,
+ * and allows user manipulation and removal. Objects stored within a
+ * Directory are not necessarily returned to the use as references to
+ * the stored objects, thus updating an object requires calling an update
+ * function.
+ *
+ * @author Michael Jumper
+ * @param <IdentifierType> The type of identifier used to identify objects
+ * stored within this Directory.
+ * @param <ObjectType> The type of objects stored within this Directory.
+ */
+public interface Directory<IdentifierType, ObjectType> {
+
+ /**
+ * Returns the object having the given identifier. Note that changes to
+ * the object returned will not necessarily affect the object stored within
+ * the Directory. To update an object stored within an
+ * Directory such that future calls to get() will return the updated
+ * object, you must call update() on the object after modification.
+ *
+ * @param identifier The identifier to use when locating the object to
+ * return.
+ * @return The object having the given identifier, or null if no such object
+ * exists.
+ *
+ * @throws GuacamoleException If an error occurs while retrieving the
+ * object, or if permission for retrieving the
+ * object is denied.
+ */
+ ObjectType get(IdentifierType identifier) throws GuacamoleException;
+
+ /**
+ * Returns a Set containing all identifiers for all objects within this
+ * Directory.
+ *
+ * @return A Set of all identifiers.
+ * @throws GuacamoleException If an error occurs while retrieving
+ * the identifiers.
+ */
+ Set<IdentifierType> getIdentifiers() throws GuacamoleException;
+
+ /**
+ * Adds the given object to the overall set.
+ *
+ * @param object The object to add.
+ *
+ * @throws GuacamoleException If an error occurs while adding the object , or
+ * if adding the object is not allowed.
+ */
+ void add(ObjectType object)
+ throws GuacamoleException;
+
+ /**
+ * Updates the stored object with the data contained in the given object.
+ *
+ * @param object The object which will supply the data for the update.
+ *
+ * @throws GuacamoleException If an error occurs while updating the object,
+ * or if updating the object is not allowed.
+ */
+ void update(ObjectType object)
+ throws GuacamoleException;
+
+ /**
+ * Removes the object with the given identifier from the overall set.
+ *
+ * @param identifier The identifier of the object to remove.
+ *
+ * @throws GuacamoleException If an error occurs while removing the object,
+ * or if removing object is not allowed.
+ */
+ void remove(IdentifierType identifier) throws GuacamoleException;
+
+ /**
+ * Moves the object with the given identifier to the given directory.
+ *
+ * @param identifier The identifier of the object to remove.
+ * @param directory The directory to move the object to.
+ *
+ * @throws GuacamoleException If an error occurs while moving the object,
+ * or if moving object is not allowed.
+ */
+ void move(IdentifierType identifier, Directory<IdentifierType, ObjectType> directory)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/User.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/User.java
new file mode 100644
index 0000000..6e792c6
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/User.java
@@ -0,0 +1,129 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * A user of the Guacamole web application.
+ *
+ * @author Michael Jumper
+ */
+public interface User {
+
+ /**
+ * Returns the name of this user, which must be unique across all users.
+ *
+ * @return The name of this user.
+ */
+ public String getUsername();
+
+ /**
+ * Sets the name of this user, which must be unique across all users.
+ *
+ * @param username The name of this user.
+ */
+ public void setUsername(String username);
+
+ /**
+ * Returns this user's password. Note that the password returned may be
+ * hashed or completely arbitrary.
+ *
+ * @return A String which may (or may not) be the user's password.
+ */
+ public String getPassword();
+
+ /**
+ * Sets this user's password. Note that while this function is guaranteed
+ * to change the password of this User object, there is no guarantee that
+ * getPassword() will return the value given to setPassword().
+ *
+ * @param password The password to set.
+ */
+ public void setPassword(String password);
+
+ /**
+ * Lists all permissions given to this user.
+ *
+ * @return A Set of all permissions granted to this user.
+ *
+ * @throws GuacamoleException If an error occurs while retrieving
+ * permissions, or if reading all permissions
+ * is not allowed.
+ */
+ Set<Permission> getPermissions() throws GuacamoleException;
+
+ /**
+ * Tests whether this user has the specified permission.
+ *
+ * @param permission The permission to check.
+ * @return true if the permission is granted to this user, false otherwise.
+ *
+ * @throws GuacamoleException If an error occurs while checking permissions,
+ * or if permissions cannot be checked due to
+ * lack of permissions to do so.
+ */
+ boolean hasPermission(Permission permission) throws GuacamoleException;
+
+ /**
+ * Adds the specified permission to this user.
+ *
+ * @param permission The permission to add.
+ *
+ * @throws GuacamoleException If an error occurs while adding the
+ * permission. or if permission to add
+ * permissions is denied.
+ */
+ void addPermission(Permission permission) throws GuacamoleException;
+
+ /**
+ * Removes the specified permission from this specified user.
+ *
+ * @param permission The permission to remove.
+ *
+ * @throws GuacamoleException If an error occurs while removing the
+ * permission. or if permission to remove
+ * permissions is denied.
+ */
+ void removePermission(Permission permission) throws GuacamoleException;
+
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/UserContext.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/UserContext.java
new file mode 100644
index 0000000..efb7431
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/UserContext.java
@@ -0,0 +1,86 @@
+
+package org.glyptodon.guacamole.net.auth;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): James Muehlner
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+
+/**
+ * The context of an active user. The functions of this class enforce all
+ * permissions and act only within the rights of the associated user.
+ *
+ * @author Michael Jumper
+ */
+public interface UserContext {
+
+ /**
+ * Returns the User whose access rights control the operations of this
+ * UserContext.
+ *
+ * @return The User whose access rights control the operations of this
+ * UserContext.
+ */
+ User self();
+
+ /**
+ * Retrieves a Directory which can be used to view and manipulate other
+ * users, but only as allowed by the permissions given to the user of this
+ * UserContext.
+ *
+ * @return A Directory whose operations are bound by the restrictions
+ * of this UserContext.
+ *
+ * @throws GuacamoleException If an error occurs while creating the
+ * Directory.
+ */
+ Directory<String, User> getUserDirectory() throws GuacamoleException;
+
+
+ /**
+ * Retrieves a connection group which can be used to view and manipulate
+ * connections, but only as allowed by the permissions given to the user of
+ * this UserContext.
+ *
+ * @return A connection group whose operations are bound by the restrictions
+ * of this UserContext.
+ *
+ * @throws GuacamoleException If an error occurs while creating the
+ * Directory.
+ */
+ ConnectionGroup getRootConnectionGroup() throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/package-info.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/package-info.java
new file mode 100644
index 0000000..7633ebb
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Provides classes which can be used to extend or replace the authentication
+ * functionality of the Guacamole web application.
+ */
+package org.glyptodon.guacamole.net.auth;
+
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ConnectionGroupPermission.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ConnectionGroupPermission.java
new file mode 100644
index 0000000..377cdbc
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ConnectionGroupPermission.java
@@ -0,0 +1,121 @@
+
+package org.glyptodon.guacamole.net.auth.permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): James Muehlner
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * A permission which controls operations that directly affect a specific
+ * ConnectionGroup. Note that this permission only refers to the
+ * ConnectionGroup by its identifier. The actual ConnectionGroup
+ * is not stored within.
+ *
+ * @author James Muehlner
+ */
+public class ConnectionGroupPermission
+ implements ObjectPermission<String> {
+
+ /**
+ * The identifier of the GuacamoleConfiguration associated with the
+ * operation affected by this permission.
+ */
+ private String identifier;
+
+ /**
+ * The type of operation affected by this permission.
+ */
+ private ObjectPermission.Type type;
+
+ /**
+ * Creates a new ConnectionGroupPermission having the given type
+ * and identifier. The identifier must be the unique identifier assigned
+ * to the ConnectionGroup by the AuthenticationProvider in use.
+ *
+ * @param type The type of operation affected by this permission.
+ * @param identifier The identifier of the ConnectionGroup associated
+ * with the operation affected by this permission.
+ */
+ public ConnectionGroupPermission(ObjectPermission.Type type, String identifier) {
+
+ this.identifier = identifier;
+ this.type = type;
+
+ }
+
+ @Override
+ public String getObjectIdentifier() {
+ return identifier;
+ }
+
+ @Override
+ public ObjectPermission.Type getType() {
+ return type;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 5;
+ if (identifier != null) hash = 47 * hash + identifier.hashCode();
+ if (type != null) hash = 47 * hash + type.hashCode();
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or wrong type
+ if (obj == null) return false;
+ if (getClass() != obj.getClass()) return false;
+
+ final ConnectionGroupPermission other =
+ (ConnectionGroupPermission) obj;
+
+ // Not equal if different type
+ if (this.type != other.type)
+ return false;
+
+ // If null identifier, equality depends on whether other identifier
+ // is null
+ if (identifier == null)
+ return other.identifier == null;
+
+ // Otherwise, equality depends entirely on identifier
+ return identifier.equals(other.identifier);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ConnectionPermission.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ConnectionPermission.java
new file mode 100644
index 0000000..7b0c267
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ConnectionPermission.java
@@ -0,0 +1,121 @@
+
+package org.glyptodon.guacamole.net.auth.permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * A permission which controls operations that directly affect a specific
+ * GuacamoleConfiguration. Note that this permission only refers to the
+ * GuacamoleConfiguration by its identifier. The actual GuacamoleConfiguration
+ * is not stored within.
+ *
+ * @author Michael Jumper
+ */
+public class ConnectionPermission
+ implements ObjectPermission<String> {
+
+ /**
+ * The identifier of the GuacamoleConfiguration associated with the
+ * operation affected by this permission.
+ */
+ private String identifier;
+
+ /**
+ * The type of operation affected by this permission.
+ */
+ private Type type;
+
+ /**
+ * Creates a new ConnectionPermission having the given type
+ * and identifier. The identifier must be the unique identifier assigned
+ * to the GuacamoleConfiguration by the AuthenticationProvider in use.
+ *
+ * @param type The type of operation affected by this permission.
+ * @param identifier The identifier of the GuacamoleConfiguration associated
+ * with the operation affected by this permission.
+ */
+ public ConnectionPermission(Type type, String identifier) {
+
+ this.identifier = identifier;
+ this.type = type;
+
+ }
+
+ @Override
+ public String getObjectIdentifier() {
+ return identifier;
+ }
+
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 5;
+ if (identifier != null) hash = 47 * hash + identifier.hashCode();
+ if (type != null) hash = 47 * hash + type.hashCode();
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or wrong type
+ if (obj == null) return false;
+ if (getClass() != obj.getClass()) return false;
+
+ final ConnectionPermission other =
+ (ConnectionPermission) obj;
+
+ // Not equal if different type
+ if (this.type != other.type)
+ return false;
+
+ // If null identifier, equality depends on whether other identifier
+ // is null
+ if (identifier == null)
+ return other.identifier == null;
+
+ // Otherwise, equality depends entirely on identifier
+ return identifier.equals(other.identifier);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ObjectPermission.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ObjectPermission.java
new file mode 100644
index 0000000..045f1c4
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/ObjectPermission.java
@@ -0,0 +1,87 @@
+
+package org.glyptodon.guacamole.net.auth.permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * A permission which affects a specific object, rather than the system as a
+ * whole.
+ *
+ * @author Michael Jumper
+ * @param <T> The type of identifier used by the object this permission affects.
+ */
+public interface ObjectPermission<T> extends Permission<ObjectPermission.Type> {
+
+ /**
+ * Specific types of object-level permissions. Each permission type is
+ * related to a specific class of object-level operation.
+ */
+ public enum Type {
+
+ /**
+ * Read data within an object.
+ */
+ READ,
+
+ /**
+ * Update data within an object.
+ */
+ UPDATE,
+
+ /**
+ * Delete an object.
+ */
+ DELETE,
+
+ /**
+ * Change who has access to an object.
+ */
+ ADMINISTER
+
+ }
+
+ /**
+ * Returns the identifier of the specific object affected by this
+ * permission.
+ *
+ * @return The identifier of the specific object affected by this
+ * permission.
+ */
+ public T getObjectIdentifier();
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/Permission.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/Permission.java
new file mode 100644
index 0000000..dcd18dd
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/Permission.java
@@ -0,0 +1,57 @@
+
+package org.glyptodon.guacamole.net.auth.permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * A permission which affects a specific type of operation, where all available
+ * operation types are defined by an enumeration.
+ *
+ * @author Michael Jumper
+ * @param <Type> The enumeration of all available operation types that this
+ * permission can affect.
+ */
+public interface Permission<Type extends Enum> {
+
+ /**
+ * Returns the type of operation affected by this permission.
+ * @return The type of operation affected by this permission.
+ */
+ public Type getType();
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/SystemPermission.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/SystemPermission.java
new file mode 100644
index 0000000..bc64785
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/SystemPermission.java
@@ -0,0 +1,120 @@
+
+package org.glyptodon.guacamole.net.auth.permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * A permission which affects the system as a whole, rather than an individual
+ * object.
+ *
+ * @author Michael Jumper
+ */
+public class SystemPermission implements Permission<SystemPermission.Type> {
+
+ /**
+ * Specific types of system-level permissions. Each permission type is
+ * related to a specific class of system-level operation.
+ */
+ public enum Type {
+
+ /**
+ * Create users.
+ */
+ CREATE_USER,
+
+ /**
+ * Create connections.
+ */
+ CREATE_CONNECTION,
+
+ /**
+ * Create connection groups.
+ */
+ CREATE_CONNECTION_GROUP,
+
+ /**
+ * Administer the system in general, including adding permissions
+ * which affect the system (like user creation, connection creation,
+ * and system administration).
+ */
+ ADMINISTER
+
+ }
+
+ /**
+ * The type of operation affected by this permission.
+ */
+ private Type type;
+
+ /**
+ * Creates a new SystemPermission with the given
+ * type.
+ *
+ * @param type The type of operation controlled by this permission.
+ */
+ public SystemPermission(Type type) {
+ this.type = type;
+ }
+
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Override
+ public int hashCode() {
+ return type.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or wrong type
+ if (obj == null) return false;
+ if (getClass() != obj.getClass()) return false;
+
+ final SystemPermission other = (SystemPermission) obj;
+
+ // Compare types
+ if (type != other.type)
+ return false;
+
+ return true;
+ }
+
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/UserPermission.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/UserPermission.java
new file mode 100644
index 0000000..5266d40
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/UserPermission.java
@@ -0,0 +1,116 @@
+
+package org.glyptodon.guacamole.net.auth.permission;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+
+/**
+ * A permission which controls operations that directly affect a specific
+ * User.
+ *
+ * @author Michael Jumper
+ */
+public class UserPermission implements ObjectPermission<String> {
+
+ /**
+ * The username of the User associated with the operation affected by this
+ * permission.
+ */
+ private String identifier;
+
+ /**
+ * The type of operation affected by this permission.
+ */
+ private Type type;
+
+ /**
+ * Creates a new UserPermission having the given type and identifier. The
+ * identifier must be the user's username.
+ *
+ * @param type The type of operation affected by this permission.
+ * @param identifier The username of the User associated with the operation
+ * affected by this permission.
+ */
+ public UserPermission(Type type, String identifier) {
+
+ this.identifier = identifier;
+ this.type = type;
+
+ }
+
+ @Override
+ public String getObjectIdentifier() {
+ return identifier;
+ }
+
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 5;
+ if (identifier != null) hash = 47 * hash + identifier.hashCode();
+ if (type != null) hash = 47 * hash + type.hashCode();
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ // Not equal if null or wrong type
+ if (obj == null) return false;
+ if (getClass() != obj.getClass()) return false;
+
+ final UserPermission other = (UserPermission) obj;
+
+ // Not equal if different type
+ if (this.type != other.type)
+ return false;
+
+ // If null identifier, equality depends on whether other identifier
+ // is null
+ if (identifier == null)
+ return other.identifier == null;
+
+ // Otherwise, equality depends entirely on identifier
+ return identifier.equals(other.identifier);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/package-info.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/package-info.java
new file mode 100644
index 0000000..aed3059
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/permission/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Provides classes which describe the various permissions a Guacamole user
+ * can be granted.
+ */
+package org.glyptodon.guacamole.net.auth.permission;
+
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleAuthenticationProvider.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleAuthenticationProvider.java
new file mode 100644
index 0000000..548713a
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleAuthenticationProvider.java
@@ -0,0 +1,105 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Map;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.AuthenticationProvider;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+
+/**
+ * Provides means of retrieving a set of named GuacamoleConfigurations for a
+ * given Credentials object. This is a simple AuthenticationProvider
+ * implementation intended to be easily extended. It is useful for simple
+ * authentication situations where access to web-based administration and
+ * complex users and permissions are not required.
+ *
+ * The interface provided by SimpleAuthenticationProvider is similar to that of
+ * the AuthenticationProvider interface of older Guacamole releases.
+ *
+ * @author Michael Jumper
+ */
+public abstract class SimpleAuthenticationProvider
+ implements AuthenticationProvider {
+
+ /**
+ * Given an arbitrary credentials object, returns a Map containing all
+ * configurations authorized by those credentials. The keys of this Map
+ * are Strings which uniquely identify each configuration.
+ *
+ * @param credentials The credentials to use to retrieve authorized
+ * configurations.
+ * @return A Map of all configurations authorized by the given credentials,
+ * or null if the credentials given are not authorized.
+ * @throws GuacamoleException If an error occurs while retrieving
+ * configurations.
+ */
+ public abstract Map<String, GuacamoleConfiguration>
+ getAuthorizedConfigurations(Credentials credentials)
+ throws GuacamoleException;
+
+ @Override
+ public UserContext getUserContext(Credentials credentials)
+ throws GuacamoleException {
+
+ // Get configurations
+ Map<String, GuacamoleConfiguration> configs =
+ getAuthorizedConfigurations(credentials);
+
+ // Return as unauthorized if not authorized to retrieve configs
+ if (configs == null)
+ return null;
+
+ // Return user context restricted to authorized configs
+ return new SimpleUserContext(configs);
+
+ }
+
+ @Override
+ public UserContext updateUserContext(UserContext context,
+ Credentials credentials) throws GuacamoleException {
+
+ // Simply return the given context, updating nothing
+ return context;
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnection.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnection.java
new file mode 100644
index 0000000..231bd57
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnection.java
@@ -0,0 +1,124 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Collections;
+import java.util.List;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.InetGuacamoleSocket;
+import org.glyptodon.guacamole.net.SSLGuacamoleSocket;
+import org.glyptodon.guacamole.net.auth.AbstractConnection;
+import org.glyptodon.guacamole.net.auth.ConnectionRecord;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.glyptodon.guacamole.protocol.ConfiguredGuacamoleSocket;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+
+/**
+ * An extremely basic Connection implementation.
+ *
+ * @author Michael Jumper
+ */
+public class SimpleConnection extends AbstractConnection {
+
+ /**
+ * Backing configuration, containing all sensitive information.
+ */
+ private GuacamoleConfiguration config;
+
+ /**
+ * Creates a completely uninitialized SimpleConnection.
+ */
+ public SimpleConnection() {
+ }
+
+ /**
+ * Creates a new SimpleConnection having the given identifier and
+ * GuacamoleConfiguration.
+ *
+ * @param name The name to associate with this connection.
+ * @param identifier The identifier to associate with this connection.
+ * @param config The configuration describing how to connect to this
+ * connection.
+ */
+ public SimpleConnection(String name, String identifier,
+ GuacamoleConfiguration config) {
+
+ // Set name
+ setName(name);
+
+ // Set identifier
+ setIdentifier(identifier);
+
+ // Set config
+ setConfiguration(config);
+ this.config = config;
+
+ }
+
+ @Override
+ public GuacamoleSocket connect(GuacamoleClientInformation info)
+ throws GuacamoleException {
+
+ // Get guacd connection parameters
+ String hostname = GuacamoleProperties.getProperty(GuacamoleProperties.GUACD_HOSTNAME);
+ int port = GuacamoleProperties.getProperty(GuacamoleProperties.GUACD_PORT);
+
+ // If guacd requires SSL, use it
+ if (GuacamoleProperties.getProperty(GuacamoleProperties.GUACD_SSL, false))
+ return new ConfiguredGuacamoleSocket(
+ new SSLGuacamoleSocket(hostname, port),
+ config, info
+ );
+
+ // Return connected socket
+ return new ConfiguredGuacamoleSocket(
+ new InetGuacamoleSocket(hostname, port),
+ config, info
+ );
+
+ }
+
+ @Override
+ public List<ConnectionRecord> getHistory() throws GuacamoleException {
+ return Collections.EMPTY_LIST;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionDirectory.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionDirectory.java
new file mode 100644
index 0000000..af3af8b
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionDirectory.java
@@ -0,0 +1,138 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+
+/**
+ * An extremely simple read-only implementation of a Directory of
+ * GuacamoleConfigurations which provides access to a pre-defined Map of
+ * GuacamoleConfigurations.
+ *
+ * @author Michael Jumper
+ */
+public class SimpleConnectionDirectory
+ implements Directory<String, Connection> {
+
+ /**
+ * The Map of Connections to provide access to.
+ */
+ private Map<String, Connection> connections =
+ new HashMap<String, Connection>();
+
+ /**
+ * Creates a new SimpleConnectionDirectory which provides
+ * access to the configurations contained within the given Map.
+ *
+ * @param configs The Map of GuacamoleConfigurations to provide access to.
+ */
+ public SimpleConnectionDirectory(
+ Map<String, GuacamoleConfiguration> configs) {
+
+ // Create connections for each config
+ for (Entry<String, GuacamoleConfiguration> entry : configs.entrySet())
+ connections.put(entry.getKey(),
+ new SimpleConnection(entry.getKey(), entry.getKey(),
+ entry.getValue()));
+
+ }
+
+ @Override
+ public Connection get(String identifier)
+ throws GuacamoleException {
+ return connections.get(identifier);
+ }
+
+ @Override
+ public Set<String> getIdentifiers() throws GuacamoleException {
+ return connections.keySet();
+ }
+
+ @Override
+ public void add(Connection connection)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void update(Connection connection)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void remove(String identifier) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void move(String identifier, Directory<String, Connection> directory)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ /**
+ * An internal method for modifying the Connections in this Directory.
+ * Returns the previous connection for the given identifier, if found.
+ *
+ * @param connection The connection to add or update the Directory with.
+ * @return The previous connection for the connection identifier, if found.
+ */
+ public Connection putConnection(Connection connection) {
+ return connections.put(connection.getIdentifier(), connection);
+ }
+
+ /**
+ * An internal method for removing a Connection from this Directory.
+ * @param identifier The identifier of the Connection to remove.
+ * @return The previous connection for the given identifier, if found.
+ */
+ public Connection removeConnection(String identifier) {
+ return connections.remove(identifier);
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionGroup.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionGroup.java
new file mode 100644
index 0000000..6afd28f
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionGroup.java
@@ -0,0 +1,119 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): James Muehlner
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.auth.AbstractConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+
+
+/**
+ * An extremely simple read-only implementation of a ConnectionGroup which
+ * returns the connection and connection group directories it was constructed
+ * with. Load balancing across this connection group is not allowed.
+ *
+ * @author James Muehlner
+ */
+public class SimpleConnectionGroup extends AbstractConnectionGroup {
+
+ /**
+ * Underlying connection directory, containing all connections within this
+ * group.
+ */
+ private final Directory<String, Connection> connectionDirectory;
+
+ /**
+ * Underlying connection group directory, containing all connections within
+ * this group.
+ */
+ private final Directory<String, ConnectionGroup> connectionGroupDirectory;
+
+ /**
+ * Creates a new SimpleConnectionGroup having the given name and identifier
+ * which will expose the given directories as its contents.
+ *
+ * @param name The name to associate with this connection.
+ * @param identifier The identifier to associate with this connection.
+ * @param connectionDirectory The connection directory to expose when
+ * requested.
+ * @param connectionGroupDirectory The connection group directory to expose
+ * when requested.
+ */
+ public SimpleConnectionGroup(String name, String identifier,
+ Directory<String, Connection> connectionDirectory,
+ Directory<String, ConnectionGroup> connectionGroupDirectory) {
+
+ // Set name
+ setName(name);
+
+ // Set identifier
+ setIdentifier(identifier);
+
+ // Set group type
+ setType(ConnectionGroup.Type.ORGANIZATIONAL);
+
+ // Assign directories
+ this.connectionDirectory = connectionDirectory;
+ this.connectionGroupDirectory = connectionGroupDirectory;
+
+ }
+
+ @Override
+ public Directory<String, Connection> getConnectionDirectory()
+ throws GuacamoleException {
+ return connectionDirectory;
+ }
+
+ @Override
+ public Directory<String, ConnectionGroup> getConnectionGroupDirectory()
+ throws GuacamoleException {
+ return connectionGroupDirectory;
+ }
+
+ @Override
+ public GuacamoleSocket connect(GuacamoleClientInformation info)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionGroupDirectory.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionGroupDirectory.java
new file mode 100644
index 0000000..ce46428
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleConnectionGroupDirectory.java
@@ -0,0 +1,138 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): James Muehlner
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+
+
+/**
+ * An extremely simple read-only implementation of a Directory of
+ * ConnectionGroup which provides which provides access to a pre-defined
+ * Collection of ConnectionGroups.
+ *
+ * @author James Muehlner
+ */
+public class SimpleConnectionGroupDirectory
+ implements Directory<String, ConnectionGroup> {
+
+ /**
+ * The Map of ConnectionGroups to provide access to.
+ */
+ private Map<String, ConnectionGroup> connectionGroups =
+ new HashMap<String, ConnectionGroup>();
+
+ /**
+ * Creates a new SimpleConnectionGroupDirectory which contains the given
+ * groups.
+ *
+ * @param groups A Collection of all groups that should be present in this
+ * connection group directory.
+ */
+ public SimpleConnectionGroupDirectory(Collection<ConnectionGroup> groups) {
+
+ // Add all given groups
+ for (ConnectionGroup group : groups)
+ connectionGroups.put(group.getIdentifier(), group);
+
+ }
+
+ @Override
+ public ConnectionGroup get(String identifier)
+ throws GuacamoleException {
+ return connectionGroups.get(identifier);
+ }
+
+ @Override
+ public Set<String> getIdentifiers() throws GuacamoleException {
+ return connectionGroups.keySet();
+ }
+
+ @Override
+ public void add(ConnectionGroup connectionGroup)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void update(ConnectionGroup connectionGroup)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void remove(String identifier) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void move(String identifier, Directory<String, ConnectionGroup> directory)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ /**
+ * An internal method for modifying the ConnectionGroups in this Directory.
+ * Returns the previous connection group for the given identifier, if found.
+ *
+ * @param connectionGroup The connection group to add or update the
+ * Directory with.
+ * @return The previous connection group for the connection group
+ * identifier, if found.
+ */
+ public ConnectionGroup putConnectionGroup(ConnectionGroup connectionGroup) {
+ return connectionGroups.put(connectionGroup.getIdentifier(), connectionGroup);
+ }
+
+ /**
+ * An internal method for removing a ConnectionGroup from this Directory.
+ *
+ * @param identifier The identifier of the ConnectionGroup to remove.
+ * @return The previous connection group for the given identifier, if found.
+ */
+ public ConnectionGroup removeConnectionGroup(String identifier) {
+ return connectionGroups.remove(identifier);
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUser.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUser.java
new file mode 100644
index 0000000..4568e0f
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUser.java
@@ -0,0 +1,137 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.auth.AbstractUser;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionGroupPermission;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+
+/**
+ * An extremely basic User implementation.
+ *
+ * @author Michael Jumper
+ */
+public class SimpleUser extends AbstractUser {
+
+ /**
+ * The set of all permissions available to this user.
+ */
+ private Set<Permission> permissions = new HashSet<Permission>();
+
+ /**
+ * Creates a completely uninitialized SimpleUser.
+ */
+ public SimpleUser() {
+ }
+
+ /**
+ * Creates a new SimpleUser having the given username.
+ *
+ * @param username The username to assign to this SimpleUser.
+ * @param configs All configurations this user has read access to.
+ * @param groups All groups this user has read access to.
+ */
+ public SimpleUser(String username,
+ Map<String, GuacamoleConfiguration> configs,
+ Collection<ConnectionGroup> groups) {
+
+ // Set username
+ setUsername(username);
+
+ // Add connection permissions
+ for (String identifier : configs.keySet()) {
+
+ // Create permission
+ Permission permission = new ConnectionPermission(
+ ObjectPermission.Type.READ,
+ identifier
+ );
+
+ // Add to set
+ permissions.add(permission);
+
+ }
+
+ // Add group permissions
+ for (ConnectionGroup group : groups) {
+
+ // Create permission
+ Permission permission = new ConnectionGroupPermission(
+ ObjectPermission.Type.READ,
+ group.getIdentifier()
+ );
+
+ // Add to set
+ permissions.add(permission);
+
+ }
+
+ }
+
+ @Override
+ public Set<Permission> getPermissions() throws GuacamoleException {
+ return permissions;
+ }
+
+ @Override
+ public boolean hasPermission(Permission permission) throws GuacamoleException {
+ return permissions.contains(permission);
+ }
+
+ @Override
+ public void addPermission(Permission permission) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void removePermission(Permission permission) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUserContext.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUserContext.java
new file mode 100644
index 0000000..dd4d0dd
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUserContext.java
@@ -0,0 +1,115 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Collections;
+import java.util.Map;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+/**
+ * An extremely simple UserContext implementation which provides access to
+ * a defined and restricted set of GuacamoleConfigurations. Access to
+ * querying or modifying either users or permissions is denied.
+ *
+ * @author Michael Jumper
+ */
+public class SimpleUserContext implements UserContext {
+
+ /**
+ * Reference to the user whose permissions dictate the configurations
+ * accessible within this UserContext.
+ */
+ private final User self;
+
+ /**
+ * The Directory with access only to the User associated with this
+ * UserContext.
+ */
+ private final Directory<String, User> userDirectory;
+
+ /**
+ * The ConnectionGroup with access only to those Connections that the User
+ * associated with this UserContext has access to.
+ */
+ private final ConnectionGroup connectionGroup;
+
+ /**
+ * Creates a new SimpleUserContext which provides access to only those
+ * configurations within the given Map.
+ *
+ * @param configs A Map of all configurations for which the user associated
+ * with this UserContext has read access.
+ */
+ public SimpleUserContext(Map<String, GuacamoleConfiguration> configs) {
+
+ // Add root group that contains only configurations
+ this.connectionGroup = new SimpleConnectionGroup("ROOT", "ROOT",
+ new SimpleConnectionDirectory(configs),
+ new SimpleConnectionGroupDirectory(Collections.EMPTY_LIST));
+
+ // Build new user from credentials, giving the user an arbitrary name
+ this.self = new SimpleUser("user",
+ configs, Collections.singleton(connectionGroup));
+
+ // Create user directory for new user
+ this.userDirectory = new SimpleUserDirectory(self);
+
+ }
+
+ @Override
+ public User self() {
+ return self;
+ }
+
+ @Override
+ public Directory<String, User> getUserDirectory()
+ throws GuacamoleException {
+ return userDirectory;
+ }
+
+ @Override
+ public ConnectionGroup getRootConnectionGroup() throws GuacamoleException {
+ return connectionGroup;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUserDirectory.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUserDirectory.java
new file mode 100644
index 0000000..7937247
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/SimpleUserDirectory.java
@@ -0,0 +1,109 @@
+
+package org.glyptodon.guacamole.net.auth.simple;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-auth.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.util.Collections;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+
+
+/**
+ * An extremely simple read-only implementation of a Directory of Users which
+ * provides access to a single pre-defined User.
+ *
+ * @author Michael Jumper
+ */
+public class SimpleUserDirectory implements Directory<String, User> {
+
+ /**
+ * The only user to be contained within this directory.
+ */
+ private User user;
+
+ /**
+ * Creates a new SimpleUserDirectory which provides access to the single
+ * user provided.
+ *
+ * @param user The user to provide access to.
+ */
+ public SimpleUserDirectory(User user) {
+ this.user = user;
+ }
+
+ @Override
+ public User get(String username) throws GuacamoleException {
+
+ // If username matches, return the user
+ if (user.getUsername().equals(username))
+ return user;
+
+ // Otherwise, not found
+ return null;
+
+ }
+
+ @Override
+ public Set<String> getIdentifiers() throws GuacamoleException {
+ return Collections.singleton(user.getUsername());
+ }
+
+ @Override
+ public void add(User user) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void update(User user) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void remove(String username) throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+ @Override
+ public void move(String identifier, Directory<String, User> directory)
+ throws GuacamoleException {
+ throw new GuacamoleSecurityException("Permission denied.");
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/package-info.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/package-info.java
new file mode 100644
index 0000000..3da06ac
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/auth/simple/package-info.java
@@ -0,0 +1,8 @@
+
+/**
+ * Provides a basic AuthenticationProvider base class that can be used to create
+ * simple AuthenticationProviders in the same way allowed by the old
+ * authentication API.
+ */
+package org.glyptodon.guacamole.net.auth.simple;
+
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/AuthenticationFailureEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/AuthenticationFailureEvent.java
new file mode 100644
index 0000000..ddd5202
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/AuthenticationFailureEvent.java
@@ -0,0 +1,34 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.auth.Credentials;
+
+/**
+ * An event which is triggered whenever a user's credentials fail to be
+ * authenticated. The credentials that failed to be authenticated are included
+ * within this event, and can be retrieved using getCredentials().
+ *
+ * @author Michael Jumper
+ */
+public class AuthenticationFailureEvent implements CredentialEvent {
+
+ /**
+ * The credentials which failed authentication.
+ */
+ private Credentials credentials;
+
+ /**
+ * Creates a new AuthenticationFailureEvent which represents the failure
+ * to authenticate the given credentials.
+ *
+ * @param credentials The credentials which failed authentication.
+ */
+ public AuthenticationFailureEvent(Credentials credentials) {
+ this.credentials = credentials;
+ }
+
+ @Override
+ public Credentials getCredentials() {
+ return credentials;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/AuthenticationSuccessEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/AuthenticationSuccessEvent.java
new file mode 100644
index 0000000..5a989f7
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/AuthenticationSuccessEvent.java
@@ -0,0 +1,49 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.UserContext;
+
+/**
+ * An event which is triggered whenever a user's credentials pass
+ * authentication. The credentials that passed authentication are included
+ * within this event, and can be retrieved using getCredentials().
+ *
+ * @author Michael Jumper
+ */
+public class AuthenticationSuccessEvent implements UserEvent, CredentialEvent {
+
+ /**
+ * The UserContext associated with the request that is connecting the
+ * tunnel, if any.
+ */
+ private UserContext context;
+
+ /**
+ * The credentials which passed authentication.
+ */
+ private Credentials credentials;
+
+ /**
+ * Creates a new AuthenticationSuccessEvent which represents a successful
+ * authentication attempt with the given credentials.
+ *
+ * @param context The UserContext created as a result of successful
+ * authentication.
+ * @param credentials The credentials which passed authentication.
+ */
+ public AuthenticationSuccessEvent(UserContext context, Credentials credentials) {
+ this.context = context;
+ this.credentials = credentials;
+ }
+
+ @Override
+ public UserContext getUserContext() {
+ return context;
+ }
+
+ @Override
+ public Credentials getCredentials() {
+ return credentials;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/CredentialEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/CredentialEvent.java
new file mode 100644
index 0000000..b9c0b51
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/CredentialEvent.java
@@ -0,0 +1,21 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.auth.Credentials;
+
+/**
+ * Abstract basis for events which may have associated user credentials when
+ * triggered.
+ *
+ * @author Michael Jumper
+ */
+public interface CredentialEvent {
+
+ /**
+ * Returns the current credentials of the user triggering the event, if any.
+ *
+ * @return The current credentials of the user triggering the event, if
+ * any, or null if no credentials are associated with the event.
+ */
+ Credentials getCredentials();
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelCloseEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelCloseEvent.java
new file mode 100644
index 0000000..36f0bab
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelCloseEvent.java
@@ -0,0 +1,66 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.UserContext;
+
+/**
+ * An event which is triggered whenever a tunnel is being closed. The tunnel
+ * being closed can be accessed through getTunnel(), and the UserContext
+ * associated with the request which is closing the tunnel can be retrieved
+ * with getUserContext().
+ *
+ * @author Michael Jumper
+ */
+public class TunnelCloseEvent implements UserEvent, CredentialEvent, TunnelEvent {
+
+ /**
+ * The UserContext associated with the request that is closing the
+ * tunnel, if any.
+ */
+ private UserContext context;
+
+ /**
+ * The credentials associated with the request that connected the
+ * tunnel, if any.
+ */
+ private Credentials credentials;
+
+ /**
+ * The tunnel being closed.
+ */
+ private GuacamoleTunnel tunnel;
+
+ /**
+ * Creates a new TunnelCloseEvent which represents the closing of the
+ * given tunnel via a request associated with the given credentials.
+ *
+ * @param context The UserContext associated with the request closing
+ * the tunnel.
+ * @param credentials The credentials associated with the request that
+ * connected the tunnel.
+ * @param tunnel The tunnel being closed.
+ */
+ public TunnelCloseEvent(UserContext context, Credentials credentials,
+ GuacamoleTunnel tunnel) {
+ this.context = context;
+ this.credentials = credentials;
+ this.tunnel = tunnel;
+ }
+
+ @Override
+ public UserContext getUserContext() {
+ return context;
+ }
+
+ @Override
+ public Credentials getCredentials() {
+ return credentials;
+ }
+
+ @Override
+ public GuacamoleTunnel getTunnel() {
+ return tunnel;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelConnectEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelConnectEvent.java
new file mode 100644
index 0000000..43f1057
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelConnectEvent.java
@@ -0,0 +1,67 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.UserContext;
+
+/**
+ * An event which is triggered whenever a tunnel is being connected. The tunnel
+ * being connected can be accessed through getTunnel(), and the UserContext
+ * associated with the request which is connecting the tunnel can be retrieved
+ * with getUserContext().
+
+ *
+ * @author Michael Jumper
+ */
+public class TunnelConnectEvent implements UserEvent, CredentialEvent, TunnelEvent {
+
+ /**
+ * The UserContext associated with the request that is connecting the
+ * tunnel, if any.
+ */
+ private UserContext context;
+
+ /**
+ * The credentials associated with the request that is connecting the
+ * tunnel, if any.
+ */
+ private Credentials credentials;
+
+ /**
+ * The tunnel being connected.
+ */
+ private GuacamoleTunnel tunnel;
+
+ /**
+ * Creates a new TunnelConnectEvent which represents the connecting of the
+ * given tunnel via a request associated with the given credentials.
+ *
+ * @param context The UserContext associated with the request connecting
+ * the tunnel.
+ * @param credentials The credentials associated with the request connecting
+ * the tunnel.
+ * @param tunnel The tunnel being connected.
+ */
+ public TunnelConnectEvent(UserContext context, Credentials credentials,
+ GuacamoleTunnel tunnel) {
+ this.context = context;
+ this.credentials = credentials;
+ this.tunnel = tunnel;
+ }
+
+ @Override
+ public UserContext getUserContext() {
+ return context;
+ }
+
+ @Override
+ public Credentials getCredentials() {
+ return credentials;
+ }
+
+ @Override
+ public GuacamoleTunnel getTunnel() {
+ return tunnel;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelEvent.java
new file mode 100644
index 0000000..cad9bac
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/TunnelEvent.java
@@ -0,0 +1,20 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+
+/**
+ * Abstract basis for events associated with tunnels.
+ *
+ * @author Michael Jumper
+ */
+public interface TunnelEvent {
+
+ /**
+ * Returns the tunnel associated with this event, if any.
+ *
+ * @return The tunnel associated with this event, if any, or null if no
+ * tunnel is associated with this event.
+ */
+ GuacamoleTunnel getTunnel();
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/UserEvent.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/UserEvent.java
new file mode 100644
index 0000000..f5983b1
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/UserEvent.java
@@ -0,0 +1,21 @@
+package org.glyptodon.guacamole.net.event;
+
+import org.glyptodon.guacamole.net.auth.UserContext;
+
+/**
+ * Abstract basis for events which may have an associated UserContext when
+ * triggered.
+ *
+ * @author Michael Jumper
+ */
+public interface UserEvent {
+
+ /**
+ * Returns the current UserContext of the user triggering the event, if any.
+ *
+ * @return The current UserContext of the user triggering the event, if
+ * any, or null if no UserContext is associated with the event.
+ */
+ UserContext getUserContext();
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/AuthenticationFailureListener.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/AuthenticationFailureListener.java
new file mode 100644
index 0000000..2d98682
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/AuthenticationFailureListener.java
@@ -0,0 +1,29 @@
+package org.glyptodon.guacamole.net.event.listener;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.event.AuthenticationFailureEvent;
+
+/**
+ * A listener whose authenticationFailed() hook will fire immediately
+ * after a user's authentication attempt fails. Note that this hook cannot
+ * be used to cancel the authentication failure.
+ *
+ * @author Michael Jumper
+ */
+public interface AuthenticationFailureListener {
+
+ /**
+ * Event hook which fires immediately after a user's authentication attempt
+ * fails.
+ *
+ * @param e The AuthenticationFailureEvent describing the authentication
+ * failure that just occurred.
+ * @throws GuacamoleException If an error occurs while handling the
+ * authentication failure event. Note that
+ * throwing an exception will NOT cause the
+ * authentication failure to be canceled.
+ */
+ void authenticationFailed(AuthenticationFailureEvent e)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/AuthenticationSuccessListener.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/AuthenticationSuccessListener.java
new file mode 100644
index 0000000..64330a3
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/AuthenticationSuccessListener.java
@@ -0,0 +1,34 @@
+package org.glyptodon.guacamole.net.event.listener;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.event.AuthenticationSuccessEvent;
+
+/**
+ * A listener whose hooks will fire immediately before and after a user's
+ * authentication attempt succeeds. If a user successfully authenticates,
+ * the authenticationSucceeded() hook has the opportunity to cancel the
+ * authentication and force it to fail.
+ *
+ * @author Michael Jumper
+ */
+public interface AuthenticationSuccessListener {
+
+ /**
+ * Event hook which fires immediately after a user's authentication attempt
+ * succeeds. The return value of this hook dictates whether the
+ * successful authentication attempt is canceled.
+ *
+ * @param e The AuthenticationFailureEvent describing the authentication
+ * failure that just occurred.
+ * @return true if the successful authentication attempt should be
+ * allowed, or false if the attempt should be denied, causing
+ * the attempt to effectively fail.
+ * @throws GuacamoleException If an error occurs while handling the
+ * authentication success event. Throwing an
+ * exception will also cancel the authentication
+ * success.
+ */
+ boolean authenticationSucceeded(AuthenticationSuccessEvent e)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/TunnelCloseListener.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/TunnelCloseListener.java
new file mode 100644
index 0000000..ea2ff9b
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/TunnelCloseListener.java
@@ -0,0 +1,31 @@
+package org.glyptodon.guacamole.net.event.listener;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.event.TunnelCloseEvent;
+
+/**
+ * A listener whose tunnelClosed() hook will fire immediately after an
+ * existing tunnel is closed.
+ *
+ * @author Michael Jumper
+ */
+public interface TunnelCloseListener {
+
+ /**
+ * Event hook which fires immediately after an existing tunnel is closed.
+ * The return value of this hook dictates whether the tunnel is allowed to
+ * be closed.
+ *
+ * @param e The TunnelCloseEvent describing the tunnel being closed and
+ * any associated credentials.
+ * @return true if the tunnel should be allowed to be closed, or false
+ * if the attempt should be denied, causing the attempt to
+ * effectively fail.
+ * @throws GuacamoleException If an error occurs while handling the
+ * tunnel close event. Throwing an exception
+ * will also stop the tunnel from being closed.
+ */
+ boolean tunnelClosed(TunnelCloseEvent e)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/TunnelConnectListener.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/TunnelConnectListener.java
new file mode 100644
index 0000000..831cdb0
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/TunnelConnectListener.java
@@ -0,0 +1,32 @@
+package org.glyptodon.guacamole.net.event.listener;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.event.TunnelConnectEvent;
+
+/**
+ * A listener whose tunnelConnected() hook will fire immediately after a new
+ * tunnel is connected.
+ *
+ * @author Michael Jumper
+ */
+public interface TunnelConnectListener {
+
+ /**
+ * Event hook which fires immediately after a new tunnel is connected.
+ * The return value of this hook dictates whether the tunnel is made visible
+ * to the session.
+ *
+ * @param e The TunnelConnectEvent describing the tunnel being connected and
+ * any associated credentials.
+ * @return true if the tunnel should be allowed to be connected, or false
+ * if the attempt should be denied, causing the attempt to
+ * effectively fail.
+ * @throws GuacamoleException If an error occurs while handling the
+ * tunnel connect event. Throwing an exception
+ * will also stop the tunnel from being made
+ * visible to the session.
+ */
+ boolean tunnelConnected(TunnelConnectEvent e)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/package-info.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/package-info.java
new file mode 100644
index 0000000..6122726
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/listener/package-info.java
@@ -0,0 +1,10 @@
+
+/**
+ * Provides classes for hooking into various events that take place as
+ * users log into and use the Guacamole web application. These event
+ * hooks can be used to take action upon occurrence of an event and,
+ * in some cases, prevent the web application from allowing the
+ * event to continue for the user that triggered it.
+ */
+package org.glyptodon.guacamole.net.event.listener;
+
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/package-info.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/package-info.java
new file mode 100644
index 0000000..b011016
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/net/event/package-info.java
@@ -0,0 +1,11 @@
+
+/**
+ * Provides classes for storing information about events that are
+ * triggered when users log into and use the Guacamole web application.
+ * These event classes are most useful when used with hooks implemented
+ * using listener classes.
+ *
+ * @see org.glyptodon.guacamole.net.event.listener
+ */
+package org.glyptodon.guacamole.net.event;
+
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/BooleanGuacamoleProperty.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/BooleanGuacamoleProperty.java
new file mode 100644
index 0000000..829e44b
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/BooleanGuacamoleProperty.java
@@ -0,0 +1,72 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+
+/**
+ * A GuacamoleProperty whose value is an boolean. Legal true values are "true",
+ * or "false". Case does not matter.
+ *
+ * @author Michael Jumper
+ */
+public abstract class BooleanGuacamoleProperty implements GuacamoleProperty<Boolean> {
+
+ @Override
+ public Boolean parseValue(String value) throws GuacamoleException {
+
+ // If no property provided, return null.
+ if (value == null)
+ return null;
+
+ // If "true", return true
+ if (value.equalsIgnoreCase("true"))
+ return true;
+
+ // If "false", return false
+ if (value.equalsIgnoreCase("false"))
+ return false;
+
+ // Otherwise, fail
+ throw new GuacamoleServerException("Property \"" + getName()
+ + "\" must be either \"true\" or \"false\".");
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/FileGuacamoleProperty.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/FileGuacamoleProperty.java
new file mode 100644
index 0000000..aa7563e
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/FileGuacamoleProperty.java
@@ -0,0 +1,61 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.File;
+import org.glyptodon.guacamole.GuacamoleException;
+
+/**
+ * A GuacamoleProperty whose value is a filename.
+ *
+ * @author Michael Jumper
+ */
+public abstract class FileGuacamoleProperty implements GuacamoleProperty<File> {
+
+ @Override
+ public File parseValue(String value) throws GuacamoleException {
+
+ // If no property provided, return null.
+ if (value == null)
+ return null;
+
+ return new File(value);
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleHome.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleHome.java
new file mode 100644
index 0000000..438316e
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleHome.java
@@ -0,0 +1,87 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.File;
+
+/**
+ * Abstract representation of the Guacamole configuration directory.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleHome {
+
+ /**
+ * GuacamoleHome is a utility class and cannot be instantiated.
+ */
+ private GuacamoleHome() {}
+
+ /**
+ * Returns the Guacamole home directory by checking, in order:
+ * the guacamole.home system property, the GUACAMOLE_HOME environment
+ * variable, and finally the .guacamole directory in the home directory of
+ * the user running the servlet container.
+ *
+ * @return The File representing the Guacamole home directory, which may
+ * or may not exist, and may turn out to not be a directory.
+ */
+ public static File getDirectory() {
+
+ // Attempt to find Guacamole home
+ File guacHome;
+
+ // Use system property by default
+ String desiredDir = System.getProperty("guacamole.home");
+
+ // Failing that, try the GUACAMOLE_HOME environment variable
+ if (desiredDir == null) desiredDir = System.getenv("GUACAMOLE_HOME");
+
+ // If successful, use explicitly specified directory
+ if (desiredDir != null)
+ guacHome = new File(desiredDir);
+
+ // If not explicitly specified, use ~/.guacamole
+ else
+ guacHome = new File(System.getProperty("user.home"), ".guacamole");
+
+ // Return discovered directory
+ return guacHome;
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleProperties.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleProperties.java
new file mode 100644
index 0000000..f502642
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleProperties.java
@@ -0,0 +1,220 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+
+/**
+ * Simple utility class for reading properties from the guacamole.properties
+ * file. The guacamole.properties file is preferably located in the servlet
+ * container's user's home directory, in a subdirectory called .guacamole, or
+ * in the directory set by the system property: guacamole.home.
+ *
+ * If none of those locations are possible, guacamole.properties will also
+ * be read from the root of the classpath.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleProperties {
+
+ /**
+ * GuacamoleProperties is a utility class and cannot be instantiated.
+ */
+ private GuacamoleProperties() {}
+
+ /**
+ * The hostname of the server where guacd (the Guacamole proxy server) is
+ * running.
+ */
+ public static final StringGuacamoleProperty GUACD_HOSTNAME = new StringGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "guacd-hostname"; }
+
+ };
+
+ /**
+ * The port that guacd (the Guacamole proxy server) is listening on.
+ */
+ public static final IntegerGuacamoleProperty GUACD_PORT = new IntegerGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "guacd-port"; }
+
+ };
+
+ /**
+ * Whether guacd requires SSL/TLS on connections.
+ */
+ public static final BooleanGuacamoleProperty GUACD_SSL = new BooleanGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "guacd-ssl"; }
+
+ };
+
+ /**
+ * All properties read from guacamole.properties when this class was first
+ * used.
+ */
+ private static final Properties properties;
+
+ /**
+ * Any error encountered when reading guacamole.properties was last
+ * attempted.
+ */
+ private static GuacamoleException exception;
+
+ static {
+
+ properties = new Properties();
+
+ try {
+
+ // Attempt to find Guacamole home
+ File guacHome = GuacamoleHome.getDirectory();
+
+ InputStream stream;
+
+ // If not a directory, load from classpath
+ if (!guacHome.isDirectory()) {
+
+ // Read from classpath
+ stream = GuacamoleProperties.class.getResourceAsStream("/guacamole.properties");
+ if (stream == null)
+ throw new IOException(
+ "guacamole.properties not loaded from " + guacHome
+ + " (not a directory), and guacamole.properties could"
+ + " not be found as a resource in the classpath.");
+
+ }
+
+ // Otherwise, try to load from file
+ else
+ stream = new FileInputStream(new File(guacHome, "guacamole.properties"));
+
+ // Load properties, always close stream
+ try { properties.load(stream); }
+ finally { stream.close(); }
+
+ }
+ catch (IOException e) {
+ exception = new GuacamoleServerException("Error reading guacamole.properties", e);
+ }
+
+ }
+
+ /**
+ * Given a GuacamoleProperty, parses and returns the value set for that
+ * property in guacamole.properties, if any.
+ *
+ * @param <Type> The type that the given property is parsed into.
+ * @param property The property to read from guacamole.properties.
+ * @return The parsed value of the property as read from
+ * guacamole.properties.
+ * @throws GuacamoleException If an error occurs while parsing the value
+ * for the given property in
+ * guacamole.properties.
+ */
+ public static <Type> Type getProperty(GuacamoleProperty<Type> property) throws GuacamoleException {
+
+ if (exception != null)
+ throw exception;
+
+ return property.parseValue(properties.getProperty(property.getName()));
+
+ }
+
+ /**
+ * Given a GuacamoleProperty, parses and returns the value set for that
+ * property in guacamole.properties, if any. If no value is found, the
+ * provided default value is returned.
+ *
+ * @param <Type> The type that the given property is parsed into.
+ * @param property The property to read from guacamole.properties.
+ * @param defaultValue The value to return if no value was given in
+ * guacamole.properties.
+ * @return The parsed value of the property as read from
+ * guacamole.properties, or the provided default value if no value
+ * was found.
+ * @throws GuacamoleException If an error occurs while parsing the value
+ * for the given property in
+ * guacamole.properties.
+ */
+ public static <Type> Type getProperty(GuacamoleProperty<Type> property,
+ Type defaultValue) throws GuacamoleException {
+
+ Type value = getProperty(property);
+ if (value == null)
+ return defaultValue;
+
+ return value;
+
+ }
+
+ /**
+ * Given a GuacamoleProperty, parses and returns the value set for that
+ * property in guacamole.properties. An exception is thrown if the value
+ * is not provided.
+ *
+ * @param <Type> The type that the given property is parsed into.
+ * @param property The property to read from guacamole.properties.
+ * @return The parsed value of the property as read from
+ * guacamole.properties.
+ * @throws GuacamoleException If an error occurs while parsing the value
+ * for the given property in
+ * guacamole.properties, or if the property is
+ * not specified.
+ */
+ public static <Type> Type getRequiredProperty(GuacamoleProperty<Type> property)
+ throws GuacamoleException {
+
+ Type value = getProperty(property);
+ if (value == null)
+ throw new GuacamoleServerException("Property " + property.getName() + " is required.");
+
+ return value;
+
+ }
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleProperty.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleProperty.java
new file mode 100644
index 0000000..ddbe6d6
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/GuacamoleProperty.java
@@ -0,0 +1,71 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+
+/**
+ * An abstract representation of a property in the guacamole.properties file,
+ * which parses into a specific type.
+ *
+ * @author Michael Jumper
+ * @param <Type> The type this GuacamoleProperty will parse into.
+ */
+public interface GuacamoleProperty<Type> {
+
+ /**
+ * Returns the name of the property in guacamole.properties that this
+ * GuacamoleProperty will parse.
+ *
+ * @return The name of the property in guacamole.properties that this
+ * GuacamoleProperty will parse.
+ */
+ public String getName();
+
+ /**
+ * Parses the given string value into the type associated with this
+ * GuacamoleProperty.
+ *
+ * @param value The string value to parse.
+ * @return The parsed value.
+ * @throws GuacamoleException If an error occurs while parsing the
+ * provided value.
+ */
+ public Type parseValue(String value) throws GuacamoleException;
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/IntegerGuacamoleProperty.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/IntegerGuacamoleProperty.java
new file mode 100644
index 0000000..6289bb9
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/IntegerGuacamoleProperty.java
@@ -0,0 +1,67 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+
+/**
+ * A GuacamoleProperty whose value is an integer.
+ *
+ * @author Michael Jumper
+ */
+public abstract class IntegerGuacamoleProperty implements GuacamoleProperty<Integer> {
+
+ @Override
+ public Integer parseValue(String value) throws GuacamoleException {
+
+ // If no property provided, return null.
+ if (value == null)
+ return null;
+
+ try {
+ Integer integer = new Integer(value);
+ return integer;
+ }
+ catch (NumberFormatException e) {
+ throw new GuacamoleServerException("Property \"" + getName() + "\" must be an integer.", e);
+ }
+
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/StringGuacamoleProperty.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/StringGuacamoleProperty.java
new file mode 100644
index 0000000..a8ebef8
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/StringGuacamoleProperty.java
@@ -0,0 +1,54 @@
+
+package org.glyptodon.guacamole.properties;
+
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is guacamole-ext.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+import org.glyptodon.guacamole.GuacamoleException;
+
+/**
+ * A GuacamoleProperty whose value is a simple string.
+ *
+ * @author Michael Jumper
+ */
+public abstract class StringGuacamoleProperty implements GuacamoleProperty<String> {
+
+ @Override
+ public String parseValue(String value) throws GuacamoleException {
+ return value;
+ }
+
+}
diff --git a/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/package-info.java b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/package-info.java
new file mode 100644
index 0000000..5dbd06f
--- /dev/null
+++ b/guacamole-ext/src/main/java/org/glyptodon/guacamole/properties/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Provides classes for reading properties from the web-application-wide
+ * guacamole.properties file.
+ */
+package org.glyptodon.guacamole.properties;
+
diff --git a/guacamole/COPYING b/guacamole/COPYING
new file mode 100644
index 0000000..dba13ed
--- /dev/null
+++ b/guacamole/COPYING
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/guacamole/ChangeLog b/guacamole/ChangeLog
new file mode 100644
index 0000000..c4b322f
--- /dev/null
+++ b/guacamole/ChangeLog
@@ -0,0 +1,75 @@
+2013-07-02 Michael Jumper <mike.jumper at guac-dev.org>
+
+ * Update rdp.xml with new "enable-printing" parameter
+
+2013-06-25 Michael Jumper <mike.jumper at guac-dev.org>
+
+ * Add support for notifications and file download
+
+2013-04-24 James Muehlner <james.muehlner at guac-dev.org>
+
+ * Fix handling of checkbox parameters (ticket #307)
+
+2013-01-09 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Rewrite parser for user-mapping.xml
+ * Fix truncation of parameter values
+
+2012-12-09 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Sort connection IDs alphabetically
+
+2012-10-24 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Implement auto-scaling
+ * Send optimal width/height
+ * Detect and send supported audio mimetypes
+
+2012-10-15 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Migrate to guacamole-common 0.6.2
+ * Migrate to guacamole-common-js 0.6.2
+
+2012-08-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Migrate to guacamole-common 0.6.1
+ * Migrate to guacamole-common-js 0.6.1
+
+2012-06-03 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Fix clipboard blur bug
+
+2012-05-04 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Touch-specific menus and keyboard support
+ * Logout prompt
+ * Multiple connections per user in user-mapping.xml
+ * Touch-related UI usability improvements
+ * Support for single sign-on
+ * Support for authentication involving parameters in URLs
+ * Test for WebSocket support (pluggable WebSocket support not yet stable)
+ * UI style improvements
+
+2011-12-11 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Improved UI usability
+ * Support for multiple connections per user
+ * Real support for authentication providers
+ * Logout button
+ * Connection type icons (thanks to Tango Desktop Project)
+ * Fixed Ctrl-Alt-Delete bug (ticket #57)
+ * Fixed arrow key rendering (Chrome-specific issue)
+ * Fixed exception in XMLReader.parse() (ticket #66)
+
+2011-07-13 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Migrated to new tunnel API
+ * Major cleanup of UI
+ * Fixed corrupt mouse cursor image
+ * Improved JavaScript style
+ * Logging (via SLF4J)
+
+2011-03-02 Michael Jumper <zhangmaike at users.sourceforge.net>
+
+ * Initial release of modern 0.3.0+ series
+
diff --git a/guacamole/README b/guacamole/README
new file mode 100644
index 0000000..0ac4c47
--- /dev/null
+++ b/guacamole/README
@@ -0,0 +1,70 @@
+
+------------------------------------------------------------
+ About this README
+------------------------------------------------------------
+
+This README is intended to provide quick and to-the-point documentation for
+technical users intending to compile parts of Guacamole themselves.
+
+Distribution-specific packages are available from the files section of the main
+project page:
+
+ http://sourceforge.net/projects/guacamole/files/
+
+Distribution-specific documentation is provided on the Guacamole wiki:
+
+ http://guac-dev.org/
+
+
+------------------------------------------------------------
+ What is Guacamole?
+------------------------------------------------------------
+
+Guacamole is an HTML5 web application that provides access to your desktop using
+remote desktop protocols. A centralized server acts as a tunnel and proxy,
+allowing access to multiple desktops through a web browser; no plugins needed.
+The client requires nothing more than a web browser supporting HTML5 and AJAX.
+
+The Guacamole project maintains this web application and the Java and C
+libraries and programs it depends on. These libraries and programs are
+separate in order to enable others to implement other applications using the
+same underlying technology.
+
+All components and dependencies of Guacamole are free and open source.
+
+
+------------------------------------------------------------
+ Compiling and installing Guacamole
+------------------------------------------------------------
+
+Guacamole is built using Maven. Building Guacamole compiles all classes and
+packages them into a deployable .war file. This .war file can be installed
+and deployed under servlet containers like Apache Tomcat or Jetty.
+
+1) Run mvn package
+
+ $ mvn package
+
+ Maven will download any needed dependencies for building the .jar file.
+ Once all dependencies have been downloaded, the .war file will be
+ created in the target/ subdirectory of the current directory.
+
+2) Copy the .war file as directed in the instructions provided with
+ your servlet container.
+
+ Apache Tomcat, Jetty, and other servlet containers have specific and
+ varying locations that .war files must be placed for the web
+ application to be deployed.
+
+ You will likely need to do this as root.
+
+
+------------------------------------------------------------
+ Reporting problems
+------------------------------------------------------------
+
+Please report any bugs encountered by opening a new ticket at the Trac system
+hosted at:
+
+ http://guac-dev.org/trac/
+
diff --git a/guacamole/doc/example/guacamole.properties b/guacamole/doc/example/guacamole.properties
new file mode 100644
index 0000000..ace043f
--- /dev/null
+++ b/guacamole/doc/example/guacamole.properties
@@ -0,0 +1,26 @@
+
+# Guacamole - Clientless Remote Desktop
+# Copyright (C) 2010 Michael Jumper
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+# Hostname and port of guacamole proxy
+guacd-hostname: localhost
+guacd-port: 4822
+
+# Auth provider class (authenticates user/pass combination, needed if using the provided login screen)
+auth-provider: net.sourceforge.guacamole.net.basic.BasicFileAuthenticationProvider
+basic-user-mapping: /path/to/user-mapping.xml
+
diff --git a/guacamole/doc/example/user-mapping.xml b/guacamole/doc/example/user-mapping.xml
new file mode 100644
index 0000000..1234de5
--- /dev/null
+++ b/guacamole/doc/example/user-mapping.xml
@@ -0,0 +1,36 @@
+<user-mapping>
+
+ <!-- Per-user authentication and config information -->
+ <authorize username="USERNAME" password="PASSWORD">
+ <protocol>vnc</protocol>
+ <param name="hostname">localhost</param>
+ <param name="port">5900</param>
+ <param name="password">VNCPASS</param>
+ </authorize>
+
+ <!-- Another user, but using md5 to hash the password
+ (example below uses the md5 hash of "PASSWORD") -->
+ <authorize
+ username="USERNAME2"
+ password="319f4d26e3c536b5dd871bb2c52e3178"
+ encoding="md5">
+
+ <!-- First authorized connection -->
+ <connection name="localhost">
+ <protocol>vnc</protocol>
+ <param name="hostname">localhost</param>
+ <param name="port">5901</param>
+ <param name="password">VNCPASS</param>
+ </connection>
+
+ <!-- Second authorized connection -->
+ <connection name="otherhost">
+ <protocol>vnc</protocol>
+ <param name="hostname">otherhost</param>
+ <param name="port">5900</param>
+ <param name="password">VNCPASS</param>
+ </connection>
+
+ </authorize>
+
+</user-mapping>
diff --git a/guacamole/pom.xml b/guacamole/pom.xml
new file mode 100644
index 0000000..f8afcbf
--- /dev/null
+++ b/guacamole/pom.xml
@@ -0,0 +1,139 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole</artifactId>
+ <packaging>war</packaging>
+ <version>0.8.3</version>
+ <name>guacamole</name>
+ <url>http://guac-dev.org/</url>
+
+ <description>
+ The Guacamole web application, providing authentication and an HTML5
+ remote desktop client.
+ </description>
+
+ <!-- All applicable licenses -->
+ <licenses>
+ <license>
+ <name>GNU Affero General Public License</name>
+ <url>http://www.gnu.org/licenses/agpl-3.0.html</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <!-- Git repository -->
+ <scm>
+ <url>https://github.com/glyptodon/guacamole-client</url>
+ <connection>scm:git:git://github.com/glyptodon/guacamole-client.git</connection>
+ </scm>
+
+ <!-- Developers -->
+ <developers>
+ <developer>
+ <id>mike.jumper</id>
+ <name>Michael Jumper</name>
+ <email>mike.jumper at guac-dev.org</email>
+ </developer>
+ <developer>
+ <id>james.muehlner</id>
+ <name>James Muehlner</name>
+ <email>james.muehlner at guac-dev.org</email>
+ </developer>
+ </developers>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+
+ <!-- Written for 1.6 -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-war-plugin</artifactId>
+ <configuration>
+
+ <!-- Filter webapp dir -->
+ <webResources>
+ <resource>
+ <directory>src/main/webapp</directory>
+ <filtering>true</filtering>
+ </resource>
+ </webResources>
+
+ <!-- Add files from guacamole-common-js -->
+ <overlays>
+ <overlay>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common-js</artifactId>
+ <type>zip</type>
+ </overlay>
+ </overlays>
+
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <!-- Java servlet API -->
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- SLF4J - logging -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-jcl</artifactId>
+ <version>1.6.1</version>
+ <scope>runtime</scope>
+ </dependency>
+
+ <!-- Guacamole Java API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+
+ <!-- Guacamole Extension API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-ext</artifactId>
+ <version>0.8.1</version>
+ </dependency>
+
+ <!-- Guacamole JavaScript API -->
+ <dependency>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-common-js</artifactId>
+ <version>0.7.4</version>
+ <type>zip</type>
+ <scope>runtime</scope>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/guacamole/src/main/java/net/sourceforge/guacamole/net/basic/BasicFileAuthenticationProvider.java b/guacamole/src/main/java/net/sourceforge/guacamole/net/basic/BasicFileAuthenticationProvider.java
new file mode 100644
index 0000000..d7da4a9
--- /dev/null
+++ b/guacamole/src/main/java/net/sourceforge/guacamole/net/basic/BasicFileAuthenticationProvider.java
@@ -0,0 +1,157 @@
+
+package net.sourceforge.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.simple.SimpleAuthenticationProvider;
+import org.glyptodon.guacamole.net.basic.auth.Authorization;
+import org.glyptodon.guacamole.net.basic.auth.UserMapping;
+import org.glyptodon.guacamole.net.basic.xml.DocumentHandler;
+import org.glyptodon.guacamole.net.basic.xml.user_mapping.UserMappingTagHandler;
+import org.glyptodon.guacamole.properties.FileGuacamoleProperty;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+/**
+ * Authenticates users against a static list of username/password pairs.
+ * Each username/password may be associated with multiple configurations.
+ * This list is stored in an XML file which is reread if modified.
+ *
+ * @author Michael Jumper, Michal Kotas
+ */
+public class BasicFileAuthenticationProvider extends SimpleAuthenticationProvider {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(BasicFileAuthenticationProvider.class);
+
+ /**
+ * The time the user mapping file was last modified.
+ */
+ private long mod_time;
+
+ /**
+ * The parsed UserMapping read when the user mapping file was last parsed.
+ */
+ private UserMapping user_mapping;
+
+ /**
+ * The filename of the XML file to read the user user_mapping from.
+ */
+ public static final FileGuacamoleProperty BASIC_USER_MAPPING = new FileGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "basic-user-mapping"; }
+
+ };
+
+ /**
+ * Returns a UserMapping containing all authorization data given within
+ * the XML file specified by the "basic-user-mapping" property in
+ * guacamole.properties. If the XML file has been modified or has not yet
+ * been read, this function may reread the file.
+ *
+ * @return A UserMapping containing all authorization data within the
+ * user mapping XML file.
+ * @throws GuacamoleException If the user mapping property is missing or
+ * an error occurs while parsing the XML file.
+ */
+ private UserMapping getUserMapping() throws GuacamoleException {
+
+ // Get user user_mapping file
+ File user_mapping_file =
+ GuacamoleProperties.getRequiredProperty(BASIC_USER_MAPPING);
+
+ // If user_mapping not yet read, or user_mapping has been modified, reread
+ if (user_mapping == null ||
+ (user_mapping_file.exists()
+ && mod_time < user_mapping_file.lastModified())) {
+
+ logger.info("Reading user mapping file: {}", user_mapping_file);
+
+ // Parse document
+ try {
+
+ // Get handler for root element
+ UserMappingTagHandler userMappingHandler =
+ new UserMappingTagHandler();
+
+ // Set up document handler
+ DocumentHandler contentHandler = new DocumentHandler(
+ "user-mapping", userMappingHandler);
+
+ // Set up XML parser
+ XMLReader parser = XMLReaderFactory.createXMLReader();
+ parser.setContentHandler(contentHandler);
+
+ // Read and parse file
+ InputStream input = new BufferedInputStream(new FileInputStream(user_mapping_file));
+ parser.parse(new InputSource(input));
+ input.close();
+
+ // Store mod time and user mapping
+ mod_time = user_mapping_file.lastModified();
+ user_mapping = userMappingHandler.asUserMapping();
+
+ }
+ catch (IOException e) {
+ throw new GuacamoleException("Error reading basic user mapping file.", e);
+ }
+ catch (SAXException e) {
+ throw new GuacamoleException("Error parsing basic user mapping XML.", e);
+ }
+
+ }
+
+ // Return (possibly cached) user mapping
+ return user_mapping;
+
+ }
+
+ @Override
+ public Map<String, GuacamoleConfiguration>
+ getAuthorizedConfigurations(Credentials credentials)
+ throws GuacamoleException {
+
+ // Validate and return info for given user and pass
+ Authorization auth = getUserMapping().getAuthorization(credentials.getUsername());
+ if (auth != null && auth.validate(credentials.getUsername(), credentials.getPassword()))
+ return auth.getConfigurations();
+
+ // Unauthorized
+ return null;
+
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/AuthenticatingHttpServlet.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/AuthenticatingHttpServlet.java
new file mode 100644
index 0000000..f42d88b
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/AuthenticatingHttpServlet.java
@@ -0,0 +1,354 @@
+
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Collection;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleResourceNotFoundException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.auth.AuthenticationProvider;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.event.SessionListenerCollection;
+import org.glyptodon.guacamole.net.basic.properties.BasicGuacamoleProperties;
+import org.glyptodon.guacamole.net.event.AuthenticationFailureEvent;
+import org.glyptodon.guacamole.net.event.AuthenticationSuccessEvent;
+import org.glyptodon.guacamole.net.event.listener.AuthenticationFailureListener;
+import org.glyptodon.guacamole.net.event.listener.AuthenticationSuccessListener;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Abstract servlet which provides an authenticatedService() function that
+ * is only called if the HTTP request is authenticated, or the current
+ * HTTP session has already been authenticated.
+ *
+ * The user context is retrieved using the authentication provider defined in
+ * guacamole.properties. The authentication provider has access to the request
+ * and session, in addition to any submitted username and password, in order
+ * to authenticate the user.
+ *
+ * The user context will be stored in the current HttpSession.
+ *
+ * Success and failure are logged.
+ *
+ * @author Michael Jumper
+ */
+public abstract class AuthenticatingHttpServlet extends HttpServlet {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(AuthenticatingHttpServlet.class);
+
+ /**
+ * The session attribute holding the current UserContext.
+ */
+ private static final String CONTEXT_ATTRIBUTE = "GUAC_CONTEXT";
+
+ /**
+ * The session attribute holding the credentials authorizing this session.
+ */
+ private static final String CREDENTIALS_ATTRIBUTE = "GUAC_CREDS";
+
+ /**
+ * The AuthenticationProvider to use to authenticate all requests.
+ */
+ private AuthenticationProvider authProvider;
+
+ @Override
+ public void init() throws ServletException {
+
+ // Get auth provider instance
+ try {
+ authProvider = GuacamoleProperties.getRequiredProperty(BasicGuacamoleProperties.AUTH_PROVIDER);
+ }
+ catch (GuacamoleException e) {
+ logger.error("Error getting authentication provider from properties.", e);
+ throw new ServletException(e);
+ }
+
+ }
+
+ /**
+ * Notifies all listeners in the given collection that authentication has
+ * failed.
+ *
+ * @param listeners A collection of all listeners that should be notified.
+ * @param credentials The credentials associated with the authentication
+ * request that failed.
+ */
+ private void notifyFailed(Collection listeners, Credentials credentials) {
+
+ // Build event for auth failure
+ AuthenticationFailureEvent event = new AuthenticationFailureEvent(credentials);
+
+ // Notify all listeners
+ for (Object listener : listeners) {
+ try {
+ if (listener instanceof AuthenticationFailureListener)
+ ((AuthenticationFailureListener) listener).authenticationFailed(event);
+ }
+ catch (GuacamoleException e) {
+ logger.error("Error notifying AuthenticationFailureListener.", e);
+ }
+ }
+
+ }
+
+ /**
+ * Notifies all listeners in the given collection that authentication was
+ * successful.
+ *
+ * @param listeners A collection of all listeners that should be notified.
+ * @param context The UserContext created as a result of authentication
+ * success.
+ * @param credentials The credentials associated with the authentication
+ * request that succeeded.
+ * @return true if all listeners are allowing the authentication success,
+ * or if there are no listeners, and false if any listener is
+ * canceling the authentication success. Note that once one
+ * listener cancels, no other listeners will run.
+ * @throws GuacamoleException If any listener throws an error while being
+ * notified. Note that if any listener throws an
+ * error, the success is canceled, and no other
+ * listeners will run.
+ */
+ private boolean notifySuccess(Collection listeners, UserContext context,
+ Credentials credentials) throws GuacamoleException {
+
+ // Build event for auth success
+ AuthenticationSuccessEvent event =
+ new AuthenticationSuccessEvent(context, credentials);
+
+ // Notify all listeners
+ for (Object listener : listeners) {
+ if (listener instanceof AuthenticationSuccessListener) {
+
+ // Cancel immediately if hook returns false
+ if (!((AuthenticationSuccessListener) listener).authenticationSucceeded(event))
+ return false;
+
+ }
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Sends an error on the given HTTP response with the given integer error
+ * code.
+ *
+ * @param response The HTTP response to use to send the error.
+ * @param code The HTTP status code of the error.
+ * @param message A human-readable message that can be presented to the
+ * user.
+ * @throws ServletException If an error prevents sending of the error
+ * code.
+ */
+ private void sendError(HttpServletResponse response, int code,
+ String message) throws ServletException {
+
+ try {
+
+ // If response not committed, send error code
+ if (!response.isCommitted()) {
+ response.addHeader("Guacamole-Error-Message", message);
+ response.sendError(code);
+ }
+
+ }
+ catch (IOException ioe) {
+
+ // If unable to send error at all due to I/O problems,
+ // rethrow as servlet exception
+ throw new ServletException(ioe);
+
+ }
+
+ }
+
+ /**
+ * Returns the credentials associated with the given session.
+ *
+ * @param session The session to retrieve credentials from.
+ * @return The credentials associated with the given session.
+ */
+ protected Credentials getCredentials(HttpSession session) {
+ return (Credentials) session.getAttribute(CREDENTIALS_ATTRIBUTE);
+ }
+
+ /**
+ * Returns the UserContext associated with the given session.
+ *
+ * @param session The session to retrieve UserContext from.
+ * @return The UserContext associated with the given session.
+ */
+ protected UserContext getUserContext(HttpSession session) {
+ return (UserContext) session.getAttribute(CONTEXT_ATTRIBUTE);
+ }
+
+ /**
+ * Returns whether the request given has updated credentials. If this
+ * function returns false, the UserContext will not be updated.
+ *
+ * @param request The request to check for credentials.
+ * @return true if the request contains credentials, false otherwise.
+ */
+ protected boolean hasNewCredentials(HttpServletRequest request) {
+ return true;
+ }
+
+ @Override
+ protected void service(HttpServletRequest request, HttpServletResponse response)
+ throws IOException, ServletException {
+
+ // Set character encoding to UTF-8 if it's not already set
+ if(request.getCharacterEncoding() == null) {
+ try {
+ request.setCharacterEncoding("UTF-8");
+ } catch (UnsupportedEncodingException exception) {
+ throw new ServletException(exception);
+ }
+ }
+
+ try {
+
+ // Obtain context from session
+ HttpSession httpSession = request.getSession(true);
+ UserContext context = getUserContext(httpSession);
+
+ // If new credentials present, update/create context
+ if (hasNewCredentials(request)) {
+
+ // Retrieve username and password from parms
+ String username = request.getParameter("username");
+ String password = request.getParameter("password");
+
+ // Build credentials object
+ Credentials credentials = new Credentials();
+ credentials.setSession(httpSession);
+ credentials.setRequest(request);
+ credentials.setUsername(username);
+ credentials.setPassword(password);
+
+ SessionListenerCollection listeners = new SessionListenerCollection(httpSession);
+
+ // If no cached context, attempt to get new context
+ if (context == null) {
+
+ context = authProvider.getUserContext(credentials);
+
+ // Log successful authentication
+ if (context != null)
+ logger.info("User \"{}\" successfully authenticated from {}.",
+ context.self().getUsername(), request.getRemoteAddr());
+
+ }
+
+ // Otherwise, update existing context
+ else
+ context = authProvider.updateUserContext(context, credentials);
+
+ // If auth failed, notify listeners
+ if (context == null) {
+ logger.warn("Authentication attempt from {} for user \"{}\" failed.",
+ request.getRemoteAddr(), credentials.getUsername());
+
+ notifyFailed(listeners, credentials);
+ }
+
+ // If auth succeeded, notify and check with listeners
+ else if (!notifySuccess(listeners, context, credentials)) {
+ logger.info("Successful authentication canceled by hook.");
+ context = null;
+ }
+
+ // If auth still OK, associate context with session
+ else {
+ httpSession.setAttribute(CONTEXT_ATTRIBUTE, context);
+ httpSession.setAttribute(CREDENTIALS_ATTRIBUTE, credentials);
+ }
+
+ } // end if credentials present
+
+ // If no context, no authorizaton present
+ if (context == null)
+ throw new GuacamoleSecurityException("Not authenticated");
+
+ // Allow servlet to run now that authentication has been validated
+ authenticatedService(context, request, response);
+
+ }
+
+ // Catch any thrown guacamole exception and attempt to pass within the
+ // HTTP response, logging each error appropriately.
+ catch (GuacamoleSecurityException e) {
+ logger.warn("Permission denied: {}", e.getMessage());
+ sendError(response, HttpServletResponse.SC_FORBIDDEN,
+ "Permission denied.");
+ }
+ catch (GuacamoleResourceNotFoundException e) {
+ logger.debug("Resource not found: {}", e.getMessage());
+ sendError(response, HttpServletResponse.SC_NOT_FOUND,
+ e.getMessage());
+ }
+ catch (GuacamoleClientException e) {
+ logger.warn("Error in client request: {}", e.getMessage());
+ sendError(response, HttpServletResponse.SC_BAD_REQUEST,
+ e.getMessage());
+ }
+ catch (GuacamoleException e) {
+ logger.error("Internal server error.", e);
+ sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ "Internal server error.");
+ }
+
+ }
+
+ /**
+ * Function called after the credentials given in the request (if any)
+ * are authenticated. If the current session is not associated with
+ * valid credentials, this function will not be called.
+ *
+ * @param context The current UserContext.
+ * @param request The HttpServletRequest being serviced.
+ * @param response An HttpServletResponse which controls the HTTP response
+ * of this servlet.
+ *
+ * @throws GuacamoleException If an error occurs that interferes with the
+ * normal operation of this servlet.
+ */
+ protected abstract void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException;
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicGuacamoleTunnelServlet.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicGuacamoleTunnelServlet.java
new file mode 100644
index 0000000..015a01c
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicGuacamoleTunnelServlet.java
@@ -0,0 +1,379 @@
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.GuacamoleTunnel;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Credentials;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.event.SessionListenerCollection;
+import org.glyptodon.guacamole.net.event.TunnelCloseEvent;
+import org.glyptodon.guacamole.net.event.TunnelConnectEvent;
+import org.glyptodon.guacamole.net.event.listener.TunnelCloseListener;
+import org.glyptodon.guacamole.net.event.listener.TunnelConnectListener;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+import org.glyptodon.guacamole.servlet.GuacamoleHTTPTunnelServlet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Connects users to a tunnel associated with the authorized connection
+ * having the given ID.
+ *
+ * @author Michael Jumper
+ */
+public class BasicGuacamoleTunnelServlet extends AuthenticatingHttpServlet {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(BasicGuacamoleTunnelServlet.class);
+
+ /**
+ * All supported identifier types.
+ */
+ private static enum IdentifierType {
+
+ /**
+ * The unique identifier of a connection.
+ */
+ CONNECTION("c/"),
+
+ /**
+ * The unique identifier of a connection group.
+ */
+ CONNECTION_GROUP("g/");
+
+ /**
+ * The prefix which precedes an identifier of this type.
+ */
+ final String PREFIX;
+
+ /**
+ * Defines an IdentifierType having the given prefix.
+ * @param prefix The prefix which will precede any identifier of this
+ * type, thus differentiating it from other identifier
+ * types.
+ */
+ IdentifierType(String prefix) {
+ PREFIX = prefix;
+ }
+
+ /**
+ * Given an identifier, determines the corresponding identifier type.
+ *
+ * @param identifier The identifier whose type should be identified.
+ * @return The identified identifier type.
+ */
+ static IdentifierType getType(String identifier) {
+
+ // If null, no known identifier
+ if (identifier == null)
+ return null;
+
+ // Connection identifiers
+ if (identifier.startsWith(CONNECTION.PREFIX))
+ return CONNECTION;
+
+ // Connection group identifiers
+ if (identifier.startsWith(CONNECTION_GROUP.PREFIX))
+ return CONNECTION_GROUP;
+
+ // Otherwise, unknown
+ return null;
+
+ }
+
+ };
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ try {
+
+ // If authenticated, respond as tunnel
+ tunnelServlet.service(request, response);
+ }
+
+ catch (ServletException e) {
+ logger.info("Error from tunnel (see previous log messages): {}",
+ e.getMessage());
+ }
+
+ catch (IOException e) {
+ logger.info("I/O error from tunnel (see previous log messages): {}",
+ e.getMessage());
+ }
+
+ }
+
+ /**
+ * Notifies all listeners in the given collection that a tunnel has been
+ * connected.
+ *
+ * @param listeners A collection of all listeners that should be notified.
+ * @param context The UserContext associated with the current session.
+ * @param credentials The credentials associated with the current session.
+ * @param tunnel The tunnel being connected.
+ * @return true if all listeners are allowing the tunnel to connect,
+ * or if there are no listeners, and false if any listener is
+ * canceling the connection. Note that once one listener cancels,
+ * no other listeners will run.
+ * @throws GuacamoleException If any listener throws an error while being
+ * notified. Note that if any listener throws an
+ * error, the connect is canceled, and no other
+ * listeners will run.
+ */
+ private boolean notifyConnect(Collection listeners, UserContext context,
+ Credentials credentials, GuacamoleTunnel tunnel)
+ throws GuacamoleException {
+
+ // Build event for auth success
+ TunnelConnectEvent event = new TunnelConnectEvent(context,
+ credentials, tunnel);
+
+ // Notify all listeners
+ for (Object listener : listeners) {
+ if (listener instanceof TunnelConnectListener) {
+
+ // Cancel immediately if hook returns false
+ if (!((TunnelConnectListener) listener).tunnelConnected(event))
+ return false;
+
+ }
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Notifies all listeners in the given collection that a tunnel has been
+ * closed.
+ *
+ * @param listeners A collection of all listeners that should be notified.
+ * @param context The UserContext associated with the current session.
+ * @param credentials The credentials associated with the current session.
+ * @param tunnel The tunnel being closed.
+ * @return true if all listeners are allowing the tunnel to close,
+ * or if there are no listeners, and false if any listener is
+ * canceling the close. Note that once one listener cancels,
+ * no other listeners will run.
+ * @throws GuacamoleException If any listener throws an error while being
+ * notified. Note that if any listener throws an
+ * error, the close is canceled, and no other
+ * listeners will run.
+ */
+ private boolean notifyClose(Collection listeners, UserContext context,
+ Credentials credentials, GuacamoleTunnel tunnel)
+ throws GuacamoleException {
+
+ // Build event for auth success
+ TunnelCloseEvent event = new TunnelCloseEvent(context,
+ credentials, tunnel);
+
+ // Notify all listeners
+ for (Object listener : listeners) {
+ if (listener instanceof TunnelCloseListener) {
+
+ // Cancel immediately if hook returns false
+ if (!((TunnelCloseListener) listener).tunnelClosed(event))
+ return false;
+
+ }
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Wrapped GuacamoleHTTPTunnelServlet which will handle all authenticated
+ * requests.
+ */
+ private GuacamoleHTTPTunnelServlet tunnelServlet = new GuacamoleHTTPTunnelServlet() {
+
+ @Override
+ protected GuacamoleTunnel doConnect(HttpServletRequest request) throws GuacamoleException {
+
+ HttpSession httpSession = request.getSession(true);
+
+ // Get listeners
+ final SessionListenerCollection listeners;
+ try {
+ listeners = new SessionListenerCollection(httpSession);
+ }
+ catch (GuacamoleException e) {
+ logger.error("Failed to retrieve listeners. Authentication canceled.", e);
+ throw e;
+ }
+
+ // Get ID of connection
+ String id = request.getParameter("id");
+ IdentifierType id_type = IdentifierType.getType(id);
+
+ // Do not continue if unable to determine type
+ if (id_type == null)
+ throw new GuacamoleClientException("Illegal identifier - unknown type.");
+
+ // Remove prefix
+ id = id.substring(id_type.PREFIX.length());
+
+ // Get credentials
+ final Credentials credentials = getCredentials(httpSession);
+
+ // Get context
+ final UserContext context = getUserContext(httpSession);
+
+ // If no context or no credentials, not logged in
+ if (context == null || credentials == null)
+ throw new GuacamoleSecurityException("Cannot connect - user not logged in.");
+
+ // Get client information
+ GuacamoleClientInformation info = new GuacamoleClientInformation();
+
+ // Set width if provided
+ String width = request.getParameter("width");
+ if (width != null)
+ info.setOptimalScreenWidth(Integer.parseInt(width));
+
+ // Set height if provided
+ String height = request.getParameter("height");
+ if (height != null)
+ info.setOptimalScreenHeight(Integer.parseInt(height));
+
+ // Add audio mimetypes
+ String[] audio_mimetypes = request.getParameterValues("audio");
+ if (audio_mimetypes != null)
+ info.getAudioMimetypes().addAll(Arrays.asList(audio_mimetypes));
+
+ // Add video mimetypes
+ String[] video_mimetypes = request.getParameterValues("video");
+ if (video_mimetypes != null)
+ info.getVideoMimetypes().addAll(Arrays.asList(video_mimetypes));
+
+ // Create connected socket from identifier
+ GuacamoleSocket socket;
+ switch (id_type) {
+
+ // Connection identifiers
+ case CONNECTION: {
+
+ // Get connection directory
+ Directory<String, Connection> directory =
+ context.getRootConnectionGroup().getConnectionDirectory();
+
+ // Get authorized connection
+ Connection connection = directory.get(id);
+ if (connection == null) {
+ logger.warn("Connection id={} not found.", id);
+ throw new GuacamoleSecurityException("Requested connection is not authorized.");
+ }
+
+ // Connect socket
+ socket = connection.connect(info);
+ logger.info("Successful connection from {} to \"{}\".", request.getRemoteAddr(), id);
+ break;
+ }
+
+ // Connection group identifiers
+ case CONNECTION_GROUP: {
+
+ // Get connection group directory
+ Directory<String, ConnectionGroup> directory =
+ context.getRootConnectionGroup().getConnectionGroupDirectory();
+
+ // Get authorized connection group
+ ConnectionGroup group = directory.get(id);
+ if (group == null) {
+ logger.warn("Connection group id={} not found.", id);
+ throw new GuacamoleSecurityException("Requested connection group is not authorized.");
+ }
+
+ // Connect socket
+ socket = group.connect(info);
+ logger.info("Successful connection from {} to group \"{}\".", request.getRemoteAddr(), id);
+ break;
+ }
+
+ // Fail if unsupported type
+ default:
+ throw new GuacamoleClientException("Connection not supported for provided identifier type.");
+
+ }
+
+ // Associate socket with tunnel
+ GuacamoleTunnel tunnel = new GuacamoleTunnel(socket) {
+
+ @Override
+ public void close() throws GuacamoleException {
+
+ // Only close if not canceled
+ if (!notifyClose(listeners, context, credentials, this))
+ throw new GuacamoleException("Tunnel close canceled by listener.");
+
+ // Close if no exception due to listener
+ super.close();
+
+ }
+
+ };
+
+ // Notify listeners about connection
+ if (!notifyConnect(listeners, context, credentials, tunnel)) {
+ logger.info("Connection canceled by listener.");
+ return null;
+ }
+
+ return tunnel;
+
+ }
+
+ };
+
+ @Override
+ protected boolean hasNewCredentials(HttpServletRequest request) {
+
+ String query = request.getQueryString();
+ if (query == null)
+ return false;
+
+ // Only connections are given new credentials
+ return query.equals("connect");
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicLogin.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicLogin.java
new file mode 100644
index 0000000..af9d22f
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicLogin.java
@@ -0,0 +1,48 @@
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Simple dummy AuthenticatingHttpServlet which provides an endpoint for arbitrary
+ * authentication requests that do not expect a response.
+ *
+ * @author Michael Jumper
+ */
+public class BasicLogin extends AuthenticatingHttpServlet {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(BasicLogin.class);
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response) {
+ logger.info("Login was successful.");
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicLogout.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicLogout.java
new file mode 100644
index 0000000..6a5ab20
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/BasicLogout.java
@@ -0,0 +1,50 @@
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+/**
+ * Logs out the current user by invalidating the associated HttpSession and
+ * redirecting the user to the login page.
+ *
+ * @author Michael Jumper
+ */
+public class BasicLogout extends HttpServlet {
+
+ @Override
+ protected void service(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+
+ // Invalidate session, if any
+ HttpSession httpSession = request.getSession(false);
+ if (httpSession != null)
+ httpSession.invalidate();
+
+ // Redirect to index
+ response.sendRedirect("index.xhtml");
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/GuacamoleClassLoader.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/GuacamoleClassLoader.java
new file mode 100644
index 0000000..547431f
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/GuacamoleClassLoader.java
@@ -0,0 +1,169 @@
+
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.Collection;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.basic.properties.BasicGuacamoleProperties;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+
+/**
+ * A ClassLoader implementation which finds classes within a configurable
+ * directory. This directory is set within guacamole.properties.
+ *
+ * @author Michael Jumper
+ */
+public class GuacamoleClassLoader extends ClassLoader {
+
+ /**
+ * Class loader which will load classes from the classpath specified
+ * in guacamole.properties.
+ */
+ private URLClassLoader classLoader = null;
+
+ /**
+ * Any exception that occurs while the class loader is being instantiated.
+ */
+ private static GuacamoleException exception = null;
+
+ /**
+ * Singleton instance of the GuacamoleClassLoader.
+ */
+ private static GuacamoleClassLoader instance = null;
+
+ static {
+
+ try {
+ // Attempt to create singleton classloader which loads classes from
+ // all .jar's in the lib directory defined in guacamole.properties
+ instance = AccessController.doPrivileged(new PrivilegedExceptionAction<GuacamoleClassLoader>() {
+
+ @Override
+ public GuacamoleClassLoader run() throws GuacamoleException {
+ return new GuacamoleClassLoader(
+ GuacamoleProperties.getProperty(BasicGuacamoleProperties.LIB_DIRECTORY)
+ );
+ }
+
+ });
+ }
+
+ catch (PrivilegedActionException e) {
+ // On error, record exception
+ exception = (GuacamoleException) e.getException();
+ }
+
+ }
+
+ /**
+ * Creates a new GuacamoleClassLoader which reads classes from the given
+ * directory.
+ *
+ * @param libDirectory The directory to load classes from.
+ * @throws GuacamoleException If the file given is not a director, or if
+ * an error occurs while constructing the URL
+ * for the backing classloader.
+ */
+ private GuacamoleClassLoader(File libDirectory) throws GuacamoleException {
+
+ // If no directory provided, just direct requests to parent classloader
+ if (libDirectory == null)
+ return;
+
+ // Validate directory is indeed a directory
+ if (!libDirectory.isDirectory())
+ throw new GuacamoleException(libDirectory + " is not a directory.");
+
+ // Get list of URLs for all .jar's in the lib directory
+ Collection<URL> jarURLs = new ArrayList<URL>();
+ for (File file : libDirectory.listFiles(new FilenameFilter() {
+
+ @Override
+ public boolean accept(File dir, String name) {
+
+ // If it ends with .jar, accept the file
+ return name.endsWith(".jar");
+
+ }
+
+ })) {
+
+ try {
+
+ // Add URL for the .jar to the jar URL list
+ jarURLs.add(file.toURI().toURL());
+
+ }
+ catch (MalformedURLException e) {
+ throw new GuacamoleException(e);
+ }
+
+ }
+
+ // Set delegate classloader to new URLClassLoader which loads from the
+ // .jars found above.
+
+ URL[] urls = new URL[jarURLs.size()];
+ classLoader = new URLClassLoader(
+ jarURLs.toArray(urls),
+ getClass().getClassLoader()
+ );
+
+ }
+
+ /**
+ * Returns an instance of a GuacamoleClassLoader which finds classes
+ * within the directory configured in guacamole.properties.
+ *
+ * @return An instance of a GuacamoleClassLoader.
+ * @throws GuacamoleException If no instance could be returned due to an
+ * error.
+ */
+ public static GuacamoleClassLoader getInstance() throws GuacamoleException {
+
+ // If instance could not be created, rethrow original exception
+ if (exception != null) throw exception;
+
+ return instance;
+
+ }
+
+ @Override
+ protected Class<?> findClass(String name) throws ClassNotFoundException {
+
+ // If no classloader, use default loader
+ if (classLoader == null)
+ return Class.forName(name);
+
+ // Otherwise, delegate
+ return classLoader.loadClass(name);
+
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolInfo.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolInfo.java
new file mode 100644
index 0000000..149190d
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolInfo.java
@@ -0,0 +1,99 @@
+
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * Describes a protocol and all parameters associated with it, as required by
+ * a protocol plugin for guacd. This class allows known parameters for a
+ * protocol to be exposed to the user as friendly fields.
+ *
+ * @author Michael Jumper
+ */
+public class ProtocolInfo {
+
+ /**
+ * The human-readable title associated with this protocol.
+ */
+ private String title;
+
+ /**
+ * The unique name associated with this protocol.
+ */
+ private String name;
+
+ /**
+ * A collection of all associated protocol parameters.
+ */
+ private Collection<ProtocolParameter> parameters =
+ new ArrayList<ProtocolParameter>();
+
+ /**
+ * Returns the human-readable title associated with this protocol.
+ *
+ * @return The human-readable title associated with this protocol.
+ */
+ public String getTitle() {
+ return title;
+ }
+
+ /**
+ * Sets the human-readable title associated with this protocol.
+ *
+ * @param title The human-readable title to associate with this protocol.
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ /**
+ * Returns the unique name of this protocol. The protocol name is the
+ * value required by the corresponding protocol plugin for guacd.
+ *
+ * @return The unique name of this protocol.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the unique name of this protocol. The protocol name is the value
+ * required by the corresponding protocol plugin for guacd.
+ *
+ * @param name The unique name of this protocol.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Returns a mutable collection of the protocol parameters associated with
+ * this protocol. Changes to this collection affect the parameters exposed
+ * to the user.
+ *
+ * @return A mutable collection of protocol parameters.
+ */
+ public Collection<ProtocolParameter> getParameters() {
+ return parameters;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolParameter.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolParameter.java
new file mode 100644
index 0000000..4b2319e
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolParameter.java
@@ -0,0 +1,171 @@
+
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * Represents a parameter of a protocol.
+ *
+ * @author Michael Jumper
+ */
+public class ProtocolParameter {
+
+ /**
+ * All possible types of protocol parameter.
+ */
+ public enum Type {
+
+ /**
+ * A text parameter, accepting arbitrary values.
+ */
+ TEXT,
+
+ /**
+ * A password parameter, whose value is sensitive and must be hidden.
+ */
+ PASSWORD,
+
+ /**
+ * A numeric parameter, whose value must contain only digits.
+ */
+ NUMERIC,
+
+ /**
+ * A boolean parameter, whose value is either blank or "true".
+ */
+ BOOLEAN,
+
+ /**
+ * An enumerated parameter, whose legal values are fully enumerated
+ * by a provided, finite list.
+ */
+ ENUM
+ }
+
+ /**
+ * The unique name that identifies this parameter to the protocol plugin.
+ */
+ private String name;
+
+ /**
+ * A human-readable name to be presented to the user.
+ */
+ private String title;
+
+ /**
+ * The type of this field.
+ */
+ private Type type;
+
+ /**
+ * The value of this parameter, for boolean parameters.
+ */
+ private String value;
+
+ /**
+ * A collection of all associated parameter options.
+ */
+ private Collection<ProtocolParameterOption> options =
+ new ArrayList<ProtocolParameterOption>();
+
+ /**
+ * Returns the name associated with this protocol parameter.
+ * @return The name associated with this protocol parameter.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the name associated with this protocol parameter. This name must
+ * uniquely identify this parameter among the others accepted by the
+ * corresponding protocol.
+ *
+ * @param name The name to assign to this protocol parameter.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the title associated with this protocol parameter.
+ * @return The title associated with this protocol parameter.
+ */
+ public String getTitle() {
+ return title;
+ }
+
+ /**
+ * Sets the title associated with this protocol parameter. The title must
+ * be a human-readable string which describes accurately this parameter.
+ *
+ * @param title A human-readable string describing this parameter.
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ /**
+ * Returns the value associated with this protocol parameter.
+ * @return The value associated with this protocol parameter.
+ */
+ public String getValue() {
+ return value;
+ }
+
+ /**
+ * Sets the value associated with this protocol parameter. The value must
+ * be a human-readable string which describes accurately this parameter.
+ *
+ * @param value A human-readable string describing this parameter.
+ */
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ /**
+ * Returns the type of this parameter.
+ * @return The type of this parameter.
+ */
+ public Type getType() {
+ return type;
+ }
+
+ /**
+ * Sets the type of this parameter.
+ * @param type The type of this parameter.
+ */
+ public void setType(Type type) {
+ this.type = type;
+ }
+
+ /**
+ * Returns a mutable collection of protocol parameter options. Changes to
+ * this collection directly affect the available options.
+ *
+ * @return A mutable collection of parameter options.
+ */
+ public Collection<ProtocolParameterOption> getOptions() {
+ return options;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolParameterOption.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolParameterOption.java
new file mode 100644
index 0000000..5e7231e
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/ProtocolParameterOption.java
@@ -0,0 +1,76 @@
+
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Describes an available legal value for an enumerated protocol parameter.
+ *
+ * @author Michael Jumper
+ */
+public class ProtocolParameterOption {
+
+ /**
+ * The value that will be sent to the client plugin if this option is
+ * chosen.
+ */
+ private String value;
+
+ /**
+ * A human-readable title describing the effect of the value.
+ */
+ private String title;
+
+ /**
+ * Returns the value that will be sent to the client plugin if this option
+ * is chosen.
+ *
+ * @return The value that will be sent if this option is chosen.
+ */
+ public String getValue() {
+ return value;
+ }
+
+ /**
+ * Sets the value that will be sent to the client plugin if this option is
+ * chosen.
+ *
+ * @param value The value to send if this option is chosen.
+ */
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ /**
+ * Returns the human-readable title describing the effect of this option.
+ * @return The human-readable title describing the effect of this option.
+ */
+ public String getTitle() {
+ return title;
+ }
+
+ /**
+ * Sets the human-readable title describing the effect of this option.
+ * @param title A human-readable title describing the effect of this option.
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/WebSocketSupportLoader.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/WebSocketSupportLoader.java
new file mode 100644
index 0000000..ecf88c2
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/WebSocketSupportLoader.java
@@ -0,0 +1,114 @@
+package org.glyptodon.guacamole.net.basic;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import javax.servlet.Servlet;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Simple ServletContextListener which loads a WebSocket tunnel implementation
+ * if available, using the Servlet 3.0 API to dynamically load and install
+ * the tunnel servlet.
+ *
+ * Note that because Guacamole depends on the Servlet 2.5 API, and 3.0 may
+ * not be available or needed if WebSocket is not desired, the 3.0 API is
+ * detected and invoked dynamically via reflection.
+ *
+ * @author Michael Jumper
+ */
+public class WebSocketSupportLoader implements ServletContextListener {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(WebSocketSupportLoader.class);
+
+ @Override
+ public void contextDestroyed(ServletContextEvent sce) {
+ }
+
+ @Override
+ public void contextInitialized(ServletContextEvent sce) {
+
+ try {
+
+ // Attempt to find WebSocket servlet
+ Class<Servlet> servlet = (Class<Servlet>) GuacamoleClassLoader.getInstance().findClass(
+ "org.glyptodon.guacamole.net.basic.BasicGuacamoleWebSocketTunnelServlet"
+ );
+
+ // Dynamically add servlet IF SERVLET 3.0 API AVAILABLE!
+ try {
+
+ // Get servlet registration class
+ Class regClass = Class.forName("javax.servlet.ServletRegistration");
+
+ // Get and invoke addServlet()
+ Method addServlet = ServletContext.class.getMethod("addServlet", String.class, Class.class);
+ Object reg = addServlet.invoke(sce.getServletContext(), "WebSocketTunnel", servlet);
+
+ // Get and invoke addMapping()
+ Method addMapping = regClass.getMethod("addMapping", String[].class);
+ addMapping.invoke(reg, (Object) new String[]{"/websocket-tunnel"});
+
+ // If we succesfully load and register the WebSocket tunnel servlet,
+ // WebSocket is supported.
+ logger.info("WebSocket support found and loaded.");
+
+ }
+
+ // Servlet API 3.0 unsupported
+ catch (ClassNotFoundException e) {
+ logger.info("Servlet API 3.0 not found.", e);
+ }
+ catch (NoSuchMethodException e) {
+ logger.warn("Servlet API 3.0 found, but incomplete.", e);
+ }
+
+ // Servlet API 3.0 found, but errors during use
+ catch (IllegalAccessException e) {
+ logger.error("Unable to load WebSocket tunnel servlet.", e);
+ }
+ catch (InvocationTargetException e) {
+ logger.error("Internal error loading WebSocket tunnel servlet.", e);
+ }
+
+ }
+
+ // If no such servlet class, WebSocket support not present
+ catch (ClassNotFoundException e) {
+ logger.info("WebSocket support not found.");
+ }
+
+ // Log all GuacamoleExceptions
+ catch (GuacamoleException e) {
+ logger.error("Unable to load/detect WebSocket support.", e);
+ }
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/Authorization.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/Authorization.java
new file mode 100644
index 0000000..4293f08
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/Authorization.java
@@ -0,0 +1,251 @@
+package org.glyptodon.guacamole.net.basic.auth;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Map;
+import java.util.TreeMap;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+/**
+ * Mapping of username/password pair to configuration set. In addition to basic
+ * storage of the username, password, and configurations, this class also
+ * provides password validation functions.
+ *
+ * @author Mike Jumper
+ */
+public class Authorization {
+
+ /**
+ * All supported password encodings.
+ */
+ public static enum Encoding {
+
+ /**
+ * Plain-text password (not hashed at all).
+ */
+ PLAIN_TEXT,
+
+ /**
+ * Password hashed with MD5.
+ */
+ MD5
+
+ }
+
+ /**
+ * The username being authorized.
+ */
+ private String username;
+
+ /**
+ * The password corresponding to the username being authorized, which may
+ * be hashed.
+ */
+ private String password;
+
+ /**
+ * The encoding used when the password was hashed.
+ */
+ private Encoding encoding = Encoding.PLAIN_TEXT;
+
+ /**
+ * Map of all authorized configurations, indexed by configuration name.
+ */
+ private Map<String, GuacamoleConfiguration> configs = new
+ TreeMap<String, GuacamoleConfiguration>();
+
+ /**
+ * Lookup table of hex bytes characters by value.
+ */
+ private static final char HEX_CHARS[] = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+
+ /**
+ * Produces a String containing the bytes provided in hexadecimal notation.
+ *
+ * @param bytes The bytes to convert into hex.
+ * @return A String containing the hex representation of the given bytes.
+ */
+ private static String getHexString(byte[] bytes) {
+
+ // If null byte array given, return null
+ if (bytes == null)
+ return null;
+
+ // Create string builder for holding the hex representation,
+ // pre-calculating the exact length
+ StringBuilder hex = new StringBuilder(2 * bytes.length);
+
+ // Convert each byte into a pair of hex digits
+ for (byte b : bytes) {
+ hex.append(HEX_CHARS[(b & 0xF0) >> 4])
+ .append(HEX_CHARS[ b & 0x0F ]);
+ }
+
+ // Return the string produced
+ return hex.toString();
+
+ }
+
+ /**
+ * Returns the username associated with this authorization.
+ *
+ * @return The username associated with this authorization.
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * Sets the username associated with this authorization.
+ *
+ * @param username The username to associate with this authorization.
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ /**
+ * Returns the password associated with this authorization, which may be
+ * encoded or hashed.
+ *
+ * @return The password associated with this authorization.
+ */
+ public String getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the password associated with this authorization, which must be
+ * encoded using the encoding specified with setEncoding(). By default,
+ * passwords are plain text.
+ *
+ * @param password Sets the password associated with this authorization.
+ */
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ /**
+ * Returns the encoding used to hash the password, if any.
+ *
+ * @return The encoding used to hash the password.
+ */
+ public Encoding getEncoding() {
+ return encoding;
+ }
+
+ /**
+ * Sets the encoding which will be used to hash the password or when
+ * comparing a given password for validation.
+ *
+ * @param encoding The encoding to use for password hashing.
+ */
+ public void setEncoding(Encoding encoding) {
+ this.encoding = encoding;
+ }
+
+ /**
+ * Returns whether a given username/password pair is authorized based on
+ * the stored username and password. The password given must be plain text.
+ * It will be hashed as necessary to perform the validation.
+ *
+ * @param username The username to validate.
+ * @param password The password to validate.
+ * @return true if the username/password pair given is authorized, false
+ * otherwise.
+ */
+ public boolean validate(String username, String password) {
+
+ // If username matches
+ if (username != null && password != null
+ && username.equals(this.username)) {
+
+ switch (encoding) {
+
+ // If plain text, just compare
+ case PLAIN_TEXT:
+
+ // Compare plaintext
+ return password.equals(this.password);
+
+ // If hased with MD5, hash password and compare
+ case MD5:
+
+ // Compare hashed password
+ try {
+ MessageDigest digest = MessageDigest.getInstance("MD5");
+ String hashedPassword = getHexString(digest.digest(password.getBytes("UTF-8")));
+ return hashedPassword.equals(this.password.toUpperCase());
+ }
+ catch (UnsupportedEncodingException e) {
+ throw new UnsupportedOperationException("Unexpected lack of UTF-8 support.", e);
+ }
+ catch (NoSuchAlgorithmException e) {
+ throw new UnsupportedOperationException("Unexpected lack of MD5 support.", e);
+ }
+
+ }
+
+ } // end validation check
+
+ return false;
+
+ }
+
+ /**
+ * Returns the GuacamoleConfiguration having the given name and associated
+ * with the username/password pair stored within this authorization.
+ *
+ * @param name The name of the GuacamoleConfiguration to return.
+ * @return The GuacamoleConfiguration having the given name, or null if no
+ * such GuacamoleConfiguration exists.
+ */
+ public GuacamoleConfiguration getConfiguration(String name) {
+ return configs.get(name);
+ }
+
+ /**
+ * Adds the given GuacamoleConfiguration to the set of stored configurations
+ * under the given name.
+ *
+ * @param name The name to associate this GuacamoleConfiguration with.
+ * @param config The GuacamoleConfiguration to store.
+ */
+ public void addConfiguration(String name, GuacamoleConfiguration config) {
+ configs.put(name, config);
+ }
+
+ /**
+ * Returns a Map of all stored GuacamoleConfigurations associated with the
+ * username/password pair stored within this authorization, indexed by
+ * configuration name.
+ *
+ * @return A Map of all stored GuacamoleConfigurations.
+ */
+ public Map<String, GuacamoleConfiguration> getConfigurations() {
+ return configs;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/UserMapping.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/UserMapping.java
new file mode 100644
index 0000000..f130f2e
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/UserMapping.java
@@ -0,0 +1,59 @@
+package org.glyptodon.guacamole.net.basic.auth;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+/**
+ * Mapping of all usernames to corresponding authorizations.
+ *
+ * @author Mike Jumper
+ */
+public class UserMapping {
+
+ /**
+ * All authorizations, indexed by username.
+ */
+ private Map<String, Authorization> authorizations =
+ new HashMap<String, Authorization>();
+
+ /**
+ * Adds the given authorization to the user mapping.
+ *
+ * @param authorization The authorization to add to the user mapping.
+ */
+ public void addAuthorization(Authorization authorization) {
+ authorizations.put(authorization.getUsername(), authorization);
+ }
+
+ /**
+ * Returns the authorization corresponding to the user having the given
+ * username, if any.
+ *
+ * @param username The username to find the authorization for.
+ * @return The authorization corresponding to the user having the given
+ * username, or null if no such authorization exists.
+ */
+ public Authorization getAuthorization(String username) {
+ return authorizations.get(username);
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/package-info.java
new file mode 100644
index 0000000..df9a376
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/auth/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes which drive the default, basic authentication of the Guacamole
+ * web application.
+ */
+package org.glyptodon.guacamole.net.basic.auth;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/ConnectionGroupUtility.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/ConnectionGroupUtility.java
new file mode 100644
index 0000000..f1a6c8e
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/ConnectionGroupUtility.java
@@ -0,0 +1,67 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+
+/**
+ * A class that provides helper methods for the ConnectionGroup CRUD servlets.
+ *
+ * @author James Muehlner
+ */
+class ConnectionGroupUtility {
+
+ // This class should not be instantiated
+ private ConnectionGroupUtility() {}
+
+ /**
+ * Get the ConnectionGroupDirectory with the parent connection group
+ * specified by parentID.
+ *
+ * @param context The UserContext to search for the connectionGroup directory.
+ * @param parentID The ID of the parent connection group to search for.
+ *
+ * @return The ConnectionGroupDirectory with the parent connection group,
+ * if found.
+ * @throws GuacamoleException If an error is encountered while getting the
+ * connection group directory.
+ */
+ static Directory<String, ConnectionGroup> findConnectionGroupDirectory(
+ UserContext context, String parentID) throws GuacamoleException {
+
+ // Find the correct connection group directory
+ ConnectionGroup rootGroup = context.getRootConnectionGroup();
+ Directory<String, ConnectionGroup> directory;
+
+ Directory<String, ConnectionGroup> connectionGroupDirectory =
+ rootGroup.getConnectionGroupDirectory();
+
+ ConnectionGroup parentGroup = connectionGroupDirectory.get(parentID);
+
+ if(parentGroup == null)
+ return null;
+
+ directory = parentGroup.getConnectionGroupDirectory();
+
+ return directory;
+ }
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Create.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Create.java
new file mode 100644
index 0000000..514b646
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Create.java
@@ -0,0 +1,71 @@
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles connection group creation.
+ *
+ * @author James Muehlner
+ */
+public class Create extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get name and type
+ String name = request.getParameter("name");
+ String type = request.getParameter("type");
+
+ // Get the ID of the parent connection group
+ String parentID = request.getParameter("parentID");
+
+ // Find the correct connection group directory
+ Directory<String, ConnectionGroup> directory =
+ ConnectionGroupUtility.findConnectionGroupDirectory(context, parentID);
+
+ if(directory == null)
+ throw new GuacamoleException("Connection group directory not found.");
+
+ // Create connection skeleton
+ ConnectionGroup connectionGroup = new DummyConnectionGroup();
+ connectionGroup.setName(name);
+
+ if("balancing".equals(type))
+ connectionGroup.setType(ConnectionGroup.Type.BALANCING);
+ else if("organizational".equals(type))
+ connectionGroup.setType(ConnectionGroup.Type.ORGANIZATIONAL);
+
+ // Add connection
+ directory.add(connectionGroup);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Delete.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Delete.java
new file mode 100644
index 0000000..f8a9dba
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Delete.java
@@ -0,0 +1,56 @@
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles connection group deletion.
+ *
+ * @author Michael Jumper
+ */
+public class Delete extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get ID
+ String identifier = request.getParameter("id");
+
+ // Attempt to get connection group directory
+ Directory<String, ConnectionGroup> directory =
+ context.getRootConnectionGroup().getConnectionGroupDirectory();
+
+ // Remove connection
+ directory.remove(identifier);
+
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/DummyConnectionGroup.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/DummyConnectionGroup.java
new file mode 100644
index 0000000..19a93d4
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/DummyConnectionGroup.java
@@ -0,0 +1,39 @@
+
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.auth.AbstractConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+
+/**
+ * Basic ConnectionGroup skeleton, providing a means of storing Connection data
+ * prior to CRUD operations. This ConnectionGroup has no functionality for actually
+ * performing a connection operation, and does not promote any of the
+ * semantics that would otherwise be present because of the authentication
+ * provider. It is up to the authentication provider to create a new
+ * ConnectionGroup based on the information contained herein.
+ *
+ * @author James Muehlner
+ */
+public class DummyConnectionGroup extends AbstractConnectionGroup {
+
+ @Override
+ public GuacamoleSocket connect(GuacamoleClientInformation info) throws GuacamoleException {
+ throw new UnsupportedOperationException("Connection unsupported in DummyConnectionGroup.");
+ }
+
+ @Override
+ public Directory<String, Connection> getConnectionDirectory() throws GuacamoleException {
+ throw new UnsupportedOperationException("Connection directory unsupported in DummyConnectionGroup.");
+ }
+
+ @Override
+ public Directory<String, ConnectionGroup> getConnectionGroupDirectory() throws GuacamoleException {
+ throw new UnsupportedOperationException("Connection group directory unsuppprted in DummyConnectionGroup.");
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/List.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/List.java
new file mode 100644
index 0000000..cbce896
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/List.java
@@ -0,0 +1,214 @@
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import java.util.Set;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which outputs XML containing a list of all authorized
+ * connection groups for the current user.
+ *
+ * @author Michael Jumper
+ */
+public class List extends AuthenticatingHttpServlet {
+
+ /**
+ * System administration permission.
+ */
+ private static final Permission SYSTEM_PERMISSION =
+ new SystemPermission(SystemPermission.Type.ADMINISTER);
+
+
+ /**
+ * Checks whether the given user has permission to perform the given
+ * object operation. Security exceptions are handled appropriately - only
+ * non-security exceptions pass through.
+ *
+ * @param user The user whose permissions should be verified.
+ * @param type The type of operation to check for permission for.
+ * @param identifier The identifier of the connection the operation
+ * would be performed upon.
+ * @return true if permission is granted, false otherwise.
+ *
+ * @throws GuacamoleException If an error occurs while checking permissions.
+ */
+ private boolean hasConfigPermission(User user, ObjectPermission.Type type,
+ String identifier)
+ throws GuacamoleException {
+
+ // Build permission
+ Permission permission = new ConnectionPermission(
+ type,
+ identifier
+ );
+
+ try {
+ // Return result of permission check, if possible
+ return user.hasPermission(permission);
+ }
+ catch (GuacamoleSecurityException e) {
+ // If cannot check due to security restrictions, no permission
+ return false;
+ }
+
+ }
+
+ /**
+ * Writes the XML for the given connection group.
+ *
+ * @param self The user whose permissions dictate the availability of the
+ * data written.
+ * @param xml The XMLStremWriter to use when writing the data.
+ * @param group The connection group whose XML representation will be
+ * written.
+ * @throws GuacamoleException If an error occurs while reading the
+ * requested data.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeConnectionGroup(User self, XMLStreamWriter xml,
+ ConnectionGroup group) throws GuacamoleException, XMLStreamException {
+
+ // Write group
+ xml.writeStartElement("group");
+ xml.writeAttribute("id", group.getIdentifier());
+ xml.writeAttribute("name", group.getName());
+
+ // Write group type
+ switch (group.getType()) {
+
+ case ORGANIZATIONAL:
+ xml.writeAttribute("type", "organizational");
+ break;
+
+ case BALANCING:
+ xml.writeAttribute("type", "balancing");
+ break;
+
+ }
+
+ // Write contained connection groups
+ writeConnectionGroups(self, xml, group.getConnectionGroupDirectory());
+
+ // End of group
+ xml.writeEndElement();
+
+ }
+
+ /**
+ * Writes the XML for the given directory of connection groups.
+ *
+ * @param self The user whose permissions dictate the availability of the
+ * data written.
+ * @param xml The XMLStremWriter to use when writing the data.
+ * @param directory The directory whose XML representation will be
+ * written.
+ * @throws GuacamoleException If an error occurs while reading the
+ * requested data.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeConnectionGroups(User self, XMLStreamWriter xml,
+ Directory<String, ConnectionGroup> directory)
+ throws GuacamoleException, XMLStreamException {
+
+ // If no connections, write nothing
+ Set<String> identifiers = directory.getIdentifiers();
+ if (identifiers.isEmpty())
+ return;
+
+ // Begin connections
+ xml.writeStartElement("groups");
+
+ // For each entry, write corresponding connection element
+ for (String identifier : identifiers) {
+
+ // Write each group
+ ConnectionGroup group = directory.get(identifier);
+ writeConnectionGroup(self, xml, group);
+
+ }
+
+ // End connections
+ xml.writeEndElement();
+
+ }
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Do not cache
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Write XML content type
+ response.setHeader("Content-Type", "text/xml");
+
+ // Set encoding
+ response.setCharacterEncoding("UTF-8");
+
+ // Get root group
+ ConnectionGroup root = context.getRootConnectionGroup();
+
+ // Write actual XML
+ try {
+
+ // Get self
+ User self = context.self();
+
+ XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
+ XMLStreamWriter xml = outputFactory.createXMLStreamWriter(response.getWriter());
+
+ // Write content of root group
+ xml.writeStartDocument();
+ writeConnectionGroup(self, xml, root);
+ xml.writeEndDocument();
+
+ }
+ catch (XMLStreamException e) {
+ throw new GuacamoleServerException(
+ "Unable to write connection group list XML.", e);
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(
+ "I/O error writing connection group list XML.", e);
+ }
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Move.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Move.java
new file mode 100644
index 0000000..51df4b1
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Move.java
@@ -0,0 +1,62 @@
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles moving connection groups.
+ *
+ * @author James Muehlner
+ */
+public class Move extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get ID
+ String identifier = request.getParameter("id");
+
+ // Get the identifier of the new parent connection group
+ String parentID = request.getParameter("parentID");
+
+ // Attempt to get the new parent connection group directory
+ Directory<String, ConnectionGroup> newParentDirectory =
+ ConnectionGroupUtility.findConnectionGroupDirectory(context, parentID);
+
+ // Attempt to get root connection group directory
+ Directory<String, ConnectionGroup> directory =
+ context.getRootConnectionGroup().getConnectionGroupDirectory();
+
+ // Move connection group
+ directory.move(identifier, newParentDirectory);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Update.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Update.java
new file mode 100644
index 0000000..7eeb184
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/Update.java
@@ -0,0 +1,66 @@
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles connection group update.
+ *
+ * @author James Muehlner
+ */
+public class Update extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get ID, name, and type
+ String identifier = request.getParameter("id");
+ String name = request.getParameter("name");
+ String type = request.getParameter("type");
+
+ // Attempt to get connection group directory
+ Directory<String, ConnectionGroup> directory =
+ context.getRootConnectionGroup().getConnectionGroupDirectory();
+
+ // Create connection group skeleton
+ ConnectionGroup connectionGroup = directory.get(identifier);
+ connectionGroup.setName(name);
+
+ if("balancing".equals(type))
+ connectionGroup.setType(ConnectionGroup.Type.BALANCING);
+ else if("organizational".equals(type))
+ connectionGroup.setType(ConnectionGroup.Type.ORGANIZATIONAL);
+
+ // Update connection group
+ directory.update(connectionGroup);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/package-info.java
new file mode 100644
index 0000000..af319d4
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connectiongroups/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Servlets dedicated to CRUD operations related to ConnectionGroups.
+ */
+package org.glyptodon.guacamole.net.basic.crud.connectiongroups;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/ConnectionUtility.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/ConnectionUtility.java
new file mode 100644
index 0000000..0b3f8dd
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/ConnectionUtility.java
@@ -0,0 +1,68 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+
+/**
+ * A class that provides helper methods for the Connection CRUD servlets.
+ *
+ * @author James Muehlner
+ */
+class ConnectionUtility {
+
+ // This class should not be instantiated
+ private ConnectionUtility() {}
+
+ /**
+ * Get the ConnectionDirectory with the parent connection group specified by
+ * parentID.
+ *
+ * @param context The UserContext to search for the connection directory.
+ * @param parentID The ID of the parent connection group to search for.
+ *
+ * @return The ConnectionDirectory with the parent connection group,
+ * if found.
+ * @throws GuacamoleException If an error is encountered while getting the
+ * connection directory.
+ */
+ static Directory<String, Connection> findConnectionDirectory(
+ UserContext context, String parentID) throws GuacamoleException {
+
+ // Find the correct connection directory
+ ConnectionGroup rootGroup = context.getRootConnectionGroup();
+ Directory<String, Connection> directory;
+
+ Directory<String, ConnectionGroup> connectionGroupDirectory =
+ rootGroup.getConnectionGroupDirectory();
+
+ ConnectionGroup parentGroup = connectionGroupDirectory.get(parentID);
+
+ if(parentGroup == null)
+ return null;
+
+ directory = parentGroup.getConnectionDirectory();
+
+ return directory;
+ }
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Create.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Create.java
new file mode 100644
index 0000000..e01972e
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Create.java
@@ -0,0 +1,93 @@
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.Enumeration;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+/**
+ * Simple HttpServlet which handles connection creation.
+ *
+ * @author Michael Jumper
+ */
+public class Create extends AuthenticatingHttpServlet {
+
+ /**
+ * Prefix given to a parameter name when that parameter is a protocol-
+ * specific parameter meant for the configuration.
+ */
+ public static final String PARAMETER_PREFIX = "_";
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get name and protocol
+ String name = request.getParameter("name");
+ String protocol = request.getParameter("protocol");
+
+ // Get the ID of the parent connection group
+ String parentID = request.getParameter("parentID");
+
+ // Find the correct connection directory
+ Directory<String, Connection> directory =
+ ConnectionUtility.findConnectionDirectory(context, parentID);
+
+ if(directory == null)
+ throw new GuacamoleException("Connection directory not found.");
+
+ // Create config
+ GuacamoleConfiguration config = new GuacamoleConfiguration();
+ config.setProtocol(protocol);
+
+ // Load parameters into config
+ Enumeration<String> params = request.getParameterNames();
+ while (params.hasMoreElements()) {
+
+ // If parameter starts with prefix, load corresponding parameter
+ // value into config
+ String param = params.nextElement();
+ if (param.startsWith(PARAMETER_PREFIX))
+ config.setParameter(
+ param.substring(PARAMETER_PREFIX.length()),
+ request.getParameter(param));
+
+ }
+
+ // Create connection skeleton
+ Connection connection = new DummyConnection();
+ connection.setName(name);
+ connection.setConfiguration(config);
+
+ // Add connection
+ directory.add(connection);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Delete.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Delete.java
new file mode 100644
index 0000000..5383346
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Delete.java
@@ -0,0 +1,56 @@
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles connection deletion.
+ *
+ * @author Michael Jumper
+ */
+public class Delete extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get ID
+ String identifier = request.getParameter("id");
+
+ // Attempt to get connection directory
+ Directory<String, Connection> directory =
+ context.getRootConnectionGroup().getConnectionDirectory();
+
+ // Remove connection
+ directory.remove(identifier);
+
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/DummyConnection.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/DummyConnection.java
new file mode 100644
index 0000000..10218fa
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/DummyConnection.java
@@ -0,0 +1,33 @@
+
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+import java.util.List;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.GuacamoleSocket;
+import org.glyptodon.guacamole.net.auth.AbstractConnection;
+import org.glyptodon.guacamole.net.auth.ConnectionRecord;
+import org.glyptodon.guacamole.protocol.GuacamoleClientInformation;
+
+/**
+ * Basic Connection skeleton, providing a means of storing Connection data
+ * prior to CRUD operations. This Connection has no functionality for actually
+ * performing a connection operation, and does not promote any of the
+ * semantics that would otherwise be present because of the authentication
+ * provider. It is up to the authentication provider to create a new
+ * Connection based on the information contained herein.
+ *
+ * @author Michael Jumper
+ */
+public class DummyConnection extends AbstractConnection {
+
+ @Override
+ public GuacamoleSocket connect(GuacamoleClientInformation info) throws GuacamoleException {
+ throw new UnsupportedOperationException("Connection unsupported in DummyConnection.");
+ }
+
+ @Override
+ public List<ConnectionRecord> getHistory() throws GuacamoleException {
+ throw new UnsupportedOperationException("History unsupported in DummyConnection.");
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/List.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/List.java
new file mode 100644
index 0000000..e8f20c9
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/List.java
@@ -0,0 +1,338 @@
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import java.util.Set;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.ConnectionGroup;
+import org.glyptodon.guacamole.net.auth.ConnectionRecord;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionGroupPermission;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+/**
+ * Simple HttpServlet which outputs XML containing a list of all authorized
+ * configurations for the current user.
+ *
+ * @author Michael Jumper
+ */
+public class List extends AuthenticatingHttpServlet {
+
+ /**
+ * System administration permission.
+ */
+ private static final Permission SYSTEM_PERMISSION =
+ new SystemPermission(SystemPermission.Type.ADMINISTER);
+
+
+ /**
+ * Checks whether the given user has permission to perform the given
+ * object operation. Security exceptions are handled appropriately - only
+ * non-security exceptions pass through.
+ *
+ * @param user The user whose permissions should be verified.
+ * @param type The type of operation to check for permission for.
+ * @param identifier The identifier of the connection the operation
+ * would be performed upon.
+ * @return true if permission is granted, false otherwise.
+ *
+ * @throws GuacamoleException If an error occurs while checking permissions.
+ */
+ private boolean hasConfigPermission(User user, ObjectPermission.Type type,
+ String identifier)
+ throws GuacamoleException {
+
+ // Build permission
+ Permission permission = new ConnectionPermission(
+ type,
+ identifier
+ );
+
+ try {
+ // Return result of permission check, if possible
+ return user.hasPermission(permission);
+ }
+ catch (GuacamoleSecurityException e) {
+ // If cannot check due to security restrictions, no permission
+ return false;
+ }
+
+ }
+
+ /**
+ * Writes the XML for the given connection group.
+ *
+ * @param self The user whose permissions dictate the availability of the
+ * data written.
+ * @param xml The XMLStremWriter to use when writing the data.
+ * @param group The connection group whose XML representation will be
+ * written.
+ * @throws GuacamoleException If an error occurs while reading the
+ * requested data.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeConnectionGroup(User self, XMLStreamWriter xml,
+ ConnectionGroup group) throws GuacamoleException, XMLStreamException {
+
+ // Write group
+ xml.writeStartElement("group");
+ xml.writeAttribute("id", group.getIdentifier());
+ xml.writeAttribute("name", group.getName());
+
+ // Write group type
+ switch (group.getType()) {
+
+ case ORGANIZATIONAL:
+ xml.writeAttribute("type", "organizational");
+ break;
+
+ case BALANCING:
+ xml.writeAttribute("type", "balancing");
+ break;
+
+ }
+
+ Permission group_admin_permission = new ConnectionGroupPermission(
+ ObjectPermission.Type.ADMINISTER, group.getIdentifier());
+
+ // Attempt to list contained groups and connections ONLY if the group
+ // is organizational or we have admin rights to it
+ if (group.getType() == ConnectionGroup.Type.ORGANIZATIONAL
+ || self.hasPermission(SYSTEM_PERMISSION)
+ || self.hasPermission(group_admin_permission)) {
+ writeConnections(self, xml, group.getConnectionDirectory());
+ writeConnectionGroups(self, xml, group.getConnectionGroupDirectory());
+ }
+
+ // End of group
+ xml.writeEndElement();
+
+ }
+
+ /**
+ * Writes the XML for the given connection.
+ *
+ * @param self The user whose permissions dictate the availability of the
+ * data written.
+ * @param xml The XMLStremWriter to use when writing the data.
+ * @param connection The connection whose XML representation will be
+ * written.
+ * @throws GuacamoleException If an error occurs while reading the
+ * requested data.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeConnection(User self, XMLStreamWriter xml,
+ Connection connection) throws GuacamoleException, XMLStreamException {
+
+ // Write connection
+ xml.writeStartElement("connection");
+ xml.writeAttribute("id", connection.getIdentifier());
+ xml.writeAttribute("name", connection.getName());
+ xml.writeAttribute("protocol",
+ connection.getConfiguration().getProtocol());
+
+ // If update permission available, include parameters
+ if (self.hasPermission(SYSTEM_PERMISSION) ||
+ hasConfigPermission(self, ObjectPermission.Type.UPDATE,
+ connection.getIdentifier())) {
+
+ // As update permission is present, also list parameters
+ GuacamoleConfiguration config = connection.getConfiguration();
+ for (String name : config.getParameterNames()) {
+
+ String value = connection.getConfiguration().getParameter(name);
+ xml.writeStartElement("param");
+ xml.writeAttribute("name", name);
+
+ if (value != null)
+ xml.writeCharacters(value);
+
+ xml.writeEndElement();
+ }
+
+ }
+
+ // Write history
+ xml.writeStartElement("history");
+ for (ConnectionRecord record : connection.getHistory()) {
+ xml.writeStartElement("record");
+
+ // Start date
+ xml.writeAttribute("start",
+ Long.toString(record.getStartDate().getTime()));
+
+ // End date
+ if (record.getEndDate() != null)
+ xml.writeAttribute("end",
+ Long.toString(record.getEndDate().getTime()));
+
+ // Whether connection currently active
+ if (record.isActive())
+ xml.writeAttribute("active", "yes");
+
+ // User involved
+ xml.writeCharacters(record.getUsername());
+
+ xml.writeEndElement();
+ }
+ xml.writeEndElement();
+
+ // End connection
+ xml.writeEndElement();
+
+ }
+
+ /**
+ * Writes the XML for the given directory of connection groups.
+ *
+ * @param self The user whose permissions dictate the availability of the
+ * data written.
+ * @param xml The XMLStremWriter to use when writing the data.
+ * @param directory The directory whose XML representation will be
+ * written.
+ * @throws GuacamoleException If an error occurs while reading the
+ * requested data.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeConnectionGroups(User self, XMLStreamWriter xml,
+ Directory<String, ConnectionGroup> directory)
+ throws GuacamoleException, XMLStreamException {
+
+ // If no connections, write nothing
+ Set<String> identifiers = directory.getIdentifiers();
+ if (identifiers.isEmpty())
+ return;
+
+ // Begin connections
+ xml.writeStartElement("groups");
+
+ // For each entry, write corresponding connection element
+ for (String identifier : identifiers) {
+
+ // Write each group
+ ConnectionGroup group = directory.get(identifier);
+ writeConnectionGroup(self, xml, group);
+
+ }
+
+ // End connections
+ xml.writeEndElement();
+
+ }
+
+ /**
+ * Writes the XML for the given directory of connections.
+ *
+ * @param self The user whose permissions dictate the availability of the
+ * data written.
+ * @param xml The XMLStremWriter to use when writing the data.
+ * @param directory The directory whose XML representation will be
+ * written.
+ * @throws GuacamoleException If an error occurs while reading the
+ * requested data.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeConnections(User self, XMLStreamWriter xml,
+ Directory<String, Connection> directory)
+ throws GuacamoleException, XMLStreamException {
+
+ // If no connections, write nothing
+ Set<String> identifiers = directory.getIdentifiers();
+ if (identifiers.isEmpty())
+ return;
+
+ // Begin connections
+ xml.writeStartElement("connections");
+
+ // For each entry, write corresponding connection element
+ for (String identifier : identifiers) {
+
+ // Write each connection
+ Connection connection = directory.get(identifier);
+ writeConnection(self, xml, connection);
+
+ }
+
+ // End connections
+ xml.writeEndElement();
+
+ }
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Do not cache
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Write XML content type
+ response.setHeader("Content-Type", "text/xml");
+
+ // Set encoding
+ response.setCharacterEncoding("UTF-8");
+
+ // Get root group
+ ConnectionGroup root = context.getRootConnectionGroup();
+
+ // Write actual XML
+ try {
+
+ // Get self
+ User self = context.self();
+
+ XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
+ XMLStreamWriter xml = outputFactory.createXMLStreamWriter(response.getWriter());
+
+ // Write content of root group
+ xml.writeStartDocument();
+ writeConnectionGroup(self, xml, root);
+ xml.writeEndDocument();
+
+ }
+ catch (XMLStreamException e) {
+ throw new GuacamoleServerException(
+ "Unable to write configuration list XML.", e);
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(
+ "I/O error writing configuration list XML.", e);
+ }
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Move.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Move.java
new file mode 100644
index 0000000..6db6ec8
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Move.java
@@ -0,0 +1,62 @@
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles moving connections.
+ *
+ * @author Michael Jumper
+ */
+public class Move extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get ID
+ String identifier = request.getParameter("id");
+
+ // Get the identifier of the new parent connection group
+ String parentID = request.getParameter("parentID");
+
+ // Attempt to get the new parent connection directory
+ Directory<String, Connection> newParentDirectory =
+ ConnectionUtility.findConnectionDirectory(context, parentID);
+
+ // Attempt to get root connection directory
+ Directory<String, Connection> directory =
+ context.getRootConnectionGroup().getConnectionDirectory();
+
+ // Move connection
+ directory.move(identifier, newParentDirectory);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Update.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Update.java
new file mode 100644
index 0000000..631e20a
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/Update.java
@@ -0,0 +1,88 @@
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.Enumeration;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Connection;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+
+/**
+ * Simple HttpServlet which handles connection update.
+ *
+ * @author Michael Jumper
+ */
+public class Update extends AuthenticatingHttpServlet {
+
+ /**
+ * Prefix given to a parameter name when that parameter is a protocol-
+ * specific parameter meant for the configuration.
+ */
+ public static final String PARAMETER_PREFIX = "_";
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get ID, name, and protocol
+ String identifier = request.getParameter("id");
+ String name = request.getParameter("name");
+ String protocol = request.getParameter("protocol");
+
+ // Attempt to get connection directory
+ Directory<String, Connection> directory =
+ context.getRootConnectionGroup().getConnectionDirectory();
+
+ // Create config
+ GuacamoleConfiguration config = new GuacamoleConfiguration();
+ config.setProtocol(protocol);
+
+ // Load parameters into config
+ Enumeration<String> params = request.getParameterNames();
+ while (params.hasMoreElements()) {
+
+ // If parameter starts with prefix, load corresponding parameter
+ // value into config
+ String param = params.nextElement();
+ if (param.startsWith(PARAMETER_PREFIX))
+ config.setParameter(
+ param.substring(PARAMETER_PREFIX.length()),
+ request.getParameter(param));
+
+ }
+
+ // Create connection skeleton
+ Connection connection = directory.get(identifier);
+ connection.setName(name);
+ connection.setConfiguration(config);
+
+ // Update connection
+ directory.update(connection);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/package-info.java
new file mode 100644
index 0000000..1c67b01
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/connections/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Servlets dedicated to CRUD operations related to Connections.
+ */
+package org.glyptodon.guacamole.net.basic.crud.connections;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/permissions/List.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/permissions/List.java
new file mode 100644
index 0000000..a8aaeae
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/permissions/List.java
@@ -0,0 +1,220 @@
+package org.glyptodon.guacamole.net.basic.crud.permissions;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleSecurityException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionGroupPermission;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+import org.glyptodon.guacamole.net.auth.permission.UserPermission;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which outputs XML containing a list of all visible
+ * permissions of a given user.
+ *
+ * @author Michael Jumper
+ */
+public class List extends AuthenticatingHttpServlet {
+
+ /**
+ * Returns the XML attribute value representation of the given
+ * SystemPermission.Type.
+ *
+ * @param type The SystemPermission.Type to translate into a String.
+ * @return The XML attribute value representation of the given
+ * SystemPermission.Type.
+ *
+ * @throws GuacamoleException If the type given is not implemented.
+ */
+ private String toString(SystemPermission.Type type)
+ throws GuacamoleException {
+
+ switch (type) {
+ case CREATE_USER: return "create-user";
+ case CREATE_CONNECTION: return "create-connection";
+ case CREATE_CONNECTION_GROUP: return "create-connection-group";
+ case ADMINISTER: return "admin";
+ }
+
+ throw new GuacamoleException("Unknown permission type: " + type);
+
+ }
+
+ /**
+ * Returns the XML attribute value representation of the given
+ * ObjectPermission.Type.
+ *
+ * @param type The ObjectPermission.Type to translate into a String.
+ * @return The XML attribute value representation of the given
+ * ObjectPermission.Type.
+ *
+ * @throws GuacamoleException If the type given is not implemented.
+ */
+ private String toString(ObjectPermission.Type type)
+ throws GuacamoleException {
+
+ switch (type) {
+ case READ: return "read";
+ case UPDATE: return "update";
+ case DELETE: return "delete";
+ case ADMINISTER: return "admin";
+ }
+
+ throw new GuacamoleException("Unknown permission type: " + type);
+
+ }
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Do not cache
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Set encoding
+ response.setCharacterEncoding("UTF-8");
+
+ // Write actual XML
+ try {
+
+ User user;
+
+ // Get username
+ String username = request.getParameter("user");
+ if (username != null) {
+
+ // Get user directory
+ Directory<String, User> users = context.getUserDirectory();
+
+ // Get specific user
+ user = users.get(username);
+ }
+ else
+ user = context.self();
+
+ if (user == null)
+ throw new GuacamoleSecurityException("No such user.");
+
+ // Write XML content type
+ response.setHeader("Content-Type", "text/xml");
+
+ XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
+ XMLStreamWriter xml = outputFactory.createXMLStreamWriter(response.getWriter());
+
+ // Begin document
+ xml.writeStartDocument();
+ xml.writeStartElement("permissions");
+ xml.writeAttribute("user", user.getUsername());
+
+ // For each entry, write corresponding user element
+ for (Permission permission : user.getPermissions()) {
+
+ // System permission
+ if (permission instanceof SystemPermission) {
+
+ // Get permission
+ SystemPermission sp = (SystemPermission) permission;
+
+ // Write permission
+ xml.writeEmptyElement("system");
+ xml.writeAttribute("type", toString(sp.getType()));
+
+ }
+
+ // Config permission
+ else if (permission instanceof ConnectionPermission) {
+
+ // Get permission
+ ConnectionPermission cp =
+ (ConnectionPermission) permission;
+
+ // Write permission
+ xml.writeEmptyElement("connection");
+ xml.writeAttribute("type", toString(cp.getType()));
+ xml.writeAttribute("name", cp.getObjectIdentifier());
+
+ }
+
+ // Connection group permission
+ else if (permission instanceof ConnectionGroupPermission) {
+
+ // Get permission
+ ConnectionGroupPermission cgp =
+ (ConnectionGroupPermission) permission;
+
+ // Write permission
+ xml.writeEmptyElement("connection-group");
+ xml.writeAttribute("type", toString(cgp.getType()));
+ xml.writeAttribute("name", cgp.getObjectIdentifier());
+
+ }
+
+ // User permission
+ else if (permission instanceof UserPermission) {
+
+ // Get permission
+ UserPermission up = (UserPermission) permission;
+
+ // Write permission
+ xml.writeEmptyElement("user");
+ xml.writeAttribute("type", toString(up.getType()));
+ xml.writeAttribute("name", up.getObjectIdentifier());
+
+ }
+
+ else
+ throw new GuacamoleClientException(
+ "Unsupported permission type.");
+
+ }
+
+ // End document
+ xml.writeEndElement();
+ xml.writeEndDocument();
+
+ }
+ catch (XMLStreamException e) {
+ throw new GuacamoleServerException(
+ "Unable to write permission list XML.", e);
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(
+ "I/O error writing permission list XML.", e);
+ }
+
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/permissions/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/permissions/package-info.java
new file mode 100644
index 0000000..39b9c68
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/permissions/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Servlets dedicated to CRUD operations related to Permissions.
+ */
+package org.glyptodon.guacamole.net.basic.crud.permissions;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/protocols/List.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/protocols/List.java
new file mode 100644
index 0000000..f219cb4
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/protocols/List.java
@@ -0,0 +1,300 @@
+package org.glyptodon.guacamole.net.basic.crud.protocols;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+import org.glyptodon.guacamole.net.basic.ProtocolInfo;
+import org.glyptodon.guacamole.net.basic.ProtocolParameter;
+import org.glyptodon.guacamole.net.basic.ProtocolParameterOption;
+import org.glyptodon.guacamole.net.basic.xml.DocumentHandler;
+import org.glyptodon.guacamole.net.basic.xml.protocol.ProtocolTagHandler;
+import org.glyptodon.guacamole.properties.GuacamoleHome;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+/**
+ * Simple HttpServlet which outputs XML containing a list of all visible
+ * protocols.
+ *
+ * @author Michael Jumper
+ */
+public class List extends AuthenticatingHttpServlet {
+
+ /**
+ * Logger for this class.
+ */
+ private Logger logger = LoggerFactory.getLogger(List.class);
+
+ /**
+ * Array of all known protocol names.
+ */
+ private static final String[] KNOWN_PROTOCOLS = new String[]{
+ "vnc", "rdp", "ssh"};
+
+ /**
+ * Parses the given XML file, returning the parsed ProtocolInfo.
+ *
+ * @param input An input stream containing XML describing the parameters
+ * associated with a protocol supported by Guacamole.
+ * @return A new ProtocolInfo object which contains the parameters described
+ * by the XML file parsed.
+ * @throws GuacamoleException If an error occurs while parsing the XML file.
+ */
+ private ProtocolInfo getProtocol(InputStream input)
+ throws GuacamoleException {
+
+ // Parse document
+ try {
+
+ // Get handler for root element
+ ProtocolTagHandler protocolTagHandler =
+ new ProtocolTagHandler();
+
+ // Set up document handler
+ DocumentHandler contentHandler = new DocumentHandler(
+ "protocol", protocolTagHandler);
+
+ // Set up XML parser
+ XMLReader parser = XMLReaderFactory.createXMLReader();
+ parser.setContentHandler(contentHandler);
+
+ // Read and parse file
+ InputStream xml = new BufferedInputStream(input);
+ parser.parse(new InputSource(xml));
+ xml.close();
+
+ // Return parsed protocol
+ return protocolTagHandler.asProtocolInfo();
+
+ }
+ catch (IOException e) {
+ throw new GuacamoleException("Error reading basic user mapping file.", e);
+ }
+ catch (SAXException e) {
+ throw new GuacamoleException("Error parsing basic user mapping XML.", e);
+ }
+
+ }
+
+ /**
+ * Given an XML stream and a fully-populated ProtocolInfo object, writes
+ * out the corresponding protocol XML describing all available parameters.
+ *
+ * @param xml The XMLStreamWriter to use to write the XML.
+ * @param protocol The ProtocolInfo object to read parameters and protocol
+ * information from.
+ * @throws XMLStreamException If an error occurs while writing the XML.
+ */
+ private void writeProtocol(XMLStreamWriter xml, ProtocolInfo protocol)
+ throws XMLStreamException {
+
+ // Write protocol
+ xml.writeStartElement("protocol");
+ xml.writeAttribute("name", protocol.getName());
+ xml.writeAttribute("title", protocol.getTitle());
+
+ // Write parameters
+ for (ProtocolParameter param : protocol.getParameters()) {
+
+ // Write param tag
+ xml.writeStartElement("param");
+ xml.writeAttribute("name", param.getName());
+ xml.writeAttribute("title", param.getTitle());
+
+ // Write type
+ switch (param.getType()) {
+
+ // Text parameter
+ case TEXT:
+ xml.writeAttribute("type", "text");
+ break;
+
+ // Password parameter
+ case PASSWORD:
+ xml.writeAttribute("type", "password");
+ break;
+
+ // Numeric parameter
+ case NUMERIC:
+ xml.writeAttribute("type", "numeric");
+ break;
+
+ // Boolean parameter
+ case BOOLEAN:
+ xml.writeAttribute("type", "boolean");
+ xml.writeAttribute("value", param.getValue());
+ break;
+
+ // Enumerated parameter
+ case ENUM:
+ xml.writeAttribute("type", "enum");
+ break;
+
+ // If unknown, fail explicitly
+ default:
+ throw new UnsupportedOperationException(
+ "Parameter type not supported: " + param.getType());
+
+ }
+
+ // Write options
+ for (ProtocolParameterOption option : param.getOptions()) {
+ xml.writeStartElement("option");
+ xml.writeAttribute("value", option.getValue());
+ xml.writeCharacters(option.getTitle());
+ xml.writeEndElement();
+ }
+
+ // End parameter
+ xml.writeEndElement();
+
+ }
+
+ // End protocol
+ xml.writeEndElement();
+
+ }
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Do not cache
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Set encoding
+ response.setCharacterEncoding("UTF-8");
+
+ // Map of all available protocols
+ Map<String, ProtocolInfo> protocols = new HashMap<String, ProtocolInfo>();
+
+ // Get protcols directory
+ File protocol_directory = new File(GuacamoleHome.getDirectory(),
+ "protocols");
+
+ // Read protocols from directory if it exists
+ if (protocol_directory.isDirectory()) {
+
+ // Get all XML files
+ File[] files = protocol_directory.listFiles(
+ new FilenameFilter() {
+
+ @Override
+ public boolean accept(File file, String string) {
+ return string.endsWith(".xml");
+ }
+
+ }
+ );
+
+ // Load each protocol from each file
+ for (File file : files) {
+
+ try {
+
+ // Parse protocol
+ FileInputStream stream = new FileInputStream(file);
+ ProtocolInfo protocol = getProtocol(stream);
+ stream.close();
+
+ // Store protocol
+ protocols.put(protocol.getName(), protocol);
+
+ }
+ catch (IOException e) {
+ logger.error("Unable to read protocol XML.", e);
+ }
+
+ }
+
+ }
+
+ // If known protocols are not already defined, read from classpath
+ for (String protocol : KNOWN_PROTOCOLS) {
+
+ // If protocol not defined yet, attempt to load from classpath
+ if (!protocols.containsKey(protocol)) {
+
+ InputStream stream = List.class.getResourceAsStream(
+ "/net/sourceforge/guacamole/net/protocols/"
+ + protocol + ".xml");
+
+ // Parse XML if available
+ if (stream != null)
+ protocols.put(protocol, getProtocol(stream));
+
+ }
+
+ }
+
+ // Write actual XML
+ try {
+ // Write XML content type
+ response.setHeader("Content-Type", "text/xml");
+
+ XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
+ XMLStreamWriter xml = outputFactory.createXMLStreamWriter(response.getWriter());
+
+ // Begin document
+ xml.writeStartDocument();
+ xml.writeStartElement("protocols");
+
+ // Write all protocols
+ for (ProtocolInfo protocol : protocols.values())
+ writeProtocol(xml, protocol);
+
+ // End document
+ xml.writeEndElement();
+ xml.writeEndDocument();
+
+ }
+ catch (XMLStreamException e) {
+ throw new GuacamoleServerException(
+ "Unable to write protocol list XML.", e);
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(
+ "I/O error writing protocol list XML.", e);
+ }
+
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/protocols/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/protocols/package-info.java
new file mode 100644
index 0000000..1d81e17
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/protocols/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Servlets dedicated to CRUD operations related to protocols.
+ */
+package org.glyptodon.guacamole.net.basic.crud.protocols;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Create.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Create.java
new file mode 100644
index 0000000..e7859c9
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Create.java
@@ -0,0 +1,61 @@
+package org.glyptodon.guacamole.net.basic.crud.users;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.UUID;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles user creation.
+ *
+ * @author Michael Jumper
+ */
+public class Create extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Create user as specified
+ String username = request.getParameter("name");
+
+ // Attempt to get user directory
+ Directory<String, User> directory =
+ context.getUserDirectory();
+
+ // Create user skeleton
+ User user = new DummyUser();
+ user.setUsername(username);
+ user.setPassword(UUID.randomUUID().toString());
+
+ // Add user
+ directory.add(user);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Delete.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Delete.java
new file mode 100644
index 0000000..bb42740
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Delete.java
@@ -0,0 +1,54 @@
+package org.glyptodon.guacamole.net.basic.crud.users;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles user deletion.
+ *
+ * @author Michael Jumper
+ */
+public class Delete extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Get username
+ String username = request.getParameter("name");
+
+ // Attempt to get user directory
+ Directory<String, User> directory = context.getUserDirectory();
+
+ // Remove user
+ directory.remove(username);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/DummyUser.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/DummyUser.java
new file mode 100644
index 0000000..8e6bbc5
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/DummyUser.java
@@ -0,0 +1,46 @@
+
+package org.glyptodon.guacamole.net.basic.crud.users;
+
+import java.util.HashSet;
+import java.util.Set;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.AbstractUser;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+
+/**
+ * Basic User skeleton, providing a means of storing User data prior to CRUD
+ * operations. This User does not promote any of the semantics that would
+ * otherwise be present because of the authentication provider. It is up to the
+ * authentication provider to create a new User based on the information
+ * contained herein.
+ *
+ * @author Michael Jumper
+ */
+public class DummyUser extends AbstractUser {
+
+ /**
+ * Set of all available permissions.
+ */
+ private Set<Permission> permissions = new HashSet<Permission>();
+
+ @Override
+ public Set<Permission> getPermissions() throws GuacamoleException {
+ return permissions;
+ }
+
+ @Override
+ public boolean hasPermission(Permission permission) throws GuacamoleException {
+ return permissions.contains(permission);
+ }
+
+ @Override
+ public void addPermission(Permission permission) throws GuacamoleException {
+ permissions.add(permission);
+ }
+
+ @Override
+ public void removePermission(Permission permission) throws GuacamoleException {
+ permissions.remove(permission);
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/List.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/List.java
new file mode 100644
index 0000000..18a7eb1
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/List.java
@@ -0,0 +1,102 @@
+package org.glyptodon.guacamole.net.basic.crud.users;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.io.IOException;
+import java.util.Set;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.GuacamoleServerException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which outputs XML containing a list of all visible users.
+ *
+ * @author Michael Jumper
+ */
+public class List extends AuthenticatingHttpServlet {
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Do not cache
+ response.setHeader("Cache-Control", "no-cache");
+
+ // Write XML content type
+ response.setHeader("Content-Type", "text/xml");
+
+ // Set encoding
+ response.setCharacterEncoding("UTF-8");
+
+ // Write actual XML
+ try {
+
+ // Get user directory
+ Directory<String, User> directory = context.getUserDirectory();
+
+ // Get users
+ Set<String> users = directory.getIdentifiers();
+
+ XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
+ XMLStreamWriter xml = outputFactory.createXMLStreamWriter(response.getWriter());
+
+ // Begin document
+ xml.writeStartDocument();
+ xml.writeStartElement("users");
+
+ // For each entry, write corresponding user element
+ for (String username : users) {
+
+ // Get user
+ User user = directory.get(username);
+
+ // Write user
+ xml.writeEmptyElement("user");
+ xml.writeAttribute("name", user.getUsername());
+
+ }
+
+ // End document
+ xml.writeEndElement();
+ xml.writeEndDocument();
+
+ }
+ catch (XMLStreamException e) {
+ throw new GuacamoleServerException(
+ "Unable to write configuration list XML.", e);
+ }
+ catch (IOException e) {
+ throw new GuacamoleServerException(
+ "I/O error writing configuration list XML.", e);
+ }
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Update.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Update.java
new file mode 100644
index 0000000..10868b3
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/Update.java
@@ -0,0 +1,307 @@
+package org.glyptodon.guacamole.net.basic.crud.users;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.glyptodon.guacamole.GuacamoleClientException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.Directory;
+import org.glyptodon.guacamole.net.auth.User;
+import org.glyptodon.guacamole.net.auth.UserContext;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionGroupPermission;
+import org.glyptodon.guacamole.net.auth.permission.ConnectionPermission;
+import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
+import org.glyptodon.guacamole.net.auth.permission.Permission;
+import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
+import org.glyptodon.guacamole.net.auth.permission.UserPermission;
+import org.glyptodon.guacamole.net.basic.AuthenticatingHttpServlet;
+
+/**
+ * Simple HttpServlet which handles user update.
+ *
+ * @author Michael Jumper
+ */
+public class Update extends AuthenticatingHttpServlet {
+
+ /**
+ * String given for user creation permission.
+ */
+ private static final String CREATE_USER_PERMISSION = "create-user";
+
+ /**
+ * String given for connection creation permission.
+ */
+ private static final String CREATE_CONNECTION_PERMISSION = "create-connection";
+
+ /**
+ * String given for connection group creation permission.
+ */
+ private static final String CREATE_CONNECTION_GROUP_PERMISSION = "create-connection-group";
+
+ /**
+ * String given for system administration permission.
+ */
+ private static final String ADMIN_PERMISSION = "admin";
+
+ /**
+ * Prefix given before an object identifier for read permission.
+ */
+ private static final String READ_PREFIX = "read:";
+
+ /**
+ * Prefix given before an object identifier for delete permission.
+ */
+ private static final String DELETE_PREFIX = "delete:";
+
+ /**
+ * Prefix given before an object identifier for update permission.
+ */
+ private static final String UPDATE_PREFIX = "update:";
+
+ /**
+ * Prefix given before an object identifier for administration permission.
+ */
+ private static final String ADMIN_PREFIX = "admin:";
+
+ /**
+ * Given a permission string, returns the corresponding system permission.
+ *
+ * @param str The permission string to parse.
+ * @return The parsed system permission.
+ * @throws GuacamoleException If the given string could not be parsed.
+ */
+ private Permission parseSystemPermission(String str)
+ throws GuacamoleException {
+
+ // Create user
+ if (str.equals(CREATE_USER_PERMISSION))
+ return new SystemPermission(SystemPermission.Type.CREATE_USER);
+
+ // Create connection
+ if (str.equals(CREATE_CONNECTION_PERMISSION))
+ return new SystemPermission(SystemPermission.Type.CREATE_CONNECTION);
+
+ // Create connection group
+ if (str.equals(CREATE_CONNECTION_GROUP_PERMISSION))
+ return new SystemPermission(SystemPermission.Type.CREATE_CONNECTION_GROUP);
+
+ // Administration
+ if (str.equals(ADMIN_PERMISSION))
+ return new SystemPermission(SystemPermission.Type.ADMINISTER);
+
+ throw new GuacamoleException("Invalid permission string.");
+
+ }
+
+ /**
+ * Given a permission string, returns the corresponding user permission.
+ *
+ * @param str The permission string to parse.
+ * @return The parsed user permission.
+ * @throws GuacamoleException If the given string could not be parsed.
+ */
+ private Permission parseUserPermission(String str)
+ throws GuacamoleException {
+
+ // Read
+ if (str.startsWith(READ_PREFIX))
+ return new UserPermission(ObjectPermission.Type.READ,
+ str.substring(READ_PREFIX.length()));
+
+ // Update
+ if (str.startsWith(UPDATE_PREFIX))
+ return new UserPermission(ObjectPermission.Type.UPDATE,
+ str.substring(UPDATE_PREFIX.length()));
+
+ // Delete
+ if (str.startsWith(DELETE_PREFIX))
+ return new UserPermission(ObjectPermission.Type.DELETE,
+ str.substring(DELETE_PREFIX.length()));
+
+ // Administration
+ if (str.startsWith(ADMIN_PREFIX))
+ return new UserPermission(ObjectPermission.Type.ADMINISTER,
+ str.substring(ADMIN_PREFIX.length()));
+
+ throw new GuacamoleException("Invalid permission string.");
+
+ }
+
+ /**
+ * Given a permission string, returns the corresponding connection
+ * permission.
+ *
+ * @param str The permission string to parse.
+ * @return The parsed connection permission.
+ * @throws GuacamoleException If the given string could not be parsed.
+ */
+ private Permission parseConnectionPermission(String str)
+ throws GuacamoleException {
+
+ // Read
+ if (str.startsWith(READ_PREFIX))
+ return new ConnectionPermission(ObjectPermission.Type.READ,
+ str.substring(READ_PREFIX.length()));
+
+ // Update
+ if (str.startsWith(UPDATE_PREFIX))
+ return new ConnectionPermission(ObjectPermission.Type.UPDATE,
+ str.substring(UPDATE_PREFIX.length()));
+
+ // Delete
+ if (str.startsWith(DELETE_PREFIX))
+ return new ConnectionPermission(ObjectPermission.Type.DELETE,
+ str.substring(DELETE_PREFIX.length()));
+
+ // Administration
+ if (str.startsWith(ADMIN_PREFIX))
+ return new ConnectionPermission(ObjectPermission.Type.ADMINISTER,
+ str.substring(ADMIN_PREFIX.length()));
+
+ throw new GuacamoleClientException("Invalid permission string.");
+
+ }
+
+ /**
+ * Given a permission string, returns the corresponding connection group
+ * permission.
+ *
+ * @param str The permission string to parse.
+ * @return The parsed connection group permission.
+ * @throws GuacamoleException If the given string could not be parsed.
+ */
+ private Permission parseConnectionGroupPermission(String str)
+ throws GuacamoleException {
+
+ // Read
+ if (str.startsWith(READ_PREFIX))
+ return new ConnectionGroupPermission(ObjectPermission.Type.READ,
+ str.substring(READ_PREFIX.length()));
+
+ // Update
+ if (str.startsWith(UPDATE_PREFIX))
+ return new ConnectionGroupPermission(ObjectPermission.Type.UPDATE,
+ str.substring(UPDATE_PREFIX.length()));
+
+ // Delete
+ if (str.startsWith(DELETE_PREFIX))
+ return new ConnectionGroupPermission(ObjectPermission.Type.DELETE,
+ str.substring(DELETE_PREFIX.length()));
+
+ // Administration
+ if (str.startsWith(ADMIN_PREFIX))
+ return new ConnectionGroupPermission(ObjectPermission.Type.ADMINISTER,
+ str.substring(ADMIN_PREFIX.length()));
+
+ throw new GuacamoleClientException("Invalid permission string.");
+
+ }
+
+ @Override
+ protected void authenticatedService(
+ UserContext context,
+ HttpServletRequest request, HttpServletResponse response)
+ throws GuacamoleException {
+
+ // Create user as specified
+ String username = request.getParameter("name");
+ String password = request.getParameter("password");
+
+ // Attempt to get user directory
+ Directory<String, User> directory =
+ context.getUserDirectory();
+
+ // Get user data, setting password if given
+ User user = directory.get(username);
+ user.setUsername(username);
+ if (password != null)
+ user.setPassword(password);
+
+ /*
+ * NEW PERMISSIONS
+ */
+
+ // Set added system permissions
+ String[] add_sys_permission = request.getParameterValues("+sys");
+ if (add_sys_permission != null) {
+ for (String str : add_sys_permission)
+ user.addPermission(parseSystemPermission(str));
+ }
+
+ // Set added user permissions
+ String[] add_user_permission = request.getParameterValues("+user");
+ if (add_user_permission != null) {
+ for (String str : add_user_permission)
+ user.addPermission(parseUserPermission(str));
+ }
+
+ // Set added connection permissions
+ String[] add_connection_permission = request.getParameterValues("+connection");
+ if (add_connection_permission != null) {
+ for (String str : add_connection_permission)
+ user.addPermission(parseConnectionPermission(str));
+ }
+
+ // Set added connection group permissions
+ String[] add_connection_group_permission = request.getParameterValues("+connection-group");
+ if (add_connection_group_permission != null) {
+ for (String str : add_connection_group_permission)
+ user.addPermission(parseConnectionGroupPermission(str));
+ }
+
+ /*
+ * REMOVED PERMISSIONS
+ */
+
+ // Unset removed system permissions
+ String[] remove_sys_permission = request.getParameterValues("-sys");
+ if (remove_sys_permission != null) {
+ for (String str : remove_sys_permission)
+ user.removePermission(parseSystemPermission(str));
+ }
+
+ // Unset removed user permissions
+ String[] remove_user_permission = request.getParameterValues("-user");
+ if (remove_user_permission != null) {
+ for (String str : remove_user_permission)
+ user.removePermission(parseUserPermission(str));
+ }
+
+ // Unset removed connection permissions
+ String[] remove_connection_permission = request.getParameterValues("-connection");
+ if (remove_connection_permission != null) {
+ for (String str : remove_connection_permission)
+ user.removePermission(parseConnectionPermission(str));
+ }
+
+ // Unset removed connection group permissions
+ String[] remove_connection_group_permission = request.getParameterValues("-connection-group");
+ if (remove_connection_group_permission != null) {
+ for (String str : remove_connection_group_permission)
+ user.removePermission(parseConnectionGroupPermission(str));
+ }
+
+ // Update user
+ directory.update(user);
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/package-info.java
new file mode 100644
index 0000000..12fdcd6
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/crud/users/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Servlets dedicated to CRUD operations related to Users.
+ */
+package org.glyptodon.guacamole.net.basic.crud.users;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/event/SessionListenerCollection.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/event/SessionListenerCollection.java
new file mode 100644
index 0000000..f354acf
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/event/SessionListenerCollection.java
@@ -0,0 +1,132 @@
+package org.glyptodon.guacamole.net.basic.event;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.AbstractCollection;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import javax.servlet.http.HttpSession;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.basic.properties.BasicGuacamoleProperties;
+import org.glyptodon.guacamole.properties.GuacamoleProperties;
+
+/**
+ * A collection which iterates over instances of all listeners defined in
+ * guacamole.properties. For each listener defined in guacamole.properties, a
+ * new instance is created and stored in this collection. The contents of this
+ * collection is stored within the HttpSession, and will be reused if available.
+ * Each listener is instantiated once per session. Listeners are singleton
+ * classes within the session, but not globally.
+ *
+ * @author Michael Jumper
+ */
+public class SessionListenerCollection extends AbstractCollection {
+
+ /**
+ * The name of the session attribute which will contain the listener
+ * collection.
+ */
+ private static final String SESSION_ATTRIBUTE = "GUAC_LISTENERS";
+
+ /**
+ * The wrapped collection of listeners, possibly retrieved from the
+ * session.
+ */
+ private Collection listeners;
+
+ /**
+ * Creates a new SessionListenerCollection which stores all listeners
+ * defined in guacamole.properties in the provided session. If listeners
+ * are already stored in the provided session, those listeners are used
+ * instead.
+ *
+ * @param session The HttpSession to store listeners within.
+ * @throws GuacamoleException If an error occurs while instantiating new
+ * listeners.
+ */
+ public SessionListenerCollection(HttpSession session) throws GuacamoleException {
+
+ // Pull cached listeners from session
+ listeners = (Collection) session.getAttribute(SESSION_ATTRIBUTE);
+
+ // If no listeners stored, listeners must be loaded first
+ if (listeners == null) {
+
+ // Load listeners from guacamole.properties
+ listeners = new ArrayList();
+ try {
+
+ // Get all listener classes from properties
+ Collection<Class> listenerClasses =
+ GuacamoleProperties.getProperty(BasicGuacamoleProperties.EVENT_LISTENERS);
+
+ // Add an instance of each class to the list
+ if (listenerClasses != null) {
+ for (Class listenerClass : listenerClasses) {
+
+ // Instantiate listener
+ Object listener = listenerClass.getConstructor().newInstance();
+
+ // Add listener to collection of listeners
+ listeners.add(listener);
+
+ }
+ }
+
+ }
+ catch (InstantiationException e) {
+ throw new GuacamoleException("Listener class is abstract.", e);
+ }
+ catch (IllegalAccessException e) {
+ throw new GuacamoleException("No access to listener constructor.", e);
+ }
+ catch (IllegalArgumentException e) {
+ // This should not happen, given there ARE no arguments
+ throw new GuacamoleException("Illegal arguments to listener constructor.", e);
+ }
+ catch (InvocationTargetException e) {
+ throw new GuacamoleException("Error while instantiating listener.", e);
+ }
+ catch (NoSuchMethodException e) {
+ throw new GuacamoleException("Listener has no default constructor.", e);
+ }
+ catch (SecurityException e) {
+ throw new GuacamoleException("Security restrictions prevent instantiation of listener.", e);
+ }
+
+ // Store listeners for next time
+ session.setAttribute(SESSION_ATTRIBUTE, listeners);
+
+ }
+
+ }
+
+ @Override
+ public Iterator iterator() {
+ return listeners.iterator();
+ }
+
+ @Override
+ public int size() {
+ return listeners.size();
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/event/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/event/package-info.java
new file mode 100644
index 0000000..ec5fc92
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/event/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Classes used by the Guacamole web application to broadcast events.
+ */
+package org.glyptodon.guacamole.net.basic.event;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/package-info.java
new file mode 100644
index 0000000..69ccee9
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes specific to the general-purpose web application implemented by
+ * the Guacamole project using the Guacamole APIs.
+ */
+package org.glyptodon.guacamole.net.basic;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/AuthenticationProviderProperty.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/AuthenticationProviderProperty.java
new file mode 100644
index 0000000..8711baa
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/AuthenticationProviderProperty.java
@@ -0,0 +1,76 @@
+package org.glyptodon.guacamole.net.basic.properties;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.lang.reflect.InvocationTargetException;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.auth.AuthenticationProvider;
+import org.glyptodon.guacamole.net.basic.GuacamoleClassLoader;
+import org.glyptodon.guacamole.properties.GuacamoleProperty;
+
+/**
+ * A GuacamoleProperty whose value is the name of a class to use to
+ * authenticate users. This class must implement AuthenticationProvider.
+ *
+ * @author Michael Jumper
+ */
+public abstract class AuthenticationProviderProperty implements GuacamoleProperty<AuthenticationProvider> {
+
+ @Override
+ public AuthenticationProvider parseValue(String authProviderClassName) throws GuacamoleException {
+
+ // If no property provided, return null.
+ if (authProviderClassName == null)
+ return null;
+
+ // Get auth provider instance
+ try {
+
+ Object obj = GuacamoleClassLoader.getInstance().loadClass(authProviderClassName)
+ .getConstructor().newInstance();
+
+ if (!(obj instanceof AuthenticationProvider))
+ throw new GuacamoleException("Specified authentication provider class is not a AuthenticationProvider.");
+
+ return (AuthenticationProvider) obj;
+
+ }
+ catch (ClassNotFoundException e) {
+ throw new GuacamoleException("Authentication provider class not found", e);
+ }
+ catch (NoSuchMethodException e) {
+ throw new GuacamoleException("Default constructor for authentication provider not present", e);
+ }
+ catch (SecurityException e) {
+ throw new GuacamoleException("Creation of authentication provider disallowed; check your security settings", e);
+ }
+ catch (InstantiationException e) {
+ throw new GuacamoleException("Unable to instantiate authentication provider", e);
+ }
+ catch (IllegalAccessException e) {
+ throw new GuacamoleException("Unable to access default constructor of authentication provider", e);
+ }
+ catch (InvocationTargetException e) {
+ throw new GuacamoleException("Internal error in constructor of authentication provider", e.getTargetException());
+ }
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/BasicGuacamoleProperties.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/BasicGuacamoleProperties.java
new file mode 100644
index 0000000..91e1d38
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/BasicGuacamoleProperties.java
@@ -0,0 +1,67 @@
+
+package org.glyptodon.guacamole.net.basic.properties;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.properties.FileGuacamoleProperty;
+
+/**
+ * Properties used by the default Guacamole web application.
+ *
+ * @author Michael Jumper
+ */
+public class BasicGuacamoleProperties {
+
+ /**
+ * This class should not be instantiated.
+ */
+ private BasicGuacamoleProperties() {}
+
+ /**
+ * The authentication provider to user when retrieving the authorized
+ * configurations of a user.
+ */
+ public static final AuthenticationProviderProperty AUTH_PROVIDER = new AuthenticationProviderProperty() {
+
+ @Override
+ public String getName() { return "auth-provider"; }
+
+ };
+
+ /**
+ * The directory to search for authentication provider classes.
+ */
+ public static final FileGuacamoleProperty LIB_DIRECTORY = new FileGuacamoleProperty() {
+
+ @Override
+ public String getName() { return "lib-directory"; }
+
+ };
+
+ /**
+ * The comma-separated list of all classes to use as event listeners.
+ */
+ public static final EventListenersProperty EVENT_LISTENERS = new EventListenersProperty() {
+
+ @Override
+ public String getName() { return "event-listeners"; }
+
+ };
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/EventListenersProperty.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/EventListenersProperty.java
new file mode 100644
index 0000000..5a987ee
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/EventListenersProperty.java
@@ -0,0 +1,68 @@
+package org.glyptodon.guacamole.net.basic.properties;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.ArrayList;
+import java.util.Collection;
+import org.glyptodon.guacamole.GuacamoleException;
+import org.glyptodon.guacamole.net.basic.GuacamoleClassLoader;
+import org.glyptodon.guacamole.properties.GuacamoleProperty;
+
+/**
+ * A GuacamoleProperty whose value is a comma-separated list of class names,
+ * where each class will be used as a listener for events.
+ *
+ * @author Michael Jumper
+ */
+public abstract class EventListenersProperty implements GuacamoleProperty<Collection<Class>> {
+
+ @Override
+ public Collection<Class> parseValue(String classNameList) throws GuacamoleException {
+
+ // If no property provided, return null.
+ if (classNameList == null)
+ return null;
+
+ // Parse list
+ String[] classNames = classNameList.split(",[\\s]*");
+
+ // Fill list of classes
+ Collection<Class> listeners = new ArrayList<Class>();
+ try {
+
+ // Load all classes in list
+ for (String className : classNames) {
+ Class clazz = GuacamoleClassLoader.getInstance().loadClass(className);
+ listeners.add(clazz);
+ }
+
+ }
+ catch (ClassNotFoundException e) {
+ throw new GuacamoleException("Listener class not found.", e);
+ }
+ catch (SecurityException e) {
+ throw new GuacamoleException("Security settings prevent loading of listener class.", e);
+ }
+
+ return listeners;
+
+ }
+
+}
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/package-info.java
new file mode 100644
index 0000000..7324280
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/properties/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes related to the properties which the Guacamole web application
+ * (and stock parts of it) read from guacamole.properties.
+ */
+package org.glyptodon.guacamole.net.basic.properties;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/DocumentHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/DocumentHandler.java
new file mode 100644
index 0000000..8bbe4b0
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/DocumentHandler.java
@@ -0,0 +1,196 @@
+package org.glyptodon.guacamole.net.basic.xml;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.util.Deque;
+import java.util.LinkedList;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * A simple ContentHandler implementation which digests SAX document events and
+ * produces simpler tag-level events, maintaining its own stack for the
+ * convenience of the tag handlers.
+ *
+ * @author Mike Jumper
+ */
+public class DocumentHandler extends DefaultHandler {
+
+ /**
+ * The name of the root element of the document.
+ */
+ private String rootElementName;
+
+ /**
+ * The handler which will be used to handle element events for the root
+ * element of the document.
+ */
+ private TagHandler root;
+
+ /**
+ * The stack of all states applicable to the current parser state. Each
+ * element of the stack references the TagHandler for the element being
+ * parsed at that level of the document, where the current element is
+ * last in the stack, and the root element is first.
+ */
+ private Deque<DocumentHandlerState> stack =
+ new LinkedList<DocumentHandlerState>();
+
+ /**
+ * Creates a new DocumentHandler which will use the given TagHandler
+ * to handle the root element.
+ *
+ * @param rootElementName The name of the root element of the document
+ * being handled.
+ * @param root The TagHandler to use for the root element.
+ */
+ public DocumentHandler(String rootElementName, TagHandler root) {
+ this.root = root;
+ this.rootElementName = rootElementName;
+ }
+
+ /**
+ * Returns the current element state. The current element state is the
+ * state of the element the parser is currently within.
+ *
+ * @return The current element state.
+ */
+ private DocumentHandlerState getCurrentState() {
+
+ // If no state, return null
+ if (stack.isEmpty())
+ return null;
+
+ return stack.getLast();
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) throws SAXException {
+
+ // Get current state
+ DocumentHandlerState current = getCurrentState();
+
+ // Handler for tag just read
+ TagHandler handler;
+
+ // If no stack, use root handler
+ if (current == null) {
+
+ // Validate element name
+ if (!localName.equals(rootElementName))
+ throw new SAXException("Root element must be '" + rootElementName + "'");
+
+ handler = root;
+ }
+
+ // Otherwise, get handler from parent
+ else {
+ TagHandler parent_handler = current.getTagHandler();
+ handler = parent_handler.childElement(localName);
+ }
+
+ // If no handler returned, the element was not expected
+ if (handler == null)
+ throw new SAXException("Unexpected element: '" + localName + "'");
+
+ // Initialize handler
+ handler.init(attributes);
+
+ // Append new element state to stack
+ stack.addLast(new DocumentHandlerState(handler));
+
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName)
+ throws SAXException {
+
+ // Pop last element from stack
+ DocumentHandlerState completed = stack.removeLast();
+
+ // Finish element by sending text content
+ completed.getTagHandler().complete(
+ completed.getTextContent().toString());
+
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length)
+ throws SAXException {
+
+ // Append received chunk to text content
+ getCurrentState().getTextContent().append(ch, start, length);
+
+ }
+
+ /**
+ * The current state of the DocumentHandler.
+ */
+ private static class DocumentHandlerState {
+
+ /**
+ * The current text content of the current element being parsed.
+ */
+ private StringBuilder textContent = new StringBuilder();
+
+ /**
+ * The TagHandler which must handle document events related to the
+ * element currently being parsed.
+ */
+ private TagHandler tagHandler;
+
+ /**
+ * Creates a new DocumentHandlerState which will maintain the state
+ * of parsing of the current element, as well as contain the TagHandler
+ * which will receive events related to that element.
+ *
+ * @param tagHandler The TagHandler which should receive any events
+ * related to the element being parsed.
+ */
+ public DocumentHandlerState(TagHandler tagHandler) {
+ this.tagHandler = tagHandler;
+ }
+
+ /**
+ * Returns the mutable StringBuilder which contains the current text
+ * content of the element being parsed.
+ *
+ * @return The mutable StringBuilder which contains the current text
+ * content of the element being parsed.
+ */
+ public StringBuilder getTextContent() {
+ return textContent;
+ }
+
+ /**
+ * Returns the TagHandler which must handle any events relating to the
+ * element being parsed.
+ *
+ * @return The TagHandler which must handle any events relating to the
+ * element being parsed.
+ */
+ public TagHandler getTagHandler() {
+ return tagHandler;
+ }
+
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/TagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/TagHandler.java
new file mode 100644
index 0000000..08b7ad1
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/TagHandler.java
@@ -0,0 +1,66 @@
+package org.glyptodon.guacamole.net.basic.xml;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * A simple element-level event handler for events triggered by the
+ * SAX-driven DocumentHandler parser.
+ *
+ * @author Mike Jumper
+ */
+public interface TagHandler {
+
+ /**
+ * Called when a child element of the current element is parsed.
+ *
+ * @param localName The local name of the child element seen.
+ * @return The TagHandler which should handle all element-level events
+ * related to the child element.
+ * @throws SAXException If the child element being parsed was not expected,
+ * or some other error prevents a proper TagHandler
+ * from being constructed for the child element.
+ */
+ public TagHandler childElement(String localName)
+ throws SAXException;
+
+ /**
+ * Called when the element corresponding to this TagHandler is first seen,
+ * just after an instance is created.
+ *
+ * @param attributes The attributes of the element seen.
+ * @throws SAXException If an error prevents a the TagHandler from being
+ * from being initialized.
+ */
+ public void init(Attributes attributes) throws SAXException;
+
+ /**
+ * Called when this element, and all child elements, have been fully parsed,
+ * and the entire text content of this element (if any) is available.
+ *
+ * @param textContent The full text content of this element, if any.
+ * @throws SAXException If the text content received is not valid for any
+ * reason, or the child elements parsed are not
+ * correct.
+ */
+ public void complete(String textContent) throws SAXException;
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/package-info.java
new file mode 100644
index 0000000..082fb4c
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes driving the SAX-based XML parser used by the Guacamole web
+ * application.
+ */
+package org.glyptodon.guacamole.net.basic.xml;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/OptionTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/OptionTagHandler.java
new file mode 100644
index 0000000..8c3f7a4
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/OptionTagHandler.java
@@ -0,0 +1,61 @@
+package org.glyptodon.guacamole.net.basic.xml.protocol;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.ProtocolParameterOption;
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "option" element.
+ *
+ * @author Mike Jumper
+ */
+public class OptionTagHandler implements TagHandler {
+
+ /**
+ * The option backing this option tag.
+ */
+ private ProtocolParameterOption option = new ProtocolParameterOption();
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+ option.setValue(attributes.getValue("value"));
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+ throw new SAXException("The 'param' tag can contain no elements.");
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ option.setTitle(textContent);
+ }
+
+ /**
+ * Returns the ProtocolParameterOption backing this tag.
+ * @return The ProtocolParameterOption backing this tag.
+ */
+ public ProtocolParameterOption asProtocolParameterOption() {
+ return option;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/ParamTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/ParamTagHandler.java
new file mode 100644
index 0000000..b4223f7
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/ParamTagHandler.java
@@ -0,0 +1,112 @@
+package org.glyptodon.guacamole.net.basic.xml.protocol;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.ProtocolParameter;
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "param" element.
+ *
+ * @author Mike Jumper
+ */
+public class ParamTagHandler implements TagHandler {
+
+ /**
+ * The ProtocolParameter backing this tag handler.
+ */
+ private ProtocolParameter protocolParameter = new ProtocolParameter();
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+
+ protocolParameter.setName(attributes.getValue("name"));
+ protocolParameter.setTitle(attributes.getValue("title"));
+ protocolParameter.setValue(attributes.getValue("value"));
+
+ // Parse type
+ String type = attributes.getValue("type");
+
+ // Text field
+ if ("text".equals(type))
+ protocolParameter.setType(ProtocolParameter.Type.TEXT);
+
+ // Numeric field
+ else if ("numeric".equals(type))
+ protocolParameter.setType(ProtocolParameter.Type.NUMERIC);
+
+ // Password field
+ else if ("password".equals(type))
+ protocolParameter.setType(ProtocolParameter.Type.PASSWORD);
+
+ // Enumerated field
+ else if ("enum".equals(type))
+ protocolParameter.setType(ProtocolParameter.Type.ENUM);
+
+ // Boolean field
+ else if ("boolean".equals(type)) {
+ protocolParameter.setType(ProtocolParameter.Type.BOOLEAN);
+
+ if(protocolParameter.getValue() == null)
+ throw new SAXException
+ ("A value is required for the boolean parameter type.");
+ }
+
+ // Otherwise, fail with unrecognized type
+ else
+ throw new SAXException("Invalid parameter type: " + type);
+
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+
+ // Start parsing of option tags
+ if (localName.equals("option")) {
+
+ // Get tag handler for option tag
+ OptionTagHandler tagHandler = new OptionTagHandler();
+
+ // Store stub in options collection
+ protocolParameter.getOptions().add(
+ tagHandler.asProtocolParameterOption());
+ return tagHandler;
+
+ }
+
+ return null;
+
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ // Do nothing
+ }
+
+ /**
+ * Returns the ProtocolParameter backing this tag.
+ * @return The ProtocolParameter backing this tag.
+ */
+ public ProtocolParameter asProtocolParameter() {
+ return protocolParameter;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/ProtocolTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/ProtocolTagHandler.java
new file mode 100644
index 0000000..e532b3a
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/ProtocolTagHandler.java
@@ -0,0 +1,77 @@
+package org.glyptodon.guacamole.net.basic.xml.protocol;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.ProtocolInfo;
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "protocol" element.
+ *
+ * @author Mike Jumper
+ */
+public class ProtocolTagHandler implements TagHandler {
+
+ /**
+ * The ProtocolInfo object which will contain all data parsed by this tag
+ * handler.
+ */
+ private ProtocolInfo info = new ProtocolInfo();
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+ info.setName(attributes.getValue("name"));
+ info.setTitle(attributes.getValue("title"));
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+
+ // Start parsing of param tags, add to list of all parameters
+ if (localName.equals("param")) {
+
+ // Get tag handler for param tag
+ ParamTagHandler tagHandler = new ParamTagHandler();
+
+ // Store stub in parameters collection
+ info.getParameters().add(tagHandler.asProtocolParameter());
+ return tagHandler;
+
+ }
+
+ return null;
+
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ // Do nothing
+ }
+
+ /**
+ * Returns the ProtocolInfo backing this tag.
+ * @return The ProtocolInfo backing this tag.
+ */
+ public ProtocolInfo asProtocolInfo() {
+ return info;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/package-info.java
new file mode 100644
index 0000000..dbf7862
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/protocol/package-info.java
@@ -0,0 +1,7 @@
+
+/**
+ * Classes related to parsing XML files which describe the parameters of a
+ * protocol.
+ */
+package org.glyptodon.guacamole.net.basic.xml.protocol;
+
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/AuthorizeTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/AuthorizeTagHandler.java
new file mode 100644
index 0000000..3e0d059
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/AuthorizeTagHandler.java
@@ -0,0 +1,147 @@
+package org.glyptodon.guacamole.net.basic.xml.user_mapping;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.auth.Authorization;
+import org.glyptodon.guacamole.net.basic.auth.UserMapping;
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "authorize" element.
+ *
+ * @author Mike Jumper
+ */
+public class AuthorizeTagHandler implements TagHandler {
+
+ /**
+ * The Authorization corresponding to the "authorize" tag being handled
+ * by this tag handler. The data of this Authorization will be populated
+ * as the tag is parsed.
+ */
+ private Authorization authorization = new Authorization();
+
+ /**
+ * The default GuacamoleConfiguration to use if "param" or "protocol"
+ * tags occur outside a "connection" tag.
+ */
+ private GuacamoleConfiguration default_config = null;
+
+ /**
+ * The UserMapping this authorization belongs to.
+ */
+ private UserMapping parent;
+
+ /**
+ * Creates a new AuthorizeTagHandler that parses an Authorization owned
+ * by the given UserMapping.
+ *
+ * @param parent The UserMapping that owns the Authorization this handler
+ * will parse.
+ */
+ public AuthorizeTagHandler(UserMapping parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+
+ // Init username and password
+ authorization.setUsername(attributes.getValue("username"));
+ authorization.setPassword(attributes.getValue("password"));
+
+ // Get encoding
+ String encoding = attributes.getValue("encoding");
+ if (encoding != null) {
+
+ // If "md5", use MD5 encoding
+ if (encoding.equals("md5"))
+ authorization.setEncoding(Authorization.Encoding.MD5);
+
+ // If "plain", use plain text
+ else if (encoding.equals("plain"))
+ authorization.setEncoding(Authorization.Encoding.PLAIN_TEXT);
+
+ // Otherwise, bad encoding
+ else
+ throw new SAXException(
+ "Invalid encoding: '" + encoding + "'");
+
+ }
+
+ parent.addAuthorization(this.asAuthorization());
+
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+
+ // "connection" tag
+ if (localName.equals("connection"))
+ return new ConnectionTagHandler(authorization);
+
+ // "param" tag
+ if (localName.equals("param")) {
+
+ // Create default config if it doesn't exist
+ if (default_config == null) {
+ default_config = new GuacamoleConfiguration();
+ authorization.addConfiguration("DEFAULT", default_config);
+ }
+
+ return new ParamTagHandler(default_config);
+ }
+
+ // "protocol" tag
+ if (localName.equals("protocol")) {
+
+ // Create default config if it doesn't exist
+ if (default_config == null) {
+ default_config = new GuacamoleConfiguration();
+ authorization.addConfiguration("DEFAULT", default_config);
+ }
+
+ return new ProtocolTagHandler(default_config);
+ }
+
+ return null;
+
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ // Do nothing
+ }
+
+ /**
+ * Returns an Authorization backed by the data of this authorize tag
+ * handler. This Authorization is guaranteed to at least have the username,
+ * password, and encoding available. Any associated configurations will be
+ * added dynamically as the authorize tag is parsed.
+ *
+ * @return An Authorization backed by the data of this authorize tag
+ * handler.
+ */
+ public Authorization asAuthorization() {
+ return authorization;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ConnectionTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ConnectionTagHandler.java
new file mode 100644
index 0000000..ef30ddb
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ConnectionTagHandler.java
@@ -0,0 +1,106 @@
+package org.glyptodon.guacamole.net.basic.xml.user_mapping;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.auth.Authorization;
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "connection" element.
+ *
+ * @author Mike Jumper
+ */
+public class ConnectionTagHandler implements TagHandler {
+
+ /**
+ * The GuacamoleConfiguration backing this tag handler.
+ */
+ private GuacamoleConfiguration config = new GuacamoleConfiguration();
+
+ /**
+ * The name associated with the connection being parsed.
+ */
+ private String name;
+
+ /**
+ * The Authorization this connection belongs to.
+ */
+ private Authorization parent;
+
+ /**
+ * Creates a new ConnectionTagHandler that parses a Connection owned by
+ * the given Authorization.
+ *
+ * @param parent The Authorization that will own this Connection once
+ * parsed.
+ */
+ public ConnectionTagHandler(Authorization parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+ name = attributes.getValue("name");
+ parent.addConfiguration(name, this.asGuacamoleConfiguration());
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+
+ if (localName.equals("param"))
+ return new ParamTagHandler(config);
+
+ if (localName.equals("protocol"))
+ return new ProtocolTagHandler(config);
+
+ return null;
+
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ // Do nothing
+ }
+
+ /**
+ * Returns a GuacamoleConfiguration whose contents are populated from data
+ * within this connection element and child elements. This
+ * GuacamoleConfiguration will continue to be modified as the user mapping
+ * is parsed.
+ *
+ * @return A GuacamoleConfiguration whose contents are populated from data
+ * within this connection element.
+ */
+ public GuacamoleConfiguration asGuacamoleConfiguration() {
+ return config;
+ }
+
+ /**
+ * Returns the name associated with this connection.
+ *
+ * @return The name associated with this connection.
+ */
+ public String getName() {
+ return name;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ParamTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ParamTagHandler.java
new file mode 100644
index 0000000..1e65e2c
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ParamTagHandler.java
@@ -0,0 +1,70 @@
+package org.glyptodon.guacamole.net.basic.xml.user_mapping;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "param" element.
+ *
+ * @author Mike Jumper
+ */
+public class ParamTagHandler implements TagHandler {
+
+ /**
+ * The GuacamoleConfiguration which will be populated with data from
+ * the tag handled by this tag handler.
+ */
+ private GuacamoleConfiguration config;
+
+ /**
+ * The name of the parameter.
+ */
+ private String name;
+
+ /**
+ * Creates a new handler for an "param" tag having the given
+ * attributes.
+ *
+ * @param config The GuacamoleConfiguration to update with the data parsed
+ * from the "protocol" tag.
+ */
+ public ParamTagHandler(GuacamoleConfiguration config) {
+ this.config = config;
+ }
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+ throw new SAXException("The 'param' tag can contain no elements.");
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ config.setParameter(name, textContent);
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ProtocolTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ProtocolTagHandler.java
new file mode 100644
index 0000000..14f0753
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/ProtocolTagHandler.java
@@ -0,0 +1,66 @@
+package org.glyptodon.guacamole.net.basic.xml.user_mapping;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "protocol" element.
+ *
+ * @author Mike Jumper
+ */
+public class ProtocolTagHandler implements TagHandler {
+
+ /**
+ * The GuacamoleConfiguration which will be populated with data from
+ * the tag handled by this tag handler.
+ */
+ private GuacamoleConfiguration config;
+
+ /**
+ * Creates a new handler for a "protocol" tag having the given
+ * attributes.
+ *
+ * @param config The GuacamoleConfiguration to update with the data parsed
+ * from the "protocol" tag.
+ * @throws SAXException If the attributes given are not valid.
+ */
+ public ProtocolTagHandler(GuacamoleConfiguration config) throws SAXException {
+ this.config = config;
+ }
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+ // Do nothing
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+ throw new SAXException("The 'protocol' tag can contain no elements.");
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ config.setProtocol(textContent);
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/UserMappingTagHandler.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/UserMappingTagHandler.java
new file mode 100644
index 0000000..8160a58
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/UserMappingTagHandler.java
@@ -0,0 +1,74 @@
+package org.glyptodon.guacamole.net.basic.xml.user_mapping;
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import org.glyptodon.guacamole.net.basic.auth.UserMapping;
+import org.glyptodon.guacamole.net.basic.xml.TagHandler;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * TagHandler for the "user-mapping" element.
+ *
+ * @author Mike Jumper
+ */
+public class UserMappingTagHandler implements TagHandler {
+
+ /**
+ * The UserMapping which will contain all data parsed by this tag handler.
+ */
+ private UserMapping user_mapping = new UserMapping();
+
+ @Override
+ public void init(Attributes attributes) throws SAXException {
+ // Do nothing
+ }
+
+ @Override
+ public TagHandler childElement(String localName) throws SAXException {
+
+ // Start parsing of authorize tags, add to list of all authorizations
+ if (localName.equals("authorize"))
+ return new AuthorizeTagHandler(user_mapping);
+
+ return null;
+
+ }
+
+ @Override
+ public void complete(String textContent) throws SAXException {
+ // Do nothing
+ }
+
+ /**
+ * Returns a user mapping containing all authorizations and configurations
+ * parsed so far. This user mapping will be backed by the data being parsed,
+ * thus any additional authorizations or configurations will be available
+ * in the object returned by this function even after this function has
+ * returned, once the data corresponding to those authorizations or
+ * configurations has been parsed.
+ *
+ * @return A user mapping containing all authorizations and configurations
+ * parsed so far.
+ */
+ public UserMapping asUserMapping() {
+ return user_mapping;
+ }
+
+}
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/package-info.java
new file mode 100644
index 0000000..ae85ac7
--- /dev/null
+++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/xml/user_mapping/package-info.java
@@ -0,0 +1,6 @@
+
+/**
+ * Classes related to parsing the user-mapping.xml file.
+ */
+package org.glyptodon.guacamole.net.basic.xml.user_mapping;
+
diff --git a/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/rdp.xml b/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/rdp.xml
new file mode 100644
index 0000000..dee0273
--- /dev/null
+++ b/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/rdp.xml
@@ -0,0 +1,44 @@
+<protocol name="rdp" title="RDP">
+
+ <param name="hostname" type="text" title="Hostname"/>
+ <param name="port" type="numeric" title="Port"/>
+
+ <param name="username" type="text" title="Username"/>
+ <param name="password" type="password" title="Password"/>
+ <param name="domain" type="text" title="Domain"/>
+ <param name="initial-program" type="text" title="Initial program"/>
+
+ <param name="width" type="numeric" title="Display width"/>
+ <param name="height" type="numeric" title="Display height"/>
+ <param name="color-depth" type="enum" title="Color depth">
+ <option value="8">256 color</option>
+ <option value="16">Low color (16-bit)</option>
+ <option value="24">True color (24-bit)</option>
+ <option value="32">True color (32-bit)</option>
+ </param>
+
+ <param name="server-layout" type="enum" title="Keyboard layout">
+ <option value="">(default)</option>
+ <option value="en-us-qwerty">US English (Qwerty)</option>
+ <option value="fr-fr-azerty">French (Azerty)</option>
+ <option value="de-de-qwertz">German (Qwertz)</option>
+ <option value="failsafe">Unicode</option>
+ </param>
+
+ <param name="console" type="boolean" title="Administrator console" value="true"/>
+ <param name="console-audio" type="boolean" title="Support audio in console" value="true"/>
+ <param name="disable-audio" type="boolean" title="Disable audio" value="true"/>
+ <param name="enable-printing" type="boolean" title="Enable printing" value="true"/>
+
+ <param name="security" type="enum" title="Security mode">
+ <option value="">(default)</option>
+ <option value="rdp">RDP encryption</option>
+ <option value="tls">TLS encryption</option>
+ <option value="nla">NLA (Network Level Authentication)</option>
+ <option value="any">Any</option>
+ </param>
+
+ <param name="disable-auth" type="boolean" title="Disable authentication" value="true"/>
+ <param name="ignore-cert" type="boolean" title="Ignore server certificate" value="true"/>
+
+</protocol>
diff --git a/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/ssh.xml b/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/ssh.xml
new file mode 100644
index 0000000..afef1a9
--- /dev/null
+++ b/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/ssh.xml
@@ -0,0 +1,28 @@
+<protocol name="ssh" title="SSH">
+
+ <param name="hostname" title="Hostname" type="text"/>
+ <param name="port" title="Port" type="numeric"/>
+
+ <param name="username" title="Username" type="text"/>
+ <param name="password" title="Password" type="password"/>
+
+ <param name="font-name" title="Font name" type="text"/>
+ <param name="font-size" title="Font size" type="enum">
+ <option value=""></option>
+ <option value="8">8</option>
+ <option value="9">9</option>
+ <option value="10">10</option>
+ <option value="11">11</option>
+ <option value="12">12</option>
+ <option value="14">14</option>
+ <option value="18">18</option>
+ <option value="24">24</option>
+ <option value="30">30</option>
+ <option value="36">36</option>
+ <option value="48">48</option>
+ <option value="60">60</option>
+ <option value="72">72</option>
+ <option value="96">96</option>
+ </param>
+
+</protocol>
diff --git a/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/vnc.xml b/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/vnc.xml
new file mode 100644
index 0000000..3f1ca82
--- /dev/null
+++ b/guacamole/src/main/resources/net/sourceforge/guacamole/net/protocols/vnc.xml
@@ -0,0 +1,23 @@
+<protocol name="vnc" title="VNC">
+
+ <param name="hostname" type="text" title="Hostname"/>
+ <param name="port" type="numeric" title="Port"/>
+ <param name="password" type="password" title="Password"/>
+
+ <param name="read-only" type="boolean" title="Read-only" value="true"/>
+ <param name="swap-red-blue" type="boolean" title="Swap red/blue components" value="true"/>
+
+ <param name="color-depth" type="enum" title="Color depth">
+ <option value="8">256 color</option>
+ <option value="16">Low color (16-bit)</option>
+ <option value="24">True color (24-bit)</option>
+ <option value="32">True color (32-bit)</option>
+ </param>
+
+ <param name="dest-host" type="text" title="Repeater destination host"/>
+ <param name="dest-port" type="numeric" title="Repeater destination port"/>
+
+ <param name="enable-audio" type="boolean" title="Enable audio" value="true"/>
+ <param name="audio-servername" type="text" title="Audio server name"/>
+
+</protocol>
diff --git a/guacamole/src/main/webapp/META-INF/context.xml b/guacamole/src/main/webapp/META-INF/context.xml
new file mode 100644
index 0000000..26f2130
--- /dev/null
+++ b/guacamole/src/main/webapp/META-INF/context.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Context antiJARLocking="true" path="/guacamole"/>
diff --git a/guacamole/src/main/webapp/WEB-INF/web.xml b/guacamole/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..728d5e6
--- /dev/null
+++ b/guacamole/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,254 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+
+ <!-- Basic config -->
+ <welcome-file-list>
+ <welcome-file>index.xhtml</welcome-file>
+ </welcome-file-list>
+ <session-config>
+ <session-timeout>
+ 30
+ </session-timeout>
+ </session-config>
+
+ <!-- Automatically detect and load WebSocket support -->
+ <listener>
+ <listener-class>org.glyptodon.guacamole.net.basic.WebSocketSupportLoader</listener-class>
+ </listener>
+
+ <!-- Basic Login Servlet -->
+ <servlet>
+ <description>Login servlet.</description>
+ <servlet-name>Login</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.BasicLogin</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Login</servlet-name>
+ <url-pattern>/login</url-pattern>
+ </servlet-mapping>
+
+ <!-- Basic Logout Servlet -->
+ <servlet>
+ <description>Logout servlet.</description>
+ <servlet-name>Logout</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.BasicLogout</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Logout</servlet-name>
+ <url-pattern>/logout</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Creation Servlet -->
+ <servlet>
+ <description>Connection creation servlet.</description>
+ <servlet-name>ConnectionCreate</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connections.Create</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionCreate</servlet-name>
+ <url-pattern>/connections/create</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection List Servlet -->
+ <servlet>
+ <description>Connection list servlet.</description>
+ <servlet-name>Connections</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connections.List</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Connections</servlet-name>
+ <url-pattern>/connections</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Update Servlet -->
+ <servlet>
+ <description>Connection update servlet.</description>
+ <servlet-name>ConnectionUpdate</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connections.Update</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionUpdate</servlet-name>
+ <url-pattern>/connections/update</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Move Servlet -->
+ <servlet>
+ <description>Connection move servlet.</description>
+ <servlet-name>ConnectionMove</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connections.Move</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionMove</servlet-name>
+ <url-pattern>/connections/move</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Deletion Servlet -->
+ <servlet>
+ <description>Connection deletion servlet.</description>
+ <servlet-name>ConnectionDelete</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connections.Delete</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionDelete</servlet-name>
+ <url-pattern>/connections/delete</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Group Creation Servlet -->
+ <servlet>
+ <description>ConnectionGroup creation servlet.</description>
+ <servlet-name>ConnectionGroupCreate</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connectiongroups.Create</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionGroupCreate</servlet-name>
+ <url-pattern>/connectiongroups/create</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Group List Servlet -->
+ <servlet>
+ <description>ConnectionGroup list servlet.</description>
+ <servlet-name>ConnectionGroups</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connectiongroups.List</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionGroups</servlet-name>
+ <url-pattern>/connectiongroups</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Group Update Servlet -->
+ <servlet>
+ <description>ConnectionGroup update servlet.</description>
+ <servlet-name>ConnectionGroupUpdate</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connectiongroups.Update</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionGroupUpdate</servlet-name>
+ <url-pattern>/connectiongroups/update</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Group Move Servlet -->
+ <servlet>
+ <description>ConnectionGroup move servlet.</description>
+ <servlet-name>ConnectionGroupMove</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connectiongroups.Move</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionGroupMove</servlet-name>
+ <url-pattern>/connectiongroups/move</url-pattern>
+ </servlet-mapping>
+
+ <!-- Connection Group Deletion Servlet -->
+ <servlet>
+ <description>ConnectionGroup deletion servlet.</description>
+ <servlet-name>ConnectionGroupDelete</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.connectiongroups.Delete</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>ConnectionGroupDelete</servlet-name>
+ <url-pattern>/connectiongroups/delete</url-pattern>
+ </servlet-mapping>
+
+ <!-- User Creation Servlet -->
+ <servlet>
+ <description>User creation servlet.</description>
+ <servlet-name>UserCreate</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.users.Create</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>UserCreate</servlet-name>
+ <url-pattern>/users/create</url-pattern>
+ </servlet-mapping>
+
+ <!-- User List Servlet -->
+ <servlet>
+ <description>User list servlet.</description>
+ <servlet-name>Users</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.users.List</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Users</servlet-name>
+ <url-pattern>/users</url-pattern>
+ </servlet-mapping>
+
+ <!-- User Update Servlet -->
+ <servlet>
+ <description>User update servlet.</description>
+ <servlet-name>UserUpdate</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.users.Update</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>UserUpdate</servlet-name>
+ <url-pattern>/users/update</url-pattern>
+ </servlet-mapping>
+
+ <!-- User Deletion Servlet -->
+ <servlet>
+ <description>User deletion servlet.</description>
+ <servlet-name>UserDelete</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.users.Delete</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>UserDelete</servlet-name>
+ <url-pattern>/users/delete</url-pattern>
+ </servlet-mapping>
+
+ <!-- Permission List Servlet -->
+ <servlet>
+ <description>Permission list servlet.</description>
+ <servlet-name>Permissions</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.permissions.List</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Permissions</servlet-name>
+ <url-pattern>/permissions</url-pattern>
+ </servlet-mapping>
+
+ <!-- Protocol List Servlet -->
+ <servlet>
+ <description>Protocol list servlet.</description>
+ <servlet-name>Protocols</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.crud.protocols.List</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Protocols</servlet-name>
+ <url-pattern>/protocols</url-pattern>
+ </servlet-mapping>
+
+ <!-- Guacamole Tunnel Servlet -->
+ <servlet>
+ <description>Tunnel servlet.</description>
+ <servlet-name>Tunnel</servlet-name>
+ <servlet-class>org.glyptodon.guacamole.net.basic.BasicGuacamoleTunnelServlet</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Tunnel</servlet-name>
+ <url-pattern>/tunnel</url-pattern>
+ </servlet-mapping>
+
+ <mime-mapping>
+ <extension>mp3</extension>
+ <mime-type>audio/mpeg</mime-type>
+ </mime-mapping>
+ <mime-mapping>
+ <extension>ogg</extension>
+ <mime-type>audio/ogg</mime-type>
+ </mime-mapping>
+
+</web-app>
diff --git a/guacamole/src/main/webapp/admin.xhtml b/guacamole/src/main/webapp/admin.xhtml
new file mode 100644
index 0000000..ec98b12
--- /dev/null
+++ b/guacamole/src/main/webapp/admin.xhtml
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html>
+
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+ <head>
+ <link rel="icon" type="image/png" href="images/guacamole-logo-64.png"/>
+ <link rel="apple-touch-icon" type="image/png" href="images/guacamole-logo-144.png"/>
+ <link rel="stylesheet" type="text/css" href="styles/ui.css"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=medium-dpi"/>
+ <title>Guacamole ${project.version}</title>
+ </head>
+
+ <body>
+
+ <div id="logout-panel">
+ <button id="back">Back</button>
+ <button id="logout">Logout</button>
+ </div>
+
+ <h2>Administration</h2>
+ <div class="settings section">
+
+ <h3 class="require-manage-users">Users</h3>
+ <div class="require-manage-users" id="users">
+
+ <p>
+ Click or tap on a user below to manage that user. Depending
+ on your access level, users can be added and deleted, and their
+ passwords can be changed.
+ </p>
+
+ <div id="user-add-form">
+ <div class="icon user add"/><input type="text" class="name" id="username" placeholder="Add user"/><button id="add-user">Add</button>
+ </div>
+
+ <div id="user-list">
+ </div>
+
+ <div id="user-list-buttons">
+ </div>
+
+ </div>
+
+ <h3 class="require-manage-connections">Connections</h3>
+ <div class="require-manage-connections" id="connections">
+
+ <p>
+ Click or tap on a connection below to manage that connection.
+ Depending on your access level, connections can be added and
+ deleted, and their properties (protocol, hostname, port, etc.)
+ can be changed.
+ </p>
+
+ <div id="connection-add-form">
+ <button id="add-connection">New Connection</button><button id="add-connection-group">New Group</button>
+ </div>
+
+ <div id="connection-list">
+ </div>
+
+ <div id="connection-list-buttons">
+ </div>
+
+ </div>
+
+ </div>
+
+ <div id="version-dialog">
+ Guacamole ${project.version}
+ </div>
+
+ <script type="text/javascript" src="scripts/session.js"></script>
+ <script type="text/javascript" src="scripts/guac-ui.js"></script>
+ <script type="text/javascript" src="scripts/service.js"></script>
+ <script type="text/javascript" src="scripts/history.js"></script>
+ <script type="text/javascript" src="scripts/admin-ui.js"></script>
+
+ </body>
+
+</html>
diff --git a/guacamole/src/main/webapp/agpl-3.0-standalone.html b/guacamole/src/main/webapp/agpl-3.0-standalone.html
new file mode 100644
index 0000000..bf47c6c
--- /dev/null
+++ b/guacamole/src/main/webapp/agpl-3.0-standalone.html
@@ -0,0 +1,688 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<html><head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
+</head>
+ <link rel="alternate" type="application/rdf+xml"
+ href="http://www.gnu.org/licenses/agpl-3.0.rdf" />
+<body>
+<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
+<p style="text-align: center;">Version 3, 19 November 2007</p>
+
+<p>Copyright © 2007 Free Software Foundation,
+Inc. <<a href="http://fsf.org/">http://fsf.org/</a>>
+ <br />
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.</p>
+
+<h3><a name="preamble"></a>Preamble</h3>
+
+<p>The GNU Affero General Public License is a free, copyleft license
+for software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.</p>
+
+<p>The licenses for most software and other practical works are
+designed to take away your freedom to share and change the works. By
+contrast, our General Public Licenses are intended to guarantee your
+freedom to share and change all versions of a program--to make sure it
+remains free software for all its users.</p>
+
+<p>When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.</p>
+
+<p>Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.</p>
+
+<p>A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.</p>
+
+<p>The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.</p>
+
+<p>An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.</p>
+
+<p>The precise terms and conditions for copying, distribution and
+modification follow.</p>
+
+<h3><a name="terms"></a>TERMS AND CONDITIONS</h3>
+
+<h4><a name="section0"></a>0. Definitions.</h4>
+
+<p>"This License" refers to version 3 of the GNU Affero General Public
+License.</p>
+
+<p>"Copyright" also means copyright-like laws that apply to other kinds
+of works, such as semiconductor masks.</p>
+
+<p>"The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.</p>
+
+<p>To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.</p>
+
+<p>A "covered work" means either the unmodified Program or a work based
+on the Program.</p>
+
+<p>To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.</p>
+
+<p>To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.</p>
+
+<p>An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.</p>
+
+<h4><a name="section1"></a>1. Source Code.</h4>
+
+<p>The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.</p>
+
+<p>A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.</p>
+
+<p>The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.</p>
+
+<p>The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.</p>
+
+<p>The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.</p>
+
+<p>The Corresponding Source for a work in source code form is that
+same work.</p>
+
+<h4><a name="section2"></a>2. Basic Permissions.</h4>
+
+<p>All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.</p>
+
+<p>You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.</p>
+
+<p>Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.</p>
+
+<h4><a name="section3"></a>3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
+
+<p>No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.</p>
+
+<p>When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.</p>
+
+<h4><a name="section4"></a>4. Conveying Verbatim Copies.</h4>
+
+<p>You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.</p>
+
+<p>You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.</p>
+
+<h4><a name="section5"></a>5. Conveying Modified Source Versions.</h4>
+
+<p>You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:</p>
+
+<ul>
+
+<li>a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.</li>
+
+<li>b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".</li>
+
+<li>c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.</li>
+
+<li>d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.</li>
+
+</ul>
+
+<p>A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.</p>
+
+<h4><a name="section6"></a>6. Conveying Non-Source Forms.</h4>
+
+<p>You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:</p>
+
+<ul>
+
+<li>a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.</li>
+
+<li>b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.</li>
+
+<li>c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.</li>
+
+<li>d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.</li>
+
+<li>e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.</li>
+
+</ul>
+
+<p>A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.</p>
+
+<p>A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.</p>
+
+<p>"Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.</p>
+
+<p>If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).</p>
+
+<p>The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.</p>
+
+<p>Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.</p>
+
+<h4><a name="section7"></a>7. Additional Terms.</h4>
+
+<p>"Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.</p>
+
+<p>When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.</p>
+
+<p>Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:</p>
+
+<ul>
+
+<li>a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or</li>
+
+<li>b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or</li>
+
+<li>c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or</li>
+
+<li>d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or</li>
+
+<li>e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or</li>
+
+<li>f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.</li>
+
+</ul>
+
+<p>All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further restriction,
+you may remove that term. If a license document contains a further
+restriction but permits relicensing or conveying under this License, you
+may add to a covered work material governed by the terms of that license
+document, provided that the further restriction does not survive such
+relicensing or conveying.</p>
+
+<p>If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.</p>
+
+<p>Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.</p>
+
+<h4><a name="section8"></a>8. Termination.</h4>
+
+<p>You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).</p>
+
+<p>However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.</p>
+
+<p>Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.</p>
+
+<p>Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.</p>
+
+<h4><a name="section9"></a>9. Acceptance Not Required for Having Copies.</h4>
+
+<p>You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.</p>
+
+<h4><a name="section10"></a>10. Automatic Licensing of Downstream Recipients.</h4>
+
+<p>Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.</p>
+
+<p>An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.</p>
+
+<p>You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.</p>
+
+<h4><a name="section11"></a>11. Patents.</h4>
+
+<p>A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".</p>
+
+<p>A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.</p>
+
+<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.</p>
+
+<p>In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.</p>
+
+<p>If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.</p>
+
+<p>If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.</p>
+
+<p>A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.</p>
+
+<p>Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.</p>
+
+<h4><a name="section12"></a>12. No Surrender of Others' Freedom.</h4>
+
+<p>If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.</p>
+
+<h4><a name="section13"></a>13. Remote Network Interaction; Use with the GNU General Public License.</h4>
+
+<p>Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.</p>
+
+<p>Notwithstanding any other provision of this License, you have permission
+to link or combine any covered work with a work licensed under version 3
+of the GNU General Public License into a single combined work, and to
+convey the resulting work. The terms of this License will continue to
+apply to the part which is the covered work, but the work with which it is
+combined will remain governed by version 3 of the GNU General Public
+License.</p>
+
+<h4><a name="section14"></a>14. Revised Versions of this License.</h4>
+
+<p>The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may differ
+in detail to address new problems or concerns.</p>
+
+<p>Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero
+General Public License "or any later version" applies to it, you have
+the option of following the terms and conditions either of that
+numbered version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number
+of the GNU Affero General Public License, you may choose any version
+ever published by the Free Software Foundation.</p>
+
+<p>If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that
+proxy's public statement of acceptance of a version permanently
+authorizes you to choose that version for the Program.</p>
+
+<p>Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.</p>
+
+<h4><a name="section15"></a>15. Disclaimer of Warranty.</h4>
+
+<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
+
+<h4><a name="section16"></a>16. Limitation of Liability.</h4>
+
+<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.</p>
+
+<h4><a name="section17"></a>17. Interpretation of Sections 15 and 16.</h4>
+
+<p>If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.</p>
+
+<p>END OF TERMS AND CONDITIONS</p>
+
+<h3><a name="howto"></a>How to Apply These Terms to Your New Programs</h3>
+
+<p>If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.</p>
+
+<p>To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.</p>
+
+<pre> <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as
+ published by the Free Software Foundation, either version 3 of the
+ License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+</pre>
+
+<p>Also add information on how to contact you by electronic and paper mail.</p>
+
+<p>If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.</p>
+
+<p>You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>>.</p>
+
+</body></html>
diff --git a/guacamole/src/main/webapp/client.xhtml b/guacamole/src/main/webapp/client.xhtml
new file mode 100644
index 0000000..0034318
--- /dev/null
+++ b/guacamole/src/main/webapp/client.xhtml
@@ -0,0 +1,151 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html>
+
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+ <head>
+ <link rel="icon" type="image/png" href="images/guacamole-logo-64.png"/>
+ <link rel="stylesheet" type="text/css" href="styles/client.css"/>
+ <link rel="stylesheet" type="text/css" href="styles/keyboard.css"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
+ <meta name="apple-mobile-web-app-capable" content="yes"/>
+ <title>Guacamole ${project.version}</title>
+ </head>
+
+ <body>
+
+ <!-- Display -->
+ <div class="displayOuter">
+ <div class="displayMiddle">
+ <div id="display">
+ </div>
+ </div>
+ </div>
+
+ <!-- Dimensional clone of viewport -->
+ <div id="viewportClone"/>
+
+ <!-- Notification area -->
+ <div id="notificationArea"/>
+
+ <!-- Images which should be preloaded -->
+ <div id="preload">
+ <img src="images/action-icons/guac-close.png"/>
+ <img src="images/progress.png"/>
+ </div>
+
+ <script type="text/javascript" src="scripts/lib/blob/blob.js"></script>
+ <script type="text/javascript" src="scripts/lib/filesaver/filesaver.js"></script>
+
+ <!-- guacamole-common-js scripts -->
+ <script type="text/javascript" src="guacamole-common-js/keyboard.js"></script>
+ <script type="text/javascript" src="guacamole-common-js/mouse.js"></script>
+ <script type="text/javascript" src="guacamole-common-js/layer.js"></script>
+ <script type="text/javascript" src="guacamole-common-js/tunnel.js"></script>
+ <script type="text/javascript" src="guacamole-common-js/audio.js"></script>
+ <script type="text/javascript" src="guacamole-common-js/guacamole.js"></script>
+ <script type="text/javascript" src="guacamole-common-js/oskeyboard.js"></script>
+
+ <!-- guacamole-default-webapp scripts -->
+ <script type="text/javascript" src="scripts/session.js"></script>
+ <script type="text/javascript" src="scripts/history.js"></script>
+ <script type="text/javascript" src="scripts/guac-ui.js"></script>
+ <script type="text/javascript" src="scripts/client-ui.js"></script>
+
+ <!-- Init -->
+ <script type="text/javascript"> /* <![CDATA[ */
+
+ // Start connect after control returns from onload (allow browser
+ // to consider the page loaded).
+ window.onload = function() {
+ window.setTimeout(function() {
+
+ var tunnel;
+
+ // If WebSocket available, try to use it.
+ if (window.WebSocket)
+ tunnel = new Guacamole.ChainedTunnel(
+ new Guacamole.WebSocketTunnel("websocket-tunnel"),
+ new Guacamole.HTTPTunnel("tunnel")
+ );
+
+ // If no WebSocket, then use HTTP.
+ else
+ tunnel = new Guacamole.HTTPTunnel("tunnel")
+
+ // Instantiate client
+ var guac = new Guacamole.Client(tunnel);
+
+ // Add client to UI
+ guac.getDisplay().className = "software-cursor";
+ GuacUI.Client.display.appendChild(guac.getDisplay());
+
+ // Tie UI to client
+ GuacUI.Client.attach(guac);
+
+ try {
+
+ // Calculate optimal width/height for display
+ var optimal_width = window.innerWidth;
+ var optimal_height = window.innerHeight;
+
+ // Scale width/height to be at least 600x600
+ if (optimal_width < 600 || optimal_height < 600) {
+ var scale = Math.max(600 / optimal_width, 600 / optimal_height);
+ optimal_width = Math.floor(optimal_width * scale);
+ optimal_height = Math.floor(optimal_height * scale);
+ }
+
+ // Get entire query string, and pass to connect().
+ // Normally, only the "id" parameter is required, but
+ // all parameters should be preserved and passed on for
+ // the sake of authentication.
+
+ var connect_string =
+ window.location.search.substring(1)
+ + "&width=" + optimal_width
+ + "&height=" + optimal_height;
+
+ // Add audio mimetypes to connect_string
+ GuacUI.Audio.supported.forEach(function(mimetype) {
+ connect_string += "&audio=" + encodeURIComponent(mimetype);
+ });
+
+ // Add video mimetypes to connect_string
+ GuacUI.Video.supported.forEach(function(mimetype) {
+ connect_string += "&video=" + encodeURIComponent(mimetype);
+ });
+
+ guac.connect(connect_string);
+
+ }
+ catch (e) {
+ GuacUI.Client.showError(e.message);
+ }
+
+ }, 0);
+ };
+
+ /* ]]> */ </script>
+
+ </body>
+
+</html>
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-close.png b/guacamole/src/main/webapp/images/action-icons/guac-close.png
new file mode 100644
index 0000000..ef29d0f
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-close.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-config.png b/guacamole/src/main/webapp/images/action-icons/guac-config.png
new file mode 100644
index 0000000..eb91fc0
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-config.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-delete.png b/guacamole/src/main/webapp/images/action-icons/guac-delete.png
new file mode 100644
index 0000000..925e958
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-delete.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-first-page.png b/guacamole/src/main/webapp/images/action-icons/guac-first-page.png
new file mode 100644
index 0000000..86c7a97
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-first-page.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-last-page.png b/guacamole/src/main/webapp/images/action-icons/guac-last-page.png
new file mode 100644
index 0000000..b03932c
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-last-page.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-monitor-add.png b/guacamole/src/main/webapp/images/action-icons/guac-monitor-add.png
new file mode 100644
index 0000000..0c9ea96
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-monitor-add.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-next-page.png b/guacamole/src/main/webapp/images/action-icons/guac-next-page.png
new file mode 100644
index 0000000..d4022a4
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-next-page.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-prev-page.png b/guacamole/src/main/webapp/images/action-icons/guac-prev-page.png
new file mode 100644
index 0000000..6f6819d
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-prev-page.png differ
diff --git a/guacamole/src/main/webapp/images/action-icons/guac-user-add.png b/guacamole/src/main/webapp/images/action-icons/guac-user-add.png
new file mode 100644
index 0000000..8b2d80e
Binary files /dev/null and b/guacamole/src/main/webapp/images/action-icons/guac-user-add.png differ
diff --git a/guacamole/src/main/webapp/images/arrows/arrows-d.png b/guacamole/src/main/webapp/images/arrows/arrows-d.png
new file mode 100644
index 0000000..15b1a77
Binary files /dev/null and b/guacamole/src/main/webapp/images/arrows/arrows-d.png differ
diff --git a/guacamole/src/main/webapp/images/arrows/arrows-l.png b/guacamole/src/main/webapp/images/arrows/arrows-l.png
new file mode 100644
index 0000000..91f8150
Binary files /dev/null and b/guacamole/src/main/webapp/images/arrows/arrows-l.png differ
diff --git a/guacamole/src/main/webapp/images/arrows/arrows-r.png b/guacamole/src/main/webapp/images/arrows/arrows-r.png
new file mode 100644
index 0000000..3ab9d5b
Binary files /dev/null and b/guacamole/src/main/webapp/images/arrows/arrows-r.png differ
diff --git a/guacamole/src/main/webapp/images/arrows/arrows-u.png b/guacamole/src/main/webapp/images/arrows/arrows-u.png
new file mode 100644
index 0000000..057cccf
Binary files /dev/null and b/guacamole/src/main/webapp/images/arrows/arrows-u.png differ
diff --git a/guacamole/src/main/webapp/images/group-icons/guac-closed.png b/guacamole/src/main/webapp/images/group-icons/guac-closed.png
new file mode 100644
index 0000000..bfa036b
Binary files /dev/null and b/guacamole/src/main/webapp/images/group-icons/guac-closed.png differ
diff --git a/guacamole/src/main/webapp/images/group-icons/guac-open.png b/guacamole/src/main/webapp/images/group-icons/guac-open.png
new file mode 100644
index 0000000..c6396ed
Binary files /dev/null and b/guacamole/src/main/webapp/images/group-icons/guac-open.png differ
diff --git a/guacamole/src/main/webapp/images/guac-mono-192.png b/guacamole/src/main/webapp/images/guac-mono-192.png
new file mode 100644
index 0000000..4283960
Binary files /dev/null and b/guacamole/src/main/webapp/images/guac-mono-192.png differ
diff --git a/guacamole/src/main/webapp/images/guacamole-logo-144.png b/guacamole/src/main/webapp/images/guacamole-logo-144.png
new file mode 100644
index 0000000..e2cb830
Binary files /dev/null and b/guacamole/src/main/webapp/images/guacamole-logo-144.png differ
diff --git a/guacamole/src/main/webapp/images/guacamole-logo-24.png b/guacamole/src/main/webapp/images/guacamole-logo-24.png
new file mode 100644
index 0000000..3652598
Binary files /dev/null and b/guacamole/src/main/webapp/images/guacamole-logo-24.png differ
diff --git a/guacamole/src/main/webapp/images/guacamole-logo-64.png b/guacamole/src/main/webapp/images/guacamole-logo-64.png
new file mode 100644
index 0000000..99aaf3e
Binary files /dev/null and b/guacamole/src/main/webapp/images/guacamole-logo-64.png differ
diff --git a/guacamole/src/main/webapp/images/mouse/blank.cur b/guacamole/src/main/webapp/images/mouse/blank.cur
new file mode 100644
index 0000000..60b635a
Binary files /dev/null and b/guacamole/src/main/webapp/images/mouse/blank.cur differ
diff --git a/guacamole/src/main/webapp/images/mouse/blank.gif b/guacamole/src/main/webapp/images/mouse/blank.gif
new file mode 100644
index 0000000..ec5c17c
Binary files /dev/null and b/guacamole/src/main/webapp/images/mouse/blank.gif differ
diff --git a/guacamole/src/main/webapp/images/mouse/dot.gif b/guacamole/src/main/webapp/images/mouse/dot.gif
new file mode 100644
index 0000000..9ac8a00
Binary files /dev/null and b/guacamole/src/main/webapp/images/mouse/dot.gif differ
diff --git a/guacamole/src/main/webapp/images/noguacamole-logo-24.png b/guacamole/src/main/webapp/images/noguacamole-logo-24.png
new file mode 100644
index 0000000..2245bfd
Binary files /dev/null and b/guacamole/src/main/webapp/images/noguacamole-logo-24.png differ
diff --git a/guacamole/src/main/webapp/images/progress.png b/guacamole/src/main/webapp/images/progress.png
new file mode 100644
index 0000000..72e0495
Binary files /dev/null and b/guacamole/src/main/webapp/images/progress.png differ
diff --git a/guacamole/src/main/webapp/images/protocol-icons/guac-monitor.png b/guacamole/src/main/webapp/images/protocol-icons/guac-monitor.png
new file mode 100644
index 0000000..6608c29
Binary files /dev/null and b/guacamole/src/main/webapp/images/protocol-icons/guac-monitor.png differ
diff --git a/guacamole/src/main/webapp/images/protocol-icons/guac-plug.png b/guacamole/src/main/webapp/images/protocol-icons/guac-plug.png
new file mode 100644
index 0000000..d54ee53
Binary files /dev/null and b/guacamole/src/main/webapp/images/protocol-icons/guac-plug.png differ
diff --git a/guacamole/src/main/webapp/images/protocol-icons/guac-text.png b/guacamole/src/main/webapp/images/protocol-icons/guac-text.png
new file mode 100644
index 0000000..8d5eff6
Binary files /dev/null and b/guacamole/src/main/webapp/images/protocol-icons/guac-text.png differ
diff --git a/guacamole/src/main/webapp/images/user-icons/guac-user.png b/guacamole/src/main/webapp/images/user-icons/guac-user.png
new file mode 100644
index 0000000..5270040
Binary files /dev/null and b/guacamole/src/main/webapp/images/user-icons/guac-user.png differ
diff --git a/guacamole/src/main/webapp/index.xhtml b/guacamole/src/main/webapp/index.xhtml
new file mode 100644
index 0000000..87d28b0
--- /dev/null
+++ b/guacamole/src/main/webapp/index.xhtml
@@ -0,0 +1,149 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html>
+
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+ <head>
+ <link rel="icon" type="image/png" href="images/guacamole-logo-64.png"/>
+ <link rel="apple-touch-icon" type="image/png" href="images/guacamole-logo-144.png"/>
+ <link rel="stylesheet" type="text/css" href="styles/ui.css"/>
+ <link rel="stylesheet" type="text/css" href="styles/login.css"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=medium-dpi"/>
+ <title>Guacamole ${project.version}</title>
+ </head>
+
+ <body>
+
+ <div id="login-ui" style="display: none">
+ <div id="login-dialog-middle">
+
+ <div id="login-dialog">
+
+ <p id="login-error"></p>
+
+ <form id="login-form" action="#" method="post">
+
+ <div id="login-fields">
+ <table>
+ <tr>
+ <th>Username</th>
+ <td><input type="text" name="username" id="username" autofocus="autofocus"/></td>
+ </tr>
+ <tr>
+ <th>Password</th>
+ <td><input type="password" name="password" id="password"/></td>
+ </tr>
+ </table>
+
+ <img class="logo" src="images/guac-mono-192.png" alt=""/>
+ </div>
+
+ <div id="buttons">
+ <input type="submit" name="login" id="login" value="Login"/>
+ </div>
+
+ </form>
+ </div>
+
+ </div>
+ </div>
+
+ <!-- Connection list UI -->
+ <div id="connection-list-ui" style="display: none">
+
+ <div id="logout-panel">
+ <button id="manage">Manage</button>
+ <button id="logout">Logout</button>
+ </div>
+
+ <h2>Recent Connections</h2>
+ <div id="recent-connections">
+ <p id="no-recent">No recent connections.</p>
+ </div>
+
+ <h2>All Connections</h2>
+ <div id="all-connections">
+ </div>
+
+ <h2>Clipboard</h2>
+ <div id="clipboardDiv">
+ <p>
+ Text copied/cut within Guacamole will appear here. Changes to the text will affect the remote clipboard, and will be pastable within the remote desktop. Use the textbox below as an interface between the client and server clipboards.
+ </p>
+ <textarea rows="10" cols="40" id="clipboard"></textarea>
+ </div>
+
+ <h2>Settings</h2>
+ <div id="settings">
+
+ <dl>
+ <!-- Auto-fit display -->
+ <dt>
+ <input type="checkbox" id="auto-fit"/>
+ Auto-fit display to browser window
+ </dt>
+ <dd>
+ <p>
+ If checked, remote displays are automatically
+ scaled to exactly fit within the browser window. If
+ unchecked, remote displays are always shown at their
+ natural resolution, even if doing so causes the
+ display to extend beyond the bounds of the window.
+ </p>
+ </dd>
+
+ <!-- Enable/disable sound -->
+ <dt>
+ <input type="checkbox" id="disable-sound"/>
+ Disable sound
+ </dt>
+ <dd>
+ <p>
+ If on a device or network where bandwidth usage must
+ be kept to a minimum, you may wish to check this box
+ and disable sound. This can also be necessary if a
+ device doesn't actually support sound, but claims
+ to, resulting in wasted bandwidth.
+ </p>
+ <p>
+ <strong>Changing this setting will only affect
+ future connections.</strong>
+ </p>
+ </dd>
+ </dl>
+
+ </div>
+
+ </div>
+
+ <div id="version-dialog">
+ Guacamole ${project.version}
+ </div>
+
+ <script type="text/javascript" src="scripts/service.js"></script>
+ <script type="text/javascript" src="scripts/session.js"></script>
+ <script type="text/javascript" src="scripts/history.js"></script>
+ <script type="text/javascript" src="scripts/guac-ui.js"></script>
+ <script type="text/javascript" src="scripts/root-ui.js"></script>
+
+ </body>
+
+</html>
diff --git a/guacamole/src/main/webapp/layouts/en-us-qwerty-mobile.xml b/guacamole/src/main/webapp/layouts/en-us-qwerty-mobile.xml
new file mode 100644
index 0000000..0be8167
--- /dev/null
+++ b/guacamole/src/main/webapp/layouts/en-us-qwerty-mobile.xml
@@ -0,0 +1,312 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE keyboard PUBLIC
+ "-//Guacamole/Guacamole Onscreen Keyboard DTD 0.6.0//EN"
+ "http://guac-dev.org/pub/dtd/guacamole-osk-0.6.0.dtd">
+
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<keyboard lang="en_US" layout="qwerty" size="16.3">
+ <row>
+ <key size="1.5">
+ <cap keysym="0xFF09">Tab</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>q</cap>
+ <cap if="numsym">1</cap>
+ <cap if="shift">Q</cap>
+ <cap if="numsym,shift">q</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>w</cap>
+ <cap if="numsym">2</cap>
+ <cap if="shift">W</cap>
+ <cap if="numsym,shift">w</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>e</cap>
+ <cap if="numsym">3</cap>
+ <cap if="shift">E</cap>
+ <cap if="numsym,shift">e</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>r</cap>
+ <cap if="numsym">4</cap>
+ <cap if="shift">R</cap>
+ <cap if="numsym,shift">r</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>t</cap>
+ <cap if="numsym">5</cap>
+ <cap if="shift">T</cap>
+ <cap if="numsym,shift">t</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>y</cap>
+ <cap if="numsym">6</cap>
+ <cap if="shift">Y</cap>
+ <cap if="numsym,shift">y</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>u</cap>
+ <cap if="numsym">7</cap>
+ <cap if="shift">U</cap>
+ <cap if="numsym,shift">u</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>i</cap>
+ <cap if="numsym">8</cap>
+ <cap if="shift">I</cap>
+ <cap if="numsym,shift">i</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>o</cap>
+ <cap if="numsym">9</cap>
+ <cap if="shift">O</cap>
+ <cap if="numsym,shift">o</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>p</cap>
+ <cap if="numsym">0</cap>
+ <cap if="shift">P</cap>
+ <cap if="numsym,shift">p</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>[</cap>
+ <cap if="shift">{</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>]</cap>
+ <cap if="shift">}</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.5">
+ <cap keysym="0xFF08">Back</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="1.85" class="numsym">
+ <cap modifier="numsym" sticky="true">?123</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>a</cap>
+ <cap if="numsym">#</cap>
+ <cap if="shift">A</cap>
+ <cap if="numsym,shift">a</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>s</cap>
+ <cap if="numsym">$</cap>
+ <cap if="shift">S</cap>
+ <cap if="numsym,shift">s</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>d</cap>
+ <cap if="numsym">%</cap>
+ <cap if="shift">D</cap>
+ <cap if="numsym,shift">d</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>f</cap>
+ <cap if="numsym">&</cap>
+ <cap if="shift">F</cap>
+ <cap if="numsym,shift">f</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>g</cap>
+ <cap if="numsym">*</cap>
+ <cap if="shift">G</cap>
+ <cap if="numsym,shift">g</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>h</cap>
+ <cap if="numsym">-</cap>
+ <cap if="shift">H</cap>
+ <cap if="numsym,shift">h</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>j</cap>
+ <cap if="numsym">+</cap>
+ <cap if="shift">J</cap>
+ <cap if="numsym,shift">j</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>k</cap>
+ <cap if="numsym">(</cap>
+ <cap if="shift">K</cap>
+ <cap if="numsym,shift">k</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>l</cap>
+ <cap if="numsym">)</cap>
+ <cap if="shift">L</cap>
+ <cap if="numsym,shift">l</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>;</cap>
+ <cap if="shift">:</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>'</cap>
+ <cap if="shift">"</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="2.25">
+ <cap keysym="0xFF0D">Enter</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="2.1" class="shift">
+ <cap modifier="shift" keysym="0xFFE1">Shift</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>z</cap>
+ <cap if="numsym"><</cap>
+ <cap if="shift">Z</cap>
+ <cap if="numsym,shift">z</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>x</cap>
+ <cap if="numsym">></cap>
+ <cap if="shift">X</cap>
+ <cap if="numsym,shift">x</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>c</cap>
+ <cap if="numsym">=</cap>
+ <cap if="shift">C</cap>
+ <cap if="numsym,shift">c</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>v</cap>
+ <cap if="numsym">'</cap>
+ <cap if="shift">V</cap>
+ <cap if="numsym,shift">v</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>b</cap>
+ <cap if="numsym">;</cap>
+ <cap if="shift">B</cap>
+ <cap if="numsym,shift">b</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>n</cap>
+ <cap if="numsym">,</cap>
+ <cap if="shift">N</cap>
+ <cap if="numsym,shift">n</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>m</cap>
+ <cap if="numsym">.</cap>
+ <cap if="shift">M</cap>
+ <cap if="numsym,shift">m</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>,</cap>
+ <cap if="numsym">!</cap>
+ <cap if="shift">!</cap>
+ <cap if="numsym,shift">!</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>.</cap>
+ <cap if="numsym">?</cap>
+ <cap if="shift">?</cap>
+ <cap if="numsym,shift">?</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>/</cap>
+ <cap if="shift">?</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="3.1" class="shift">
+ <cap modifier="shift" keysym="0xFFE2">Shift</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="1.6" class="control">
+ <cap modifier="control" keysym="0xFFE3">Ctrl</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="super">
+ <cap modifier="super" keysym="0xFFEB">Super</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="alt">
+ <cap modifier="alt" keysym="0xFFE9">Alt</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="6.1">
+ <cap> </cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="alt">
+ <cap modifier="alt" keysym="0xFFEA">Alt</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6">
+ <cap keysym="0xFF67">Menu</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="control">
+ <cap modifier="control" keysym="0xFFE4">Ctrl</cap>
+ </key>
+ </row>
+</keyboard>
diff --git a/guacamole/src/main/webapp/layouts/en-us-qwerty.xml b/guacamole/src/main/webapp/layouts/en-us-qwerty.xml
new file mode 100644
index 0000000..8a02944
--- /dev/null
+++ b/guacamole/src/main/webapp/layouts/en-us-qwerty.xml
@@ -0,0 +1,496 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE keyboard PUBLIC
+ "-//Guacamole/Guacamole Onscreen Keyboard DTD 0.6.0//EN"
+ "http://guac-dev.org/pub/dtd/guacamole-osk-0.6.0.dtd">
+
+<!--
+ Guacamole - Clientless Remote Desktop
+ Copyright (C) 2010 Michael Jumper
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<keyboard lang="en_US" layout="qwerty" size="22">
+ <row>
+ <key>
+ <cap keysym="0xFF1B">Esc</cap>
+ </key>
+ <gap size="0.8"/>
+ <key>
+ <cap keysym="0xFFBE">F1</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFBF">F2</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC0">F3</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC1">F4</cap>
+ </key>
+ <gap size="0.8"/>
+ <key>
+ <cap keysym="0xFFC2">F5</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC3">F6</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC4">F7</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC5">F8</cap>
+ </key>
+ <gap size="0.8"/>
+ <key>
+ <cap keysym="0xFFC6">F9</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC7">F10</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC8">F11</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFFC9">F12</cap>
+ </key>
+ </row>
+ <row>
+ <gap size="0.25"/>
+ </row>
+ <column>
+ <row>
+ <key>
+ <cap>`</cap>
+ <cap if="shift">~</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>1</cap>
+ <cap if="shift">!</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>2</cap>
+ <cap if="shift">@</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>3</cap>
+ <cap if="shift">#</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>4</cap>
+ <cap if="shift">$</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>5</cap>
+ <cap if="shift">%</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>6</cap>
+ <cap if="shift">^</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>7</cap>
+ <cap if="shift">&</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>8</cap>
+ <cap if="shift">*</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>9</cap>
+ <cap if="shift">(</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>0</cap>
+ <cap if="shift">)</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>-</cap>
+ <cap if="shift">_</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>=</cap>
+ <cap if="shift">+</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="2">
+ <cap keysym="0xFF08">Back</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="1.5">
+ <cap keysym="0xFF09">Tab</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>q</cap>
+ <cap if="caps">Q</cap>
+ <cap if="shift">Q</cap>
+ <cap if="caps,shift">q</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>w</cap>
+ <cap if="caps">W</cap>
+ <cap if="shift">W</cap>
+ <cap if="caps,shift">w</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>e</cap>
+ <cap if="caps">E</cap>
+ <cap if="shift">E</cap>
+ <cap if="caps,shift">e</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>r</cap>
+ <cap if="caps">R</cap>
+ <cap if="shift">R</cap>
+ <cap if="caps,shift">r</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>t</cap>
+ <cap if="caps">T</cap>
+ <cap if="shift">T</cap>
+ <cap if="caps,shift">t</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>y</cap>
+ <cap if="caps">Y</cap>
+ <cap if="shift">Y</cap>
+ <cap if="caps,shift">y</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>u</cap>
+ <cap if="caps">U</cap>
+ <cap if="shift">U</cap>
+ <cap if="caps,shift">u</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>i</cap>
+ <cap if="caps">I</cap>
+ <cap if="shift">I</cap>
+ <cap if="caps,shift">i</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>o</cap>
+ <cap if="caps">O</cap>
+ <cap if="shift">O</cap>
+ <cap if="caps,shift">o</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>p</cap>
+ <cap if="caps">P</cap>
+ <cap if="shift">P</cap>
+ <cap if="caps,shift">p</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>[</cap>
+ <cap if="shift">{</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>]</cap>
+ <cap if="shift">}</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.5">
+ <cap>\</cap>
+ <cap if="shift">|</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="1.85">
+ <cap modifier="caps" keysym="0xFFE5" sticky="true">Caps</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>a</cap>
+ <cap if="caps">A</cap>
+ <cap if="shift">A</cap>
+ <cap if="caps,shift">a</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>s</cap>
+ <cap if="caps">S</cap>
+ <cap if="shift">S</cap>
+ <cap if="caps,shift">s</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>d</cap>
+ <cap if="caps">D</cap>
+ <cap if="shift">D</cap>
+ <cap if="caps,shift">d</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>f</cap>
+ <cap if="caps">F</cap>
+ <cap if="shift">F</cap>
+ <cap if="caps,shift">f</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>g</cap>
+ <cap if="caps">G</cap>
+ <cap if="shift">G</cap>
+ <cap if="caps,shift">g</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>h</cap>
+ <cap if="caps">H</cap>
+ <cap if="shift">H</cap>
+ <cap if="caps,shift">h</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>j</cap>
+ <cap if="caps">J</cap>
+ <cap if="shift">J</cap>
+ <cap if="caps,shift">j</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>k</cap>
+ <cap if="caps">K</cap>
+ <cap if="shift">K</cap>
+ <cap if="caps,shift">k</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>l</cap>
+ <cap if="caps">L</cap>
+ <cap if="shift">L</cap>
+ <cap if="caps,shift">l</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>;</cap>
+ <cap if="shift">:</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>'</cap>
+ <cap if="shift">"</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="2.25">
+ <cap keysym="0xFF0D">Enter</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="2.1" class="shift">
+ <cap modifier="shift" keysym="0xFFE1">Shift</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>z</cap>
+ <cap if="caps">Z</cap>
+ <cap if="shift">Z</cap>
+ <cap if="caps,shift">z</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>x</cap>
+ <cap if="caps">X</cap>
+ <cap if="shift">X</cap>
+ <cap if="caps,shift">x</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>c</cap>
+ <cap if="caps">C</cap>
+ <cap if="shift">C</cap>
+ <cap if="caps,shift">c</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>v</cap>
+ <cap if="caps">V</cap>
+ <cap if="shift">V</cap>
+ <cap if="caps,shift">v</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>b</cap>
+ <cap if="caps">B</cap>
+ <cap if="shift">B</cap>
+ <cap if="caps,shift">b</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>n</cap>
+ <cap if="caps">N</cap>
+ <cap if="shift">N</cap>
+ <cap if="caps,shift">n</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>m</cap>
+ <cap if="caps">M</cap>
+ <cap if="shift">M</cap>
+ <cap if="caps,shift">m</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>,</cap>
+ <cap if="shift"><</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>.</cap>
+ <cap if="shift">></cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap>/</cap>
+ <cap if="shift">?</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="3.1" class="shift">
+ <cap modifier="shift" keysym="0xFFE2">Shift</cap>
+ </key>
+ </row>
+
+ <row><gap size="0.1"/></row>
+
+ <row>
+ <key size="1.6" class="control">
+ <cap modifier="control" keysym="0xFFE3">Ctrl</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="super">
+ <cap modifier="super" keysym="0xFFEB">Super</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="alt">
+ <cap modifier="alt" keysym="0xFFE9">Alt</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="6.1">
+ <cap> </cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="alt">
+ <cap modifier="alt" keysym="0xFFE3">Alt</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="super">
+ <cap modifier="super" keysym="0xFF67">Menu</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.6" class="control">
+ <cap modifier="control" keysym="0xFFE4">Ctrl</cap>
+ </key>
+ </row>
+ </column>
+ <column>
+ <row>
+ <gap size="0.25"/>
+ </row>
+ </column>
+ <column align="center">
+ <row>
+ <key size="1.75">
+ <cap keysym="0xFF63">Ins</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.75">
+ <cap keysym="0xFF50">Home</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.75">
+ <cap keysym="0xFF55">PgUp</cap>
+ </key>
+ </row>
+ <row><gap size="0.1"/></row>
+ <row>
+ <key size="1.75">
+ <cap keysym="0xFFFF">Del</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.75">
+ <cap keysym="0xFF57">End</cap>
+ </key>
+ <gap size="0.1"/>
+ <key size="1.75">
+ <cap keysym="0xFF56">PgDn</cap>
+ </key>
+ </row>
+ <row>
+ <gap/>
+ </row>
+ <row>
+ <key>
+ <cap keysym="0xFF52">↑</cap>
+ </key>
+ </row>
+ <row><gap size="0.1"/></row>
+ <row>
+ <key>
+ <cap keysym="0xFF51">←</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFF54">↓</cap>
+ </key>
+ <gap size="0.1"/>
+ <key>
+ <cap keysym="0xFF53">→</cap>
+ </key>
+ </row>
+ </column>
+</keyboard>
diff --git a/guacamole/src/main/webapp/scripts/admin-ui.js b/guacamole/src/main/webapp/scripts/admin-ui.js
new file mode 100644
index 0000000..4370cf1
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/admin-ui.js
@@ -0,0 +1,1472 @@
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * General set of UI elements and UI-related functions regarding
+ * administration.
+ */
+var GuacAdmin = {
+
+ "containers" : {
+ "connection_list" : document.getElementById("connection-list"),
+ "user_list" : document.getElementById("user-list"),
+ "user_list_buttons" : document.getElementById("user-list-buttons"),
+ },
+
+ "buttons" : {
+ "back" : document.getElementById("back"),
+ "logout" : document.getElementById("logout"),
+ "add_connection" : document.getElementById("add-connection"),
+ "add_connection_group" : document.getElementById("add-connection-group"),
+ "add_user" : document.getElementById("add-user")
+ },
+
+ "fields" : {
+ "username" : document.getElementById("username")
+ },
+
+ "cached_permissions" : null,
+ "cached_protocols" : null,
+ "cached_root_group" : null
+
+};
+
+/**
+ * An arbitrary input field.
+ *
+ * @constructor
+ */
+GuacAdmin.Field = function() {
+
+ /**
+ * Returns the DOM Element representing this field.
+ *
+ * @return {Element} The DOM Element representing this field.
+ */
+ this.getElement = function() {};
+
+ /**
+ * Returns the value of this field.
+ *
+ * @return {String} The value of this field.
+ */
+ this.getValue = function() {};
+
+ /**
+ * Sets the value of this field.
+ *
+ * @param {String} value The value of this field.
+ */
+ this.setValue = function(value) {};
+
+};
+
+
+/**
+ * Simple HTML input field.
+ *
+ * @augments GuacAdmin.Field
+ * @param {String} type The type of HTML field.
+ */
+GuacAdmin.Field._HTML_INPUT = function(type) {
+
+ // Call parent constructor
+ GuacAdmin.Field.apply(this);
+
+ // Create backing element
+ var element = GuacUI.createElement("input");
+ element.setAttribute("type", type);
+
+ this.getValue = function() {
+ return element.value;
+ };
+
+ this.getElement = function() {
+ return element;
+ };
+
+ this.setValue = function(value) {
+ element.value = value;
+ };
+
+};
+
+GuacAdmin.Field._HTML_INPUT.prototype = new GuacAdmin.Field();
+
+
+/**
+ * A basic text field.
+ *
+ * @augments GuacAdmin.Field._HTML_INPUT
+ */
+GuacAdmin.Field.TEXT = function() {
+ GuacAdmin.Field._HTML_INPUT.apply(this, ["text"]);
+};
+
+GuacAdmin.Field.TEXT.prototype = new GuacAdmin.Field._HTML_INPUT();
+
+
+/**
+ * A basic password field.
+ *
+ * @augments GuacAdmin.Field._HTML_INPUT
+ */
+GuacAdmin.Field.PASSWORD = function() {
+ GuacAdmin.Field._HTML_INPUT.apply(this, ["password"]);
+};
+
+GuacAdmin.Field.PASSWORD.prototype = new GuacAdmin.Field._HTML_INPUT();
+
+
+/**
+ * A basic numeric field, leveraging the new HTML5 field types.
+ *
+ * @augments GuacAdmin.Field._HTML_INPUT
+ */
+GuacAdmin.Field.NUMERIC = function() {
+ GuacAdmin.Field._HTML_INPUT.apply(this, ["number"]);
+};
+
+GuacAdmin.Field.NUMERIC.prototype = new GuacAdmin.Field._HTML_INPUT();
+
+
+/**
+ * Simple checkbox.
+ *
+ * @augments GuacAdmin.Field
+ */
+GuacAdmin.Field.CHECKBOX = function(value) {
+
+ // Call parent constructor
+ GuacAdmin.Field.apply(this);
+
+ // Create backing element
+ var element = GuacUI.createElement("input");
+ element.setAttribute("type", "checkbox");
+ element.setAttribute("value", value);
+
+ this.getValue = function() {
+ if (element.checked)
+ return value;
+ else
+ return "";
+ };
+
+ this.getElement = function() {
+ return element;
+ };
+
+ this.setValue = function(new_value) {
+ if (new_value == value)
+ element.checked = true;
+ else
+ element.checked = false;
+ };
+
+};
+
+GuacAdmin.Field.CHECKBOX.prototype = new GuacAdmin.Field();
+
+/**
+ * Enumerated field type.
+ *
+ * @augments GuacAdmin.Field
+ */
+GuacAdmin.Field.ENUM = function(values) {
+
+ // Call parent constructor
+ GuacAdmin.Field.apply(this);
+
+ // Create backing element
+ var element = GuacUI.createElement("select");
+ for (var i=0; i<values.length; i++) {
+ var option = GuacUI.createChildElement(element, "option");
+ option.textContent = values[i].title;
+ option.value = values[i].value;
+ }
+
+ this.getValue = function() {
+ return element.value;
+ };
+
+ this.getElement = function() {
+ return element;
+ };
+
+ this.setValue = function(value) {
+ element.value = value;
+ };
+
+};
+
+GuacAdmin.Field.ENUM.prototype = new GuacAdmin.Field();
+
+
+/**
+ * An arbitrary button.
+ *
+ * @constructor
+ * @param {String} title A human-readable title for the button.
+ */
+GuacAdmin.Button = function(title) {
+
+ /**
+ * A human-readable title describing this button.
+ */
+ this.title = title;
+
+ // Button element
+ var element = GuacUI.createElement("button");
+ element.textContent = title;
+
+ /**
+ * Returns the DOM element associated with this button.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+};
+
+/**
+ * An arbitrary list item with an icon and caption.
+ */
+GuacAdmin.ListItem = function(type, title) {
+
+ // Create connection display elements
+ var element = GuacUI.createElement("div", "list-item");
+ var caption = GuacUI.createChildElement(element, "div", "caption");
+ var icon = GuacUI.createChildElement(caption, "div", "icon");
+ var name = GuacUI.createChildElement(caption, "span", "name");
+ GuacUI.addClass(icon, type);
+
+ // Set name
+ name.textContent = title;
+
+ /**
+ * Returns the DOM element representing this connection.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+};
+
+/*
+ * Set handler for logout
+ */
+
+GuacAdmin.buttons.logout.onclick = function() {
+ window.location.href = "logout";
+};
+
+/*
+ * Set handler for back button
+ */
+
+GuacAdmin.buttons.back.onclick = function() {
+ window.location.href = "index.xhtml";
+};
+
+/**
+ * Returns whether the given object has at least one property.
+ */
+GuacAdmin.hasEntry = function(object) {
+ for (var name in object)
+ return true;
+ return false;
+};
+
+/**
+ * Given a Date, returns a formatted String.
+ *
+ * @param {Date} date The date tor format.
+ * @return {String} A formatted String.
+ */
+GuacAdmin.formatDate = function(date) {
+
+ var month = date.getMonth() + 1;
+ var day = date.getDate();
+ var year = date.getFullYear();
+
+ var hour = date.getHours();
+ var minute = date.getMinutes();
+ var second = date.getSeconds();
+
+ return ("00" + month).slice(-2)
+ + "/" + ("00" + day).slice(-2)
+ + "/" + year
+ + " " + ("00" + hour).slice(-2)
+ + ":" + ("00" + minute).slice(-2)
+ + ":" + ("00" + second).slice(-2);
+
+};
+
+/**
+ * Given a number of seconds, returns a String representing that length
+ * of time in a human-readable format.
+ *
+ * @param {Number} seconds The number of seconds.
+ * @return {String} A human-readable description of the duration specified.
+ */
+GuacAdmin.formatSeconds = function(seconds) {
+
+ function round(value) {
+ return Math.round(value * 10) / 10;
+ }
+
+ if (seconds < 60) return round(seconds) + " seconds";
+ if (seconds < 3600) return round(seconds / 60) + " minutes";
+ if (seconds < 86400) return round(seconds / 3600) + " hours";
+ return round(seconds / 86400) + " days";
+
+};
+
+/**
+ * Currently-defined pager for users, if any.
+ */
+GuacAdmin.userPager = null;
+
+/**
+ * Adds the user with the given name to the displayed user list.
+ */
+GuacAdmin.addUser = function(name, parameters) {
+
+ // Create user list item
+ var item = new GuacAdmin.ListItem("user", name);
+ var item_element = item.getElement();
+ GuacAdmin.userPager.addElement(item_element);
+
+ // When clicked, build and display property form
+ item_element.onclick = function() {
+
+ // Open user editor
+ var user_dialog = new GuacAdmin.UserEditor(name, parameters);
+ document.body.appendChild(user_dialog.getElement());
+
+ };
+
+};
+
+
+/**
+ * User edit dialog which allows editing of the user's password and connection
+ * access level.
+ *
+ * @param {String} name The name of the user to edit.
+ * @param {String} parameters Any parameters to add to service requests for sake
+ * of authentication.
+ */
+GuacAdmin.UserEditor = function(name, parameters) {
+
+ /**
+ * Dialog containing the user editor.
+ */
+ var dialog = new GuacUI.Dialog();
+
+ // Get user permissions
+ var user_perms = GuacamoleService.Permissions.list(name, parameters);
+
+ // Permission deltas
+ var added_perms = new GuacamoleService.PermissionSet();
+ var removed_perms = new GuacamoleService.PermissionSet();
+
+ // Create form base elements
+ var user_header = GuacUI.createChildElement(dialog.getHeader(), "h2");
+ var form_element = GuacUI.createChildElement(dialog.getBody(), "div", "form");
+ var sections = GuacUI.createChildElement(
+ GuacUI.createChildElement(form_element, "div", "settings section"),
+ "dl");
+
+ var field_header = GuacUI.createChildElement(sections, "dt");
+ var field_table = GuacUI.createChildElement(
+ GuacUI.createChildElement(sections, "dd"),
+ "table", "fields section");
+
+ user_header.textContent = name;
+ field_header.textContent = "Properties:";
+
+ // Add password field
+ var password_field = GuacUI.createChildElement(
+ GuacUI.createTabulatedContainer(field_table, "Password:"),
+ "input");
+ password_field.setAttribute("type", "password");
+ password_field.setAttribute("value", "password");
+
+ // Add password re-entry field
+ var reenter_password_field = GuacUI.createChildElement(
+ GuacUI.createTabulatedContainer(field_table, "Re-enter Password:"),
+ "input");
+ reenter_password_field.setAttribute("type", "password");
+ reenter_password_field.setAttribute("value", "password");
+
+ // Update password if changed
+ var password_modified = false;
+ password_field.onchange =
+ reenter_password_field.onchange = function() {
+ password_modified = true;
+ };
+
+ // If administrator, allow manipulation of admin permissions on users
+ if (GuacAdmin.cached_permissions.administer) {
+
+ var permission_header = GuacUI.createChildElement(sections, "dt");
+ var permission_table = GuacUI.createChildElement(
+ GuacUI.createChildElement(sections, "dd"),
+ "table", "permissions section");
+
+ permission_header.textContent = "Permissions:";
+
+ // Add system administration checkbox
+ var is_admin = GuacUI.createChildElement(
+ GuacUI.createTabulatedContainer(permission_table, "Administer system:"),
+ "input");
+ is_admin.setAttribute("type", "checkbox");
+ is_admin.setAttribute("value", "administer");
+
+ // Check if set
+ if (user_perms.administer)
+ is_admin.checked = true;
+
+ // Add create user permission checkbox
+ var create_users = GuacUI.createChildElement(
+ GuacUI.createTabulatedContainer(permission_table, "Create new users:"),
+ "input");
+ create_users.setAttribute("type", "checkbox");
+ create_users.setAttribute("value", "create_user");
+
+ // Check if set
+ if (user_perms.create_user)
+ create_users.checked = true;
+
+ // Add create connection permission checkbox
+ var create_connections = GuacUI.createChildElement(
+ GuacUI.createTabulatedContainer(permission_table, "Create new connections:"),
+ "input");
+ create_connections.setAttribute("type", "checkbox");
+ create_connections.setAttribute("value", "create_connection");
+
+ // Check if set
+ if (user_perms.create_connection)
+ create_connections.checked = true;
+
+ // Add create connection group permission checkbox
+ var create_connection_groups = GuacUI.createChildElement(
+ GuacUI.createTabulatedContainer(permission_table, "Create new connection groups:"),
+ "input");
+ create_connection_groups.setAttribute("type", "checkbox");
+ create_connection_groups.setAttribute("value", "create_connection_group");
+
+ // Check if set
+ if (user_perms.create_connection_group)
+ create_connection_groups.checked = true;
+
+ // Update system permissions when changed
+ is_admin.onclick =
+ create_users.onclick =
+ create_connections.onclick =
+ create_connection_groups.onclick =
+ function() {
+
+ // Update permission deltas for ADDED permission
+ if (this.checked) {
+ added_perms[this.value] = true;
+ removed_perms[this.value] = false;
+ }
+
+ // Update permission deltas for REMOVED permission
+ else {
+ added_perms[this.value] = false;
+ removed_perms[this.value] = true;
+ }
+
+ };
+
+ }
+
+ // If administrable connections/groups exist, list them
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.administer_connection)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.administer_connection_group)) {
+
+ // Add fields for per-connection checkboxes
+ var connections_header = GuacUI.createChildElement(sections, "dt");
+ connections_header.textContent = "Connections:";
+
+ var connections_section = GuacUI.createChildElement(sections, "dd");
+
+ // Construct group view for all readable connections
+ var group_view = new GuacUI.GroupView(GuacAdmin.cached_root_group,
+ GuacUI.GroupView.SHOW_CONNECTIONS | GuacUI.GroupView.MULTISELECT);
+ connections_section.appendChild(group_view.getElement());
+
+ // Update connection permissions when changed
+ group_view.onconnectionchange = function(connection, selected) {
+
+ var id = connection.id;
+
+ // Update permission deltas for ADDED permission
+ if (selected) {
+ added_perms.read_connection[id] = true;
+ if (removed_perms.read_connection[id])
+ delete removed_perms.read_connection[id];
+ }
+
+ // Update permission deltas for REMOVED permission
+ else {
+ removed_perms.read_connection[id] = true;
+ if (added_perms.read_connection[id])
+ delete added_perms.read_connection[id];
+ }
+
+ };
+
+ // Update group permissions when changed
+ group_view.ongroupchange = function(group, selected) {
+
+ var id = group.id;
+
+ // Update permission deltas for ADDED permission
+ if (selected) {
+ added_perms.read_connection_group[id] = true;
+ if (removed_perms.read_connection_group[id])
+ delete removed_perms.read_connection_group[id];
+ }
+
+ // Update permission deltas for REMOVED permission
+ else {
+ removed_perms.read_connection_group[id] = true;
+ if (added_perms.read_connection_group[id])
+ delete added_perms.read_connection_group[id];
+ }
+
+ };
+
+ // Set selectable and selected states based on current permissions
+ for (var conn_id in group_view.connections) {
+
+ // Pre-select connection if readable by chosen user
+ if (conn_id in user_perms.read_connection)
+ group_view.setConnectionValue(conn_id, true);
+
+ // If we lack permissions to admin this connection, disable it
+ if (!GuacAdmin.cached_permissions.administer &&
+ !(conn_id in GuacAdmin.cached_permissions.administer_connection))
+ group_view.setConnectionEnabled(conn_id, false);
+
+ }
+
+ for (var group_id in group_view.groups) {
+
+ // Pre-select connection if readable by chosen user
+ if (group_id in user_perms.read_connection_group)
+ group_view.setGroupValue(group_id, true);
+
+ // If we lack permissions to admin this connection, disable it
+ if (!GuacAdmin.cached_permissions.administer &&
+ !(group_id in GuacAdmin.cached_permissions.administer_connection_group))
+ group_view.setGroupEnabled(group_id, false);
+
+ }
+
+ }
+
+ // Add save button
+ var save_button = GuacUI.createChildElement(dialog.getFooter(), "button");
+ save_button.textContent = "Save";
+ save_button.onclick = function(e) {
+
+ e.stopPropagation();
+
+ try {
+
+ // If password modified, use password given
+ var password;
+ if (password_modified) {
+
+ // Get passwords
+ password = password_field.value;
+ var reentered_password = reenter_password_field.value;
+
+ // Check that passwords match
+ if (password != reentered_password)
+ throw new Error("Passwords do not match.");
+
+ }
+
+ // Otherwise, do not change password
+ else
+ password = null;
+
+ // Save user
+ GuacamoleService.Users.update(name, password, added_perms, removed_perms, parameters);
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ GuacAdmin.reset();
+
+ }
+ catch (e) {
+ alert(e.message);
+ }
+
+ };
+
+ // Add cancel button
+ var cancel_button = GuacUI.createChildElement(dialog.getFooter(), "button");
+ cancel_button.textContent = "Cancel";
+ cancel_button.onclick = function(e) {
+ e.stopPropagation();
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ };
+
+ // Add delete button if permission available
+ if (GuacAdmin.cached_permissions.administer ||
+ name in GuacAdmin.cached_permissions.remove_user) {
+
+ // Create button
+ var delete_button = GuacUI.createChildElement(dialog.getFooter(), "button", "danger");
+ delete_button.textContent = "Delete";
+
+ // Remove selected user when clicked
+ delete_button.onclick = function(e) {
+
+ e.stopPropagation();
+
+ // Delete user upon confirmation
+ if (confirm("Are you sure you want to delete the user \""
+ + name + "\"?")) {
+
+ // Attempt to delete user
+ try {
+ GuacamoleService.Users.remove(name, parameters);
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ GuacAdmin.reset();
+ }
+
+ // Alert on failure
+ catch (e) {
+ alert(e.message);
+ }
+
+ }
+
+ };
+
+ }
+
+ /**
+ * Returns the DOM Element representing this dialog.
+ *
+ * @return {Element} The DOM Element representing this dialog.
+ */
+ this.getElement = function() {
+ return dialog.getElement();
+ };
+
+};
+
+/**
+ * Connection edit dialog which allows editing of the connection parameters.
+ *
+ * @param {GuacamoleService.Connection} connection The connection to edit. This
+ * must be a connection without
+ * an id, if the connection is
+ * to be created.
+ * @param {String} parameters Any parameters to add to service requests for sake
+ * of authentication.
+ */
+GuacAdmin.ConnectionEditor = function(connection, parameters) {
+
+ /**
+ * Dialog containing the user editor.
+ */
+ var dialog = new GuacUI.Dialog();
+
+ var i;
+
+ // Create form base elements
+ var connection_header = GuacUI.createChildElement(dialog.getHeader(), "h2");
+ var form_element = GuacUI.createChildElement(dialog.getBody(), "div", "form");
+
+ var sections = GuacUI.createChildElement(
+ GuacUI.createChildElement(form_element, "div", "settings section"),
+ "dl");
+
+ // Header section
+ var header_table = GuacUI.createChildElement(
+ GuacUI.createChildElement(sections, "dt"),
+ "table", "fields section");
+
+ // Header parameter containers
+ var name_container = GuacUI.createTabulatedContainer(header_table, "Name:");
+ var location_container = GuacUI.createTabulatedContainer(header_table, "Location:");
+ var protocol_container = GuacUI.createTabulatedContainer(header_table, "Protocol:");
+
+ var name_field = GuacUI.createChildElement(name_container, "input");
+ var location = GuacUI.createChildElement(location_container, "div", "location");
+ var protocol_field = GuacUI.createChildElement(protocol_container, "select");
+ name_field.setAttribute("type", "text");
+
+ var location_value = connection.parent;
+ location.textContent = connection.parent.name;
+ location.onclick = function() {
+
+ // Show group selector
+ var group_select = new GuacAdmin.ConnectionGroupSelect(GuacAdmin.cached_root_group);
+ location_container.appendChild(group_select.getElement());
+
+ // Pre-select current value
+ group_select.select(location_value);
+
+ // Update location when chosen
+ group_select.onselect = function(group) {
+ location_value = group;
+ location.textContent = group.name;
+ };
+
+ };
+
+ // Set header
+ name_field.value =
+ connection_header.textContent = connection.name;
+
+ // Associative set of protocols
+ var available_protocols = {};
+
+ // All form fields by parameter name
+ var fields = {};
+
+ // Add protocols
+ for (i=0; i<GuacAdmin.cached_protocols.length; i++) {
+
+ // Get protocol and store in associative set
+ var protocol = GuacAdmin.cached_protocols[i];
+ available_protocols[protocol.name] = protocol;
+
+ // List protocol in select
+ var protocol_title = GuacUI.createChildElement(protocol_field, "option");
+ protocol_title.textContent = protocol.title;
+ protocol_title.value = protocol.name;
+
+ }
+
+ // Parameter section
+ var field_table = GuacUI.createChildElement(
+ GuacUI.createChildElement(sections, "dd"),
+ "table", "fields section");
+
+ // History header
+ var history_header = GuacUI.createChildElement(sections, "dt");
+ history_header.textContent = "Usage History:";
+
+ // If history present, display as table
+ if (connection.history.length > 0) {
+
+ // History section
+ var history_section = GuacUI.createChildElement(sections, "dd");
+ var history_table = GuacUI.createChildElement(history_section,
+ "table", "history section");
+
+ var history_table_header = GuacUI.createChildElement(
+ history_table, "tr");
+
+ GuacUI.createChildElement(history_table_header, "th").textContent =
+ "Username";
+
+ GuacUI.createChildElement(history_table_header, "th").textContent =
+ "Start Time";
+
+ GuacUI.createChildElement(history_table_header, "th").textContent =
+ "Duration";
+
+ // Paginated body of history
+ var history_buttons = GuacUI.createChildElement(history_section, "div",
+ "list-pager-buttons");
+ var history_body = GuacUI.createChildElement(history_table, "tbody");
+ var history_pager = new GuacUI.Pager(history_body);
+
+ // Add history
+ for (i=0; i<connection.history.length; i++) {
+
+ // Get record
+ var record = connection.history[i];
+
+ // Create record elements
+ var row = GuacUI.createElement("tr");
+ var user = GuacUI.createChildElement(row, "td", "username");
+ var start = GuacUI.createChildElement(row, "td", "start");
+ var duration = GuacUI.createChildElement(row, "td", "duration");
+
+ // Display record
+ user.textContent = record.username;
+ start.textContent = GuacAdmin.formatDate(record.start);
+ if (record.duration !== null)
+ duration.textContent = GuacAdmin.formatSeconds(record.duration);
+ else
+ duration.textContent = "Active now";
+
+ // Add record to pager
+ history_pager.addElement(row);
+
+ }
+
+ // Init pager
+ history_pager.setPage(0);
+
+ // Add pager if more than one page
+ if (history_pager.last_page !== 0)
+ history_buttons.appendChild(history_pager.getElement());
+
+ }
+ else
+ GuacUI.createChildElement(
+ GuacUI.createChildElement(sections, "dd"), "p").textContent =
+ "This connection has not yet been used.";
+
+ // Display fields for the given protocol name
+ function setFields(protocol_name) {
+
+ // Clear fields
+ field_table.innerHTML = "";
+
+ // Get protocol
+ var protocol = available_protocols[protocol_name];
+
+ // For each parameter
+ for (var i=0; i<protocol.parameters.length; i++) {
+
+ // Get parameter
+ var parameter = protocol.parameters[i];
+ var name = parameter.name;
+
+ // Create corresponding field
+ var field;
+ switch (parameter.type) {
+
+ // Text field
+ case GuacamoleService.Protocol.Parameter.TEXT:
+ field = new GuacAdmin.Field.TEXT();
+ break;
+
+ // Password field
+ case GuacamoleService.Protocol.Parameter.PASSWORD:
+ field = new GuacAdmin.Field.PASSWORD();
+ break;
+
+ // Numeric field
+ case GuacamoleService.Protocol.Parameter.NUMERIC:
+ field = new GuacAdmin.Field.NUMERIC();
+ break;
+
+ // Checkbox
+ case GuacamoleService.Protocol.Parameter.BOOLEAN:
+ field = new GuacAdmin.Field.CHECKBOX(parameter.value);
+ break;
+
+ // Select field
+ case GuacamoleService.Protocol.Parameter.ENUM:
+ field = new GuacAdmin.Field.ENUM(parameter.options);
+ break;
+
+ default:
+ continue;
+
+ }
+
+ // Create container for field
+ var container =
+ GuacUI.createTabulatedContainer(field_table, parameter.title + ":");
+
+ // Set initial value, if available
+ if (connection.parameters[name])
+ field.setValue(connection.parameters[name]);
+
+ // Add field
+ container.appendChild(field.getElement());
+ fields[name] = field;
+
+ } // end foreach parameter
+
+ }
+
+ // Set initially selected protocol
+ if (connection.protocol) protocol_field.value = connection.protocol;
+ setFields(protocol_field.value);
+
+ protocol_field.onchange = protocol_field.onclick = function() {
+ setFields(this.value);
+ };
+
+ // Add save button
+ var save_button = GuacUI.createChildElement(dialog.getFooter(), "button");
+ save_button.textContent = "Save";
+ save_button.onclick = function(e) {
+
+ e.stopPropagation();
+
+ try {
+
+ // Build connection
+ var updated_connection = new GuacamoleService.Connection(
+ protocol_field.value,
+ connection.id,
+ name_field.value
+ );
+
+ // Populate parameters
+ for (var name in fields) {
+ var field = fields[name];
+ if (field)
+ updated_connection.parameters[name] = field.getValue();
+ }
+
+ // Update connection if it exists
+ if (connection.id) {
+ GuacamoleService.Connections.update(updated_connection, parameters);
+ if (location_value.id !== connection.parent.id)
+ GuacamoleService.Connections.move(updated_connection, location_value, parameters);
+ }
+
+ // Otherwise, create
+ else {
+ updated_connection.parent = location_value;
+ GuacamoleService.Connections.create(updated_connection, parameters);
+ }
+
+ // Hide dialog and reset UI
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ GuacAdmin.reset();
+
+ }
+ catch (e) {
+ alert(e.message);
+ }
+
+ };
+
+ // Add cancel button
+ var cancel_button = GuacUI.createChildElement(dialog.getFooter(), "button");
+ cancel_button.textContent = "Cancel";
+ cancel_button.onclick = function(e) {
+ e.stopPropagation();
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ };
+
+ // Add delete button if permission available
+ if (GuacAdmin.cached_permissions.administer ||
+ connection.id in GuacAdmin.cached_permissions.remove_connection) {
+
+ // Create button
+ var delete_button = GuacUI.createChildElement(dialog.getFooter(), "button", "danger");
+ delete_button.textContent = "Delete";
+
+ // Remove selected connection when clicked
+ delete_button.onclick = function(e) {
+
+ e.stopPropagation();
+
+ // Delete connection upon confirmation
+ if (confirm("Are you sure you want to delete the connection \""
+ + connection.name + "\"?")) {
+
+ // Attempt to delete connection
+ try {
+ GuacamoleService.Connections.remove(connection.id, parameters);
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ GuacAdmin.reset();
+ }
+
+ // Alert on failure
+ catch (e) {
+ alert(e.message);
+ }
+
+ }
+
+ };
+
+ }
+
+ /**
+ * Returns the DOM Element representing this dialog.
+ *
+ * @return {Element} The DOM Element representing this dialog.
+ */
+ this.getElement = function() {
+ return dialog.getElement();
+ };
+
+};
+
+/**
+ * Connection group edit dialog which allows editing of the group parameters.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to edit. This must
+ * be a group without an ID for
+ * group creation.
+ * @param {String} parameters Any parameters to add to service requests for sake
+ * of authentication.
+ */
+GuacAdmin.ConnectionGroupEditor = function(group, parameters) {
+
+ /**
+ * Dialog containing the user editor.
+ */
+ var dialog = new GuacUI.Dialog();
+
+ var i;
+
+ // Create form base elements
+ var group_header = GuacUI.createChildElement(dialog.getHeader(), "h2");
+ var form_element = GuacUI.createChildElement(dialog.getBody(), "div", "form");
+
+ var sections = GuacUI.createChildElement(
+ GuacUI.createChildElement(form_element, "div", "settings section"),
+ "dl");
+
+ // Header section
+ var header_table = GuacUI.createChildElement(
+ GuacUI.createChildElement(sections, "dt"),
+ "table", "fields section");
+
+ // Header parameter containers
+ var name_container = GuacUI.createTabulatedContainer(header_table, "Name:");
+ var location_container = GuacUI.createTabulatedContainer(header_table, "Location:");
+ var type_container = GuacUI.createTabulatedContainer(header_table, "Type:");
+
+ var name_field = GuacUI.createChildElement(name_container, "input");
+ var location = GuacUI.createChildElement(location_container, "div", "location");
+ var type_field = GuacUI.createChildElement(type_container, "select");
+ name_field.setAttribute("type", "text");
+
+ var location_value = group.parent;
+ location.textContent = group.parent.name;
+ location.onclick = function() {
+
+ // Show group selector
+ var group_select = new GuacAdmin.ConnectionGroupSelect(GuacAdmin.cached_root_group);
+ location_container.appendChild(group_select.getElement());
+
+ // Pre-select current value
+ group_select.select(location_value);
+
+ // Update location when chosen
+ group_select.onselect = function(selected_group) {
+
+ // Prevent selecting a situation that would produce a cycle
+ var current = selected_group;
+ while (current !== null) {
+
+ if (current.id === group.id) {
+ alert("Cannot move a group into a subgroup of itself.");
+ return;
+ }
+
+ current = current.parent;
+ }
+
+ location_value = selected_group;
+ location.textContent = selected_group.name;
+ };
+
+ };
+
+ // Set title
+ name_field.value =
+ group_header.textContent = group.name;
+
+ // Organizational type
+ var org_type = GuacUI.createChildElement(type_field, "option");
+ org_type.textContent = "Organizational";
+ org_type.value = "organizational";
+
+ // Balancing type
+ var bal_type = GuacUI.createChildElement(type_field, "option");
+ bal_type.textContent = "Balancing";
+ bal_type.value = "balancing";
+
+ // Read type from group
+ if (group.type === GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL)
+ type_field.value = "organizational";
+ else if (group.type === GuacamoleService.ConnectionGroup.Type.BALANCING)
+ type_field.value = "balancing";
+
+ // Add save button
+ var save_button = GuacUI.createChildElement(dialog.getFooter(), "button");
+ save_button.textContent = "Save";
+ save_button.onclick = function(e) {
+
+ e.stopPropagation();
+
+ try {
+
+ // Parse type
+ var type;
+ if (type_field.value === "organizational")
+ type = GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL;
+ else if (type_field.value === "balancing")
+ type = GuacamoleService.ConnectionGroup.Type.BALANCING;
+
+ // Build group
+ var updated_group = new GuacamoleService.ConnectionGroup(
+ type,
+ group.id,
+ name_field.value
+ );
+
+ // Update group if provided
+ if (group.id) {
+ GuacamoleService.ConnectionGroups.update(updated_group, parameters);
+ if (location_value.id !== group.parent.id)
+ GuacamoleService.ConnectionGroups.move(updated_group, location_value, parameters);
+ }
+
+ // Otherwise, create
+ else {
+ updated_group.parent = location_value;
+ GuacamoleService.ConnectionGroups.create(updated_group, parameters);
+ }
+
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ GuacAdmin.reset();
+
+ }
+ catch (e) {
+ alert(e.message);
+ }
+
+ };
+
+ // Add cancel button
+ var cancel_button = GuacUI.createChildElement(dialog.getFooter(), "button");
+ cancel_button.textContent = "Cancel";
+ cancel_button.onclick = function(e) {
+ e.stopPropagation();
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ };
+
+ // Add delete button if permission available
+ if (GuacAdmin.cached_permissions.administer ||
+ group.id in GuacAdmin.cached_permissions.remove_connection_group) {
+
+ // Create button
+ var delete_button = GuacUI.createChildElement(dialog.getFooter(), "button", "danger");
+ delete_button.textContent = "Delete";
+
+ // Remove selected group when clicked
+ delete_button.onclick = function(e) {
+
+ e.stopPropagation();
+
+ // Delete group upon confirmation
+ if (confirm("Are you sure you want to delete the group \""
+ + group.name + "\"?")) {
+
+ // Attempt to delete group
+ try {
+ GuacamoleService.ConnectionGroups.remove(group.id, parameters);
+ dialog.getElement().parentNode.removeChild(dialog.getElement());
+ GuacAdmin.reset();
+ }
+
+ // Alert on failure
+ catch (e) {
+ alert(e.message);
+ }
+
+ }
+
+ };
+
+ }
+
+ /**
+ * Returns the DOM Element representing this dialog.
+ *
+ * @return {Element} The DOM Element representing this dialog.
+ */
+ this.getElement = function() {
+ return dialog.getElement();
+ };
+
+};
+
+/**
+ * Connection group dialog which allows selection of a single group.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to view.
+ */
+GuacAdmin.ConnectionGroupSelect = function(group) {
+
+ /**
+ * Reference to this group selector.
+ * @private
+ */
+ var group_select = this;
+
+ // Add section with group view
+ var container = GuacUI.createElement("div");
+ var group_outside = GuacUI.createChildElement(container, "div", "overlay");
+ var group_section = GuacUI.createChildElement(container, "div", "dropdown");
+
+ var view = new GuacUI.GroupView(group, GuacUI.GroupView.SHOW_ROOT_GROUP,
+
+ // Only show organizational groups or balancing groups we can administer
+ function(group) {
+
+ if (group.type === GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL)
+ return true;
+
+ return GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.administer_connection_group[group.id];
+
+ });
+
+ group_section.appendChild(view.getElement());
+
+ // Hide when clicked outside
+ group_outside.addEventListener("click", function(e) {
+ e.stopPropagation();
+ container.parentNode.removeChild(container);
+ }, false);
+
+ // Handle select
+ view.ongroupclick = function(group) {
+
+ // Fire event if defined
+ if (group_select.onselect)
+ group_select.onselect(group);
+
+ // Hide dialog
+ container.parentNode.removeChild(container);
+
+ };
+
+ /**
+ * Fired when a group is selected.
+ *
+ * @event
+ * @param {GuacamoleService.ConnectionGroup} group The selected group.
+ */
+ this.onselect = null;
+
+ /**
+ * Returns the DOM Element representing this dialog.
+ *
+ * @return {Element} The DOM Element representing this dialog.
+ */
+ this.getElement = function() {
+ return container;
+ };
+
+ /**
+ * Pre-selects the given group.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to select.
+ */
+ this.select = function(group) {
+ view.expand(group);
+ };
+
+};
+
+GuacAdmin.reset = function() {
+
+ // Get parameters from query string
+ var parameters = window.location.search.substring(1);
+
+ /*
+ * Show admin elements if admin permissions available
+ */
+
+ // Query service for permissions, protocols, and connections
+ GuacAdmin.cached_permissions = GuacamoleService.Permissions.list(null, parameters);
+ GuacAdmin.cached_protocols = GuacamoleService.Protocols.list(parameters);
+ GuacAdmin.cached_root_group = GuacamoleService.Connections.list(parameters);
+
+ // Connection management
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.create_connection
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.update_connection)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.remove_connection)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.administer_connection)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.update_connection_group)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.remove_connection_group)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.administer_connection_group))
+ GuacUI.addClass(document.body, "manage-connections");
+ else
+ GuacUI.removeClass(document.body, "manage-connections");
+
+ // User management
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.create_user
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.update_user)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.remove_user)
+ || GuacAdmin.hasEntry(GuacAdmin.cached_permissions.administer_user))
+ GuacUI.addClass(document.body, "manage-users");
+ else
+ GuacUI.removeClass(document.body, "manage-users");
+
+ // Connection creation
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.create_connection) {
+ GuacUI.addClass(document.body, "add-connections");
+
+ GuacAdmin.buttons.add_connection.onclick = function() {
+
+ // Create stub base connection
+ var connection = new GuacamoleService.Connection(null, null, "New Connection");
+ connection.parent = GuacAdmin.cached_root_group;
+
+ // Open connection creation dialog
+ var connection_dialog = new GuacAdmin.ConnectionEditor(connection, parameters);
+ document.body.appendChild(connection_dialog.getElement());
+
+ };
+
+ }
+
+ // Connection group creation
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.create_connection_group) {
+ GuacUI.addClass(document.body, "add-connection-groups");
+
+ GuacAdmin.buttons.add_connection_group.onclick = function() {
+
+ // Create stub base group
+ var group = new GuacamoleService.ConnectionGroup(
+ GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL, null, "New Group");
+ group.parent = GuacAdmin.cached_root_group;
+
+ // Open group creation dialog
+ var group_dialog = new GuacAdmin.ConnectionGroupEditor(group, parameters);
+ document.body.appendChild(group_dialog.getElement());
+
+ };
+
+ }
+
+ // User creation
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.create_user) {
+ GuacUI.addClass(document.body, "add-users");
+
+ GuacAdmin.buttons.add_user.onclick = function() {
+
+ // Attempt to create user
+ try {
+ GuacamoleService.Users.create(GuacAdmin.fields.username.value, parameters);
+ GuacAdmin.fields.username.value = "";
+ GuacAdmin.reset();
+ }
+
+ // Alert on failure
+ catch (e) {
+ alert(e.message);
+ }
+
+ };
+
+ }
+
+ var i;
+
+ /*
+ * Add readable users.
+ */
+
+ // Get previous page, if any
+ var user_previous_page = 0;
+ if (GuacAdmin.userPager)
+ user_previous_page = GuacAdmin.userPager.current_page;
+
+ // Add new pager
+ GuacAdmin.containers.user_list.innerHTML = "";
+ GuacAdmin.userPager = new GuacUI.Pager(GuacAdmin.containers.user_list);
+
+ // Add users to pager
+ var usernames = GuacamoleService.Users.list(parameters);
+ for (i=0; i<usernames.length; i++) {
+ if (GuacAdmin.cached_permissions.administer
+ || usernames[i] in GuacAdmin.cached_permissions.update_user)
+ GuacAdmin.addUser(usernames[i], parameters);
+ }
+
+ // If more than one page, add navigation buttons
+ GuacAdmin.containers.user_list_buttons.innerHTML = "";
+ if (GuacAdmin.userPager.last_page != 0)
+ GuacAdmin.containers.user_list_buttons.appendChild(GuacAdmin.userPager.getElement());
+
+ // Set starting page
+ GuacAdmin.userPager.setPage(Math.min(GuacAdmin.userPager.last_page,
+ user_previous_page));
+
+ /*
+ * Add readable connections.
+ */
+
+ // Add new group view
+ GuacAdmin.containers.connection_list.innerHTML = "";
+ var group_view = new GuacUI.GroupView(GuacAdmin.cached_root_group, GuacUI.GroupView.SHOW_CONNECTIONS,
+
+ // Show all organizational groups and balancing groups we have admin
+ // for
+ function(group) {
+
+ if (group.type === GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL)
+ return true;
+
+ return GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.administer_connection_group[group.id];
+
+ },
+
+ // Only show connections we can update/administer
+ function(connection) {
+ return GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.update_connection[connection.id]
+ || GuacAdmin.cached_permissions.administer_connection[connection.id];
+ });
+
+ GuacAdmin.containers.connection_list.appendChild(group_view.getElement());
+
+ // Show connection editor when connections are clicked
+ group_view.onconnectionclick = function(connection) {
+ var connection_dialog = new GuacAdmin.ConnectionEditor(connection, parameters);
+ document.body.appendChild(connection_dialog.getElement());
+ };
+
+ // Show group editor when groups are clicked
+ group_view.ongroupclick = function(group) {
+
+ // Only show group editor if we can actually update/admin this group
+ if (GuacAdmin.cached_permissions.administer
+ || GuacAdmin.cached_permissions.update_connection_group[group.id]
+ || GuacAdmin.cached_permissions.administer_connection_group[group.id]) {
+
+ var group_dialog = new GuacAdmin.ConnectionGroupEditor(group, parameters);
+ document.body.appendChild(group_dialog.getElement());
+
+ }
+
+ };
+
+};
+
+// Initial load
+GuacAdmin.reset();
+
diff --git a/guacamole/src/main/webapp/scripts/client-ui.js b/guacamole/src/main/webapp/scripts/client-ui.js
new file mode 100644
index 0000000..ede0e33
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/client-ui.js
@@ -0,0 +1,1046 @@
+
+/**
+ * Client UI root object.
+ */
+GuacUI.Client = {
+
+ /**
+ * Collection of all Guacamole client UI states.
+ */
+ "states": {
+
+ /**
+ * The normal default Guacamole client UI mode
+ */
+ "INTERACTIVE" : 0,
+
+ /**
+ * Same as INTERACTIVE except with visible on-screen keyboard.
+ */
+ "OSK" : 1,
+
+ /**
+ * No on-screen keyboard, but a visible magnifier.
+ */
+ "MAGNIFIER" : 2,
+
+ /**
+ * Arrows and a draggable view.
+ */
+ "PAN" : 3,
+
+ /**
+ * Same as PAN, but with visible native OSK.
+ */
+ "PAN_TYPING" : 4,
+
+ /**
+ * Precursor to PAN_TYPING, like PAN, except does not pan the
+ * screen, but rather hints at how to start typing.
+ */
+ "WAIT_TYPING" : 5
+
+ },
+
+ /* Constants */
+
+ "LONG_PRESS_DETECT_TIMEOUT" : 800, /* milliseconds */
+ "LONG_PRESS_MOVEMENT_THRESHOLD" : 10, /* pixels */
+ "KEYBOARD_AUTO_RESIZE_INTERVAL" : 30, /* milliseconds */
+
+ /* UI Components */
+
+ "viewport" : document.getElementById("viewportClone"),
+ "display" : document.getElementById("display"),
+ "notification_area" : document.getElementById("notificationArea"),
+
+ /* Expected Input Rectangle */
+
+ "expected_input_x" : 0,
+ "expected_input_y" : 0,
+ "expected_input_width" : 1,
+ "expected_input_height" : 1,
+
+ "connectionName" : "Guacamole",
+ "overrideAutoFit" : false,
+ "attachedClient" : null
+
+};
+
+/**
+ * Component which displays a magnified (100% zoomed) client display.
+ *
+ * @constructor
+ * @augments GuacUI.DraggableComponent
+ */
+GuacUI.Client.Magnifier = function() {
+
+ /**
+ * Reference to this magnifier.
+ * @private
+ */
+ var guac_magnifier = this;
+
+ /**
+ * Large background div which will block touch events from reaching the
+ * client while also providing a click target to deactivate the
+ * magnifier.
+ * @private
+ */
+ var magnifier_background = GuacUI.createElement("div", "magnifier-background");
+
+ /**
+ * Container div for the magnifier, providing a clipping rectangle.
+ * @private
+ */
+ var magnifier = GuacUI.createChildElement(magnifier_background,
+ "div", "magnifier");
+
+ /**
+ * Canvas which will contain the static image copy of the display at time
+ * of show.
+ * @private
+ */
+ var magnifier_display = GuacUI.createChildElement(magnifier, "canvas");
+
+ /**
+ * Context of magnifier display.
+ * @private
+ */
+ var magnifier_context = magnifier_display.getContext("2d");
+
+ /*
+ * This component is draggable.
+ */
+ GuacUI.DraggableComponent.apply(this, [magnifier]);
+
+ // Ensure transformations on display originate at 0,0
+ magnifier.style.transformOrigin =
+ magnifier.style.webkitTransformOrigin =
+ magnifier.style.MozTransformOrigin =
+ magnifier.style.OTransformOrigin =
+ magnifier.style.msTransformOrigin =
+ "0 0";
+
+ /*
+ * Reposition magnifier display relative to own position on screen.
+ */
+
+ this.onmove = function(x, y) {
+
+ var width = magnifier.offsetWidth;
+ var height = magnifier.offsetHeight;
+
+ // Update contents relative to new position
+ var clip_x = x
+ / (window.innerWidth - width) * (GuacUI.Client.attachedClient.getWidth() - width);
+ var clip_y = y
+ / (window.innerHeight - height) * (GuacUI.Client.attachedClient.getHeight() - height);
+
+ magnifier_display.style.WebkitTransform =
+ magnifier_display.style.MozTransform =
+ magnifier_display.style.OTransform =
+ magnifier_display.style.msTransform =
+ magnifier_display.style.transform = "translate("
+ + (-clip_x) + "px, " + (-clip_y) + "px)";
+
+ /* Update expected input rectangle */
+ GuacUI.Client.expected_input_x = clip_x;
+ GuacUI.Client.expected_input_y = clip_y;
+ GuacUI.Client.expected_input_width = width;
+ GuacUI.Client.expected_input_height = height;
+
+ };
+
+ /*
+ * Copy display and add self to body on show.
+ */
+
+ this.show = function() {
+
+ // Copy displayed image
+ magnifier_display.width = GuacUI.Client.attachedClient.getWidth();
+ magnifier_display.height = GuacUI.Client.attachedClient.getHeight();
+ magnifier_context.drawImage(GuacUI.Client.attachedClient.flatten(), 0, 0);
+
+ // Show magnifier container
+ document.body.appendChild(magnifier_background);
+
+ };
+
+ /*
+ * Remove self from body on hide.
+ */
+
+ this.hide = function() {
+
+ // Hide magnifier container
+ document.body.removeChild(magnifier_background);
+
+ };
+
+ /*
+ * If the user clicks on the background, switch to INTERACTIVE mode.
+ */
+
+ magnifier_background.addEventListener("click", function() {
+ GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
+ }, true);
+
+ /*
+ * If the user clicks on the magnifier, switch to PAN_TYPING mode.
+ */
+
+ magnifier.addEventListener("click", function(e) {
+ GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
+ e.stopPropagation();
+ }, true);
+
+};
+
+/*
+ * We inherit from GuacUI.DraggableComponent.
+ */
+GuacUI.Client.Magnifier.prototype = new GuacUI.DraggableComponent();
+
+GuacUI.StateManager.registerComponent(
+ new GuacUI.Client.Magnifier(),
+ GuacUI.Client.states.MAGNIFIER
+);
+
+/**
+ * Zoomed Display, a pseudo-component.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.Client.ZoomedDisplay = function() {
+
+ this.show = function() {
+ GuacUI.Client.overrideAutoFit = true;
+ GuacUI.Client.updateDisplayScale();
+ };
+
+ this.hide = function() {
+ GuacUI.Client.overrideAutoFit = false;
+ GuacUI.Client.updateDisplayScale();
+ };
+
+};
+
+GuacUI.Client.ZoomedDisplay.prototype = new GuacUI.Component();
+
+/*
+ * Zoom the main display during PAN and PAN_TYPING modes.
+ */
+
+GuacUI.StateManager.registerComponent(
+ new GuacUI.Client.ZoomedDisplay(),
+ GuacUI.Client.states.PAN,
+ GuacUI.Client.states.PAN_TYPING
+);
+
+/**
+ * Type overlay UI. This component functions to provide a means of activating
+ * the keyboard, when neither panning nor magnification make sense.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.Client.TypeOverlay = function() {
+
+ /**
+ * Overlay which will provide the means of scrolling the screen.
+ */
+ var type_overlay = GuacUI.createElement("div", "type-overlay");
+
+ /*
+ * Add exit button
+ */
+
+ var start = GuacUI.createChildElement(type_overlay, "p", "hint");
+ start.textContent = "Tap here to type, or tap the screen to cancel.";
+
+ // Begin typing when user clicks hint
+ start.addEventListener("click", function(e) {
+ GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
+ e.stopPropagation();
+ }, false);
+
+ this.show = function() {
+ document.body.appendChild(type_overlay);
+ };
+
+ this.hide = function() {
+ document.body.removeChild(type_overlay);
+ };
+
+ /*
+ * Cancel when user taps screen
+ */
+
+ type_overlay.addEventListener("click", function(e) {
+ GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
+ e.stopPropagation();
+ }, false);
+
+};
+
+GuacUI.Client.TypeOverlay.prototype = new GuacUI.Component();
+
+/*
+ * Show the type overlay during WAIT_TYPING mode only
+ */
+
+GuacUI.StateManager.registerComponent(
+ new GuacUI.Client.TypeOverlay(),
+ GuacUI.Client.states.WAIT_TYPING
+);
+
+/**
+ * Pan overlay UI. This component functions to receive touch events and
+ * translate them into scrolling of the main UI.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.Client.PanOverlay = function() {
+
+ /**
+ * Overlay which will provide the means of scrolling the screen.
+ */
+ var pan_overlay = GuacUI.createElement("div", "pan-overlay");
+
+ /*
+ * Add arrows
+ */
+
+ GuacUI.createChildElement(pan_overlay, "div", "indicator up");
+ GuacUI.createChildElement(pan_overlay, "div", "indicator down");
+ GuacUI.createChildElement(pan_overlay, "div", "indicator right");
+ GuacUI.createChildElement(pan_overlay, "div", "indicator left");
+
+ /*
+ * Add exit button
+ */
+
+ var back = GuacUI.createChildElement(pan_overlay, "p", "hint");
+ back.textContent = "Tap here to exit panning mode";
+
+ // Return to interactive when back is clicked
+ back.addEventListener("click", function() {
+ GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
+ }, false);
+
+ this.show = function() {
+ document.body.appendChild(pan_overlay);
+ };
+
+ this.hide = function() {
+ document.body.removeChild(pan_overlay);
+ };
+
+ /*
+ * Transition to PAN_TYPING when the user taps on the overlay.
+ */
+
+ pan_overlay.addEventListener("click", function(e) {
+ GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
+ e.stopPropagation();
+ }, true);
+
+};
+
+GuacUI.Client.PanOverlay.prototype = new GuacUI.Component();
+
+/*
+ * Show the pan overlay during PAN or PAN_TYPING modes.
+ */
+
+GuacUI.StateManager.registerComponent(
+ new GuacUI.Client.PanOverlay(),
+ GuacUI.Client.states.PAN,
+ GuacUI.Client.states.PAN_TYPING
+);
+
+/**
+ * Native Keyboard. This component uses a hidden textarea field to show the
+ * platforms native on-screen keyboard (if any) or otherwise enable typing,
+ * should the platform require a text field with focus for keyboard events to
+ * register.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.Client.NativeKeyboard = function() {
+
+ /**
+ * Event target. This is a hidden textarea element which will receive
+ * key events.
+ * @private
+ */
+ var eventTarget = GuacUI.createElement("textarea", "event-target");
+ eventTarget.setAttribute("autocorrect", "off");
+ eventTarget.setAttribute("autocapitalize", "off");
+
+ this.show = function() {
+
+ // Move to location of expected input
+ eventTarget.style.left = GuacUI.Client.expected_input_x + "px";
+ eventTarget.style.top = GuacUI.Client.expected_input_y + "px";
+ eventTarget.style.width = GuacUI.Client.expected_input_width + "px";
+ eventTarget.style.height = GuacUI.Client.expected_input_height + "px";
+
+ // Show and focus target
+ document.body.appendChild(eventTarget);
+ eventTarget.focus();
+
+ };
+
+ this.hide = function() {
+
+ // Hide and blur target
+ eventTarget.blur();
+ document.body.removeChild(eventTarget);
+
+ };
+
+ /*
+ * Automatically switch to INTERACTIVE mode after target loses focus
+ */
+
+ eventTarget.addEventListener("blur", function() {
+ GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
+ }, false);
+
+};
+
+GuacUI.Client.NativeKeyboard.prototype = new GuacUI.Component();
+
+/*
+ * Show native keyboard during PAN_TYPING mode only.
+ */
+
+GuacUI.StateManager.registerComponent(
+ new GuacUI.Client.NativeKeyboard(),
+ GuacUI.Client.states.PAN_TYPING
+);
+
+/**
+ * On-screen Keyboard. This component provides a clickable/touchable keyboard
+ * which sends key events to the Guacamole client.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.Client.OnScreenKeyboard = function() {
+
+ /**
+ * Event target. This is a hidden textarea element which will receive
+ * key events.
+ * @private
+ */
+ var keyboard_container = GuacUI.createElement("div", "keyboard-container");
+
+ var keyboard_resize_interval = null;
+
+ // On-screen keyboard
+ var keyboard = new Guacamole.OnScreenKeyboard("layouts/en-us-qwerty.xml");
+ keyboard_container.appendChild(keyboard.getElement());
+
+ var last_keyboard_width = 0;
+
+ // Function for automatically updating keyboard size
+ function updateKeyboardSize() {
+ var currentSize = keyboard.getElement().offsetWidth;
+ if (last_keyboard_width != currentSize) {
+ keyboard.resize(currentSize);
+ last_keyboard_width = currentSize;
+ }
+ }
+
+ keyboard.onkeydown = function(keysym) {
+ GuacUI.Client.attachedClient.sendKeyEvent(1, keysym);
+ };
+
+ keyboard.onkeyup = function(keysym) {
+ GuacUI.Client.attachedClient.sendKeyEvent(0, keysym);
+ };
+
+
+ this.show = function() {
+
+ // Show keyboard
+ document.body.appendChild(keyboard_container);
+
+ // Start periodic update of keyboard size
+ keyboard_resize_interval = window.setInterval(
+ updateKeyboardSize,
+ GuacUI.Client.KEYBOARD_AUTO_RESIZE_INTERVAL);
+
+ // Resize on window resize
+ window.addEventListener("resize", updateKeyboardSize, true);
+
+ // Initialize size
+ updateKeyboardSize();
+
+ };
+
+ this.hide = function() {
+
+ // Hide keyboard
+ document.body.removeChild(keyboard_container);
+ window.clearInterval(keyboard_resize_interval);
+ window.removeEventListener("resize", updateKeyboardSize, true);
+
+ };
+
+};
+
+GuacUI.Client.OnScreenKeyboard.prototype = new GuacUI.Component();
+
+/*
+ * Show on-screen keyboard during OSK mode only.
+ */
+
+GuacUI.StateManager.registerComponent(
+ new GuacUI.Client.OnScreenKeyboard(),
+ GuacUI.Client.states.OSK
+);
+
+
+/*
+ * Set initial state
+ */
+
+GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
+
+/**
+ * Modal status display. Displays a message to the user, covering the entire
+ * screen.
+ *
+ * Normally, this should only be used when user interaction with other
+ * components is impossible.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.Client.ModalStatus = function(text, classname) {
+
+ // Create element hierarchy
+ var outer = GuacUI.createElement("div", "dialogOuter");
+ var middle = GuacUI.createChildElement(outer, "div", "dialogMiddle");
+ var dialog = GuacUI.createChildElement(middle, "div", "dialog");
+ var status = GuacUI.createChildElement(dialog, "p", "status");
+
+ // Set classname if given
+ if (classname)
+ GuacUI.addClass(outer, classname);
+
+ // Set status text
+ status.textContent = text;
+
+ this.show = function() {
+ document.body.appendChild(outer);
+ };
+
+ this.hide = function() {
+ document.body.removeChild(outer);
+ };
+
+};
+
+GuacUI.Client.ModalStatus.prototype = new GuacUI.Component();
+
+/**
+ * Flattens the attached Guacamole.Client, storing the result within the
+ * connection history.
+ */
+GuacUI.Client.updateThumbnail = function() {
+
+ // Get screenshot
+ var canvas = GuacUI.Client.attachedClient.flatten();
+
+ // Calculate scale of thumbnail (max 320x240, max zoom 100%)
+ var scale = Math.min(
+ 320 / canvas.width,
+ 240 / canvas.height,
+ 1
+ );
+
+ // Create thumbnail canvas
+ var thumbnail = document.createElement("canvas");
+ thumbnail.width = canvas.width*scale;
+ thumbnail.height = canvas.height*scale;
+
+ // Scale screenshot to thumbnail
+ var context = thumbnail.getContext("2d");
+ context.drawImage(canvas,
+ 0, 0, canvas.width, canvas.height,
+ 0, 0, thumbnail.width, thumbnail.height
+ );
+
+ // Save thumbnail to history
+ var id = decodeURIComponent(window.location.search.substring(4));
+ GuacamoleHistory.update(id, thumbnail.toDataURL());
+
+};
+
+/**
+ * Updates the scale of the attached Guacamole.Client based on current window
+ * size and "auto-fit" setting.
+ */
+GuacUI.Client.updateDisplayScale = function() {
+
+ // Currently attacched client
+ var guac = GuacUI.Client.attachedClient;
+
+ // If auto-fit is enabled, scale display
+ if (!GuacUI.Client.overrideAutoFit
+ && GuacUI.sessionState.getProperty("auto-fit")) {
+
+ // Calculate scale to fit screen
+ var fit_scale = Math.min(
+ window.innerWidth / guac.getWidth(),
+ window.innerHeight / guac.getHeight()
+ );
+
+ // Scale client
+ if (fit_scale != guac.getScale())
+ guac.scale(fit_scale);
+
+ }
+
+ // Otherwise, scale to 100%
+ else if (guac.getScale() != 1.0)
+ guac.scale(1.0);
+
+};
+
+/**
+ * Updates the document title based on the connection name.
+ */
+GuacUI.Client.updateTitle = function () {
+
+ if (GuacUI.Client.titlePrefix)
+ document.title = GuacUI.Client.titlePrefix + " " + GuacUI.Client.connectionName;
+ else
+ document.title = GuacUI.Client.connectionName;
+
+};
+
+/**
+ * Hides the currently-visible status overlay, if any.
+ */
+GuacUI.Client.hideStatus = function() {
+ if (GuacUI.Client.visibleStatus)
+ GuacUI.Client.visibleStatus.hide();
+ GuacUI.Client.visibleStatus = null;
+};
+
+/**
+ * Displays a status overlay with the given text.
+ */
+GuacUI.Client.showStatus = function(status) {
+ GuacUI.Client.hideStatus();
+
+ GuacUI.Client.visibleStatus = new GuacUI.Client.ModalStatus(status);
+ GuacUI.Client.visibleStatus.show();
+};
+
+/**
+ * Displays an error status overlay with the given text.
+ */
+GuacUI.Client.showError = function(status) {
+ GuacUI.Client.hideStatus();
+
+ GuacUI.Client.visibleStatus =
+ new GuacUI.Client.ModalStatus(status, "guac-error");
+ GuacUI.Client.visibleStatus.show();
+}
+
+/**
+ * Attaches a Guacamole.Client to the client UI, such that Guacamole events
+ * affect the UI, and local events affect the Guacamole.Client.
+ *
+ * @param {Guacamole.Client} guac The Guacamole.Client to attach to the UI.
+ */
+GuacUI.Client.attach = function(guac) {
+
+ // Store attached client
+ GuacUI.Client.attachedClient = guac;
+
+ // Get display element
+ var guac_display = guac.getDisplay();
+
+ /*
+ * Update the scale of the display when the client display size changes.
+ */
+
+ guac.onresize = function(width, height) {
+ GuacUI.Client.updateDisplayScale();
+ }
+
+ /*
+ * Update UI when the state of the Guacamole.Client changes.
+ */
+
+ guac.onstatechange = function(clientState) {
+
+ switch (clientState) {
+
+ // Idle
+ case 0:
+ GuacUI.Client.showStatus("Idle.");
+ GuacUI.Client.titlePrefix = "[Idle]";
+ break;
+
+ // Connecting
+ case 1:
+ GuacUI.Client.showStatus("Connecting...");
+ GuacUI.Client.titlePrefix = "[Connecting...]";
+ break;
+
+ // Connected + waiting
+ case 2:
+ GuacUI.Client.showStatus("Connected, waiting for first update...");
+ GuacUI.Client.titlePrefix = "[Waiting...]";
+ break;
+
+ // Connected
+ case 3:
+
+ GuacUI.Client.hideStatus();
+ GuacUI.Client.titlePrefix = null;
+
+ // Update clipboard with current data
+ if (GuacUI.sessionState.getProperty("clipboard"))
+ guac.setClipboard(GuacUI.sessionState.getProperty("clipboard"));
+
+ break;
+
+ // Disconnecting
+ case 4:
+ GuacUI.Client.showStatus("Disconnecting...");
+ GuacUI.Client.titlePrefix = "[Disconnecting...]";
+ break;
+
+ // Disconnected
+ case 5:
+ GuacUI.Client.showStatus("Disconnected.");
+ GuacUI.Client.titlePrefix = "[Disconnected]";
+ break;
+
+ // Unknown status code
+ default:
+ GuacUI.Client.showStatus("[UNKNOWN STATUS]");
+
+ }
+
+ GuacUI.Client.updateTitle();
+
+ };
+
+ /*
+ * Change UI to reflect the connection name
+ */
+
+ guac.onname = function(name) {
+ GuacUI.Client.connectionName = name;
+ GuacUI.Client.updateTitle();
+ };
+
+ /*
+ * Disconnect and display an error message when the Guacamole.Client
+ * receives an error.
+ */
+
+ guac.onerror = function(error) {
+
+ // Disconnect, if connected
+ guac.disconnect();
+
+ // Display error message
+ GuacUI.Client.showError(error);
+
+ };
+
+ // Server copy handler
+ guac.onclipboard = function(data) {
+ GuacUI.sessionState.setProperty("clipboard", data);
+ };
+
+ /*
+ * Prompt to download file when file received.
+ */
+
+ function getSizeString(bytes) {
+
+ if (bytes > 1000000000)
+ return (bytes / 1000000000).toFixed(1) + " GB";
+
+ else if (bytes > 1000000)
+ return (bytes / 1000000).toFixed(1) + " MB";
+
+ else if (bytes > 1000)
+ return (bytes / 1000).toFixed(1) + " KB";
+
+ else
+ return bytes + " B";
+
+ }
+
+ guac.onblob = function(blob) {
+
+ var download = new GuacUI.Download(blob.name);
+ download.updateProgress(getSizeString(0));
+
+ GuacUI.Client.notification_area.appendChild(download.getElement());
+
+ // Update progress as data is received
+ blob.ondata = function() {
+ download.updateProgress(getSizeString(blob.getLength()));
+ };
+
+ // When complete, prompt for download
+ blob.oncomplete = function() {
+
+ download.ondownload = function() {
+ saveAs(blob.getBlob(), blob.name);
+ };
+
+ download.complete();
+
+ };
+
+ // When close clicked, remove from notification area
+ download.onclose = function() {
+ GuacUI.Client.notification_area.removeChild(download.getElement());
+ };
+
+ };
+
+ /*
+ * Do nothing when the display element is clicked on.
+ */
+
+ guac_display.onclick = function(e) {
+ e.preventDefault();
+ return false;
+ };
+
+ /*
+ * Handle mouse and touch events relative to the display element.
+ */
+
+ // Mouse
+ var mouse = new Guacamole.Mouse(guac_display);
+ var touch = new Guacamole.Mouse.Touchpad(guac_display);
+ touch.onmousedown = touch.onmouseup = touch.onmousemove =
+ mouse.onmousedown = mouse.onmouseup = mouse.onmousemove =
+ function(mouseState) {
+
+ // Determine mouse position within view
+ var mouse_view_x = mouseState.x + guac_display.offsetLeft - window.pageXOffset;
+ var mouse_view_y = mouseState.y + guac_display.offsetTop - window.pageYOffset;
+
+ // Determine viewport dimensioins
+ var view_width = GuacUI.Client.viewport.offsetWidth;
+ var view_height = GuacUI.Client.viewport.offsetHeight;
+
+ // Determine scroll amounts based on mouse position relative to document
+
+ var scroll_amount_x;
+ if (mouse_view_x > view_width)
+ scroll_amount_x = mouse_view_x - view_width;
+ else if (mouse_view_x < 0)
+ scroll_amount_x = mouse_view_x;
+ else
+ scroll_amount_x = 0;
+
+ var scroll_amount_y;
+ if (mouse_view_y > view_height)
+ scroll_amount_y = mouse_view_y - view_height;
+ else if (mouse_view_y < 0)
+ scroll_amount_y = mouse_view_y;
+ else
+ scroll_amount_y = 0;
+
+ // Scroll (if necessary) to keep mouse on screen.
+ window.scrollBy(scroll_amount_x, scroll_amount_y);
+
+ // Scale event by current scale
+ var scaledState = new Guacamole.Mouse.State(
+ mouseState.x / guac.getScale(),
+ mouseState.y / guac.getScale(),
+ mouseState.left,
+ mouseState.middle,
+ mouseState.right,
+ mouseState.up,
+ mouseState.down);
+
+ // Send mouse event
+ guac.sendMouseState(scaledState);
+
+ };
+
+ /*
+ * Route document-level keyboard events to the client.
+ */
+
+
+ var keyboard = new Guacamole.Keyboard(document);
+ var show_keyboard_gesture_possible = true;
+
+ keyboard.onkeydown = function (keysym) {
+ guac.sendKeyEvent(1, keysym);
+
+ // If key is NOT one of the expected keys, gesture not possible
+ if (keysym != 0xFFE3 && keysym != 0xFFE9 && keysym != 0xFFE1)
+ show_keyboard_gesture_possible = false;
+
+ };
+
+ keyboard.onkeyup = function (keysym) {
+ guac.sendKeyEvent(0, keysym);
+
+ // If lifting up on shift, toggle keyboard if rest of gesture
+ // conditions satisfied
+ if (show_keyboard_gesture_possible && keysym == 0xFFE1) {
+ if (keyboard.pressed[0xFFE3] && keyboard.pressed[0xFFE9]) {
+
+ // If in INTERACTIVE mode, switch to OSK
+ if (GuacUI.StateManager.getState() == GuacUI.Client.states.INTERACTIVE)
+ GuacUI.StateManager.setState(GuacUI.Client.states.OSK);
+
+ // If in OSK mode, switch to INTERACTIVE
+ else if (GuacUI.StateManager.getState() == GuacUI.Client.states.OSK)
+ GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
+
+ }
+ }
+
+ // Detect if no keys are pressed
+ var reset_gesture = true;
+ for (var pressed in keyboard.pressed) {
+ reset_gesture = false;
+ break;
+ }
+
+ // Reset gesture state if possible
+ if (reset_gesture)
+ show_keyboard_gesture_possible = true;
+
+ };
+
+ var thumbnail_update_interval = null;
+
+ window.onblur = function() {
+
+ // Regularly update screenshot if window not visible
+ if (!thumbnail_update_interval)
+ thumbnail_update_interval =
+ window.setInterval(GuacUI.Client.updateThumbnail, 1000);
+
+ };
+
+ window.onfocus = function() {
+ if (thumbnail_update_interval) {
+ window.clearInterval(thumbnail_update_interval);
+ thumbnail_update_interval = null;
+ }
+ };
+
+ /*
+ * Disconnect and update thumbnail on close
+ */
+ window.onunload = function() {
+
+ GuacUI.Client.updateThumbnail();
+ guac.disconnect();
+
+ };
+
+ /*
+ * Send size events on resize
+ */
+ window.onresize = function() {
+
+ guac.sendSize(window.innerWidth, window.innerHeight);
+ GuacUI.Client.updateDisplayScale();
+
+ };
+
+ GuacUI.sessionState.onchange = function(old_state, new_state, name) {
+ if (name == "clipboard")
+ guac.setClipboard(new_state[name]);
+ else if (name == "auto-fit")
+ GuacUI.Client.updateDisplayScale();
+ };
+
+ var long_press_start_x = 0;
+ var long_press_start_y = 0;
+ var longPressTimeout = null;
+
+ GuacUI.Client.startLongPressDetect = function() {
+
+ if (!longPressTimeout) {
+
+ longPressTimeout = window.setTimeout(function() {
+ longPressTimeout = null;
+
+ // If screen shrunken, show magnifier
+ if (GuacUI.Client.attachedClient.getScale() < 1.0)
+ GuacUI.StateManager.setState(GuacUI.Client.states.MAGNIFIER);
+
+ // Otherwise, if screen too big to fit, use panning mode
+ else if (
+ GuacUI.Client.attachedClient.getWidth() > window.innerWidth
+ || GuacUI.Client.attachedClient.getHeight() > window.innerHeight
+ )
+ GuacUI.StateManager.setState(GuacUI.Client.states.PAN);
+
+ // Otherwise, just show a hint
+ else
+ GuacUI.StateManager.setState(GuacUI.Client.states.WAIT_TYPING);
+ }, GuacUI.Client.LONG_PRESS_DETECT_TIMEOUT);
+
+ }
+ };
+
+ GuacUI.Client.stopLongPressDetect = function() {
+ window.clearTimeout(longPressTimeout);
+ longPressTimeout = null;
+ };
+
+ // Detect long-press at bottom of screen
+ GuacUI.Client.display.addEventListener('touchstart', function(e) {
+
+ // Record touch location
+ if (e.touches.length == 1) {
+ var touch = e.touches[0];
+ long_press_start_x = touch.screenX;
+ long_press_start_y = touch.screenY;
+ }
+
+ // Start detection
+ GuacUI.Client.startLongPressDetect();
+
+ }, true);
+
+ // Stop detection if touch moves significantly
+ GuacUI.Client.display.addEventListener('touchmove', function(e) {
+
+ // If touch distance from start exceeds threshold, cancel long press
+ var touch = e.touches[0];
+ if (Math.abs(touch.screenX - long_press_start_x) >= GuacUI.Client.LONG_PRESS_MOVEMENT_THRESHOLD
+ || Math.abs(touch.screenY - long_press_start_y) >= GuacUI.Client.LONG_PRESS_MOVEMENT_THRESHOLD)
+ GuacUI.Client.stopLongPressDetect();
+
+ }, true);
+
+ // Stop detection if press stops
+ GuacUI.Client.display.addEventListener('touchend', GuacUI.Client.stopLongPressDetect, true);
+
+};
+
diff --git a/guacamole/src/main/webapp/scripts/guac-ui.js b/guacamole/src/main/webapp/scripts/guac-ui.js
new file mode 100644
index 0000000..d43a9e4
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/guac-ui.js
@@ -0,0 +1,1425 @@
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Main Guacamole UI namespace.
+ * @namespace
+ */
+var GuacUI = GuacUI || {};
+
+/**
+ * Current session state, including settings.
+ */
+GuacUI.sessionState = new GuacamoleSessionState();
+
+/**
+ * Creates a new element having the given tagname and CSS class.
+ */
+GuacUI.createElement = function(tagname, classname) {
+ var new_element = document.createElement(tagname);
+ if (classname) new_element.className = classname;
+ return new_element;
+};
+
+/**
+ * Creates a new element having the given tagname, CSS class, and specified
+ * parent element.
+ */
+GuacUI.createChildElement = function(parent, tagname, classname) {
+ var element = GuacUI.createElement(tagname, classname);
+ parent.appendChild(element);
+ return element;
+};
+
+/**
+ * Creates a new row within the given table having a single header cell
+ * with the given title, and a single value cell. The value cell is returned.
+ */
+GuacUI.createTabulatedContainer = function(table, title) {
+
+ // Create elements
+ var row = GuacUI.createChildElement(table, "tr");
+ var header = GuacUI.createChildElement(row, "th");
+ var cell = GuacUI.createChildElement(row, "td");
+
+ // Set title, return cell
+ header.textContent = title;
+ return cell;
+
+};
+
+/**
+ * Adds the given CSS class to the given element.
+ */
+GuacUI.addClass = function(element, classname) {
+
+ // If supported, use native classlist for addClass()
+ if (Node.classlist)
+ element.classList.add(classname);
+
+ // Otherwise, simply add new class via string manipulation
+ else
+ element.className += " " + classname;
+
+};
+
+/**
+ * Removes the given CSS class from the given element.
+ */
+GuacUI.removeClass = function(element, classname) {
+
+ // If supported, use native classlist for removeClass()
+ if (Node.classlist)
+ element.classList.remove(classname);
+
+ // Otherwise, remove class via string manipulation
+ else {
+
+ // Filter out classes with given name
+ element.className = element.className.replace(/([^ ]+)[ ]*/g,
+ function(match, testClassname, spaces, offset, string) {
+
+ // If same class, remove
+ if (testClassname == classname)
+ return "";
+
+ // Otherwise, allow
+ return match;
+
+ }
+ );
+
+ } // end if no classlist support
+
+};
+
+/**
+ * Opens the connection group having the given ID in a new tab/window.
+ *
+ * @param {String} id The ID of the connection group to open.
+ * @param {String} parameters Any parameters that should be added to the URL,
+ * for sake of authentication.
+ */
+GuacUI.openConnectionGroup = function(id, parameters) {
+ GuacUI.openObject("g/" + id, parameters);
+};
+
+/**
+ * Opens the connection having the given ID in a new tab/window.
+ *
+ * @param {String} id The ID of the connection to open.
+ * @param {String} parameters Any parameters that should be added to the URL,
+ * for sake of authentication.
+ */
+GuacUI.openConnection = function(id, parameters) {
+ GuacUI.openObject("c/" + id, parameters);
+};
+
+/**
+ * Opens the object having the given ID in a new tab/window. The ID must
+ * include the relevant prefix.
+ *
+ * @param {String} id The ID of the object to open, including prefix.
+ * @param {String} parameters Any parameters that should be added to the URL,
+ * for sake of authentication.
+ */
+GuacUI.openObject = function(id, parameters) {
+
+ // Get URL
+ var url = "client.xhtml?id=" + encodeURIComponent(id);
+
+ // Add parameters, if given
+ if (parameters)
+ url += "&" + parameters;
+
+ // Attempt to focus existing window
+ var current = window.open(null, id);
+
+ // If window did not already exist, set up as
+ // Guacamole client
+ if (!current.GuacUI)
+ window.open(url, id);
+
+};
+
+/**
+ * Object describing the UI's level of audio support. If the user has request
+ * that audio be disabled, this object will pretend that audio is not
+ * supported.
+ */
+GuacUI.Audio = new (function() {
+
+ var codecs = [
+ 'audio/ogg; codecs="vorbis"',
+ 'audio/mp4; codecs="mp4a.40.5"',
+ 'audio/mpeg; codecs="mp3"',
+ 'audio/webm; codecs="vorbis"',
+ 'audio/wav; codecs=1'
+ ];
+
+ var probably_supported = [];
+ var maybe_supported = [];
+
+ /**
+ * Array of all supported audio mimetypes, ordered by liklihood of
+ * working.
+ */
+ this.supported = [];
+
+ // If sound disabled, we're done now.
+ if (GuacUI.sessionState.getProperty("disable-sound"))
+ return;
+
+ // Build array of supported audio formats
+ codecs.forEach(function(mimetype) {
+
+ var audio = new Audio();
+ var support_level = audio.canPlayType(mimetype);
+
+ // Trim semicolon and trailer
+ var semicolon = mimetype.indexOf(";");
+ if (semicolon != -1)
+ mimetype = mimetype.substring(0, semicolon);
+
+ // Partition by probably/maybe
+ if (support_level == "probably")
+ probably_supported.push(mimetype);
+ else if (support_level == "maybe")
+ maybe_supported.push(mimetype);
+
+ });
+
+ // Add probably supported types first
+ Array.prototype.push.apply(
+ this.supported, probably_supported);
+
+ // Prioritize "maybe" supported types second
+ Array.prototype.push.apply(
+ this.supported, maybe_supported);
+
+})();
+
+/**
+ * Object describing the UI's level of video support.
+ */
+GuacUI.Video = new (function() {
+
+ var codecs = [
+ 'video/ogg; codecs="theora, vorbis"',
+ 'video/mp4; codecs="avc1.4D401E, mp4a.40.5"',
+ 'video/webm; codecs="vp8.0, vorbis"'
+ ];
+
+ var probably_supported = [];
+ var maybe_supported = [];
+
+ /**
+ * Array of all supported video mimetypes, ordered by liklihood of
+ * working.
+ */
+ this.supported = [];
+
+ // Build array of supported audio formats
+ codecs.forEach(function(mimetype) {
+
+ var video = document.createElement("video");
+ var support_level = video.canPlayType(mimetype);
+
+ // Trim semicolon and trailer
+ var semicolon = mimetype.indexOf(";");
+ if (semicolon != -1)
+ mimetype = mimetype.substring(0, semicolon);
+
+ // Partition by probably/maybe
+ if (support_level == "probably")
+ probably_supported.push(mimetype);
+ else if (support_level == "maybe")
+ maybe_supported.push(mimetype);
+
+ });
+
+ // Add probably supported types first
+ Array.prototype.push.apply(
+ this.supported, probably_supported);
+
+ // Prioritize "maybe" supported types second
+ Array.prototype.push.apply(
+ this.supported, maybe_supported);
+
+})();
+
+
+/**
+ * Central registry of all components for all states.
+ */
+GuacUI.StateManager = new (function() {
+
+ /**
+ * The current state.
+ */
+ var current_state = null;
+
+ /**
+ * Array of arrays of components, indexed by the states they are in.
+ */
+ var components = [];
+
+ /**
+ * Registers the given component with this state manager, to be shown
+ * during the given states.
+ *
+ * @param {GuacUI.Component} component The component to register.
+ * @param {Number} [...] The list of states this component should be
+ * visible during.
+ */
+ this.registerComponent = function(component) {
+
+ // For each state specified, add the given component
+ for (var i=1; i<arguments.length; i++) {
+
+ // Get specified state
+ var state = arguments[i];
+
+ // Get array of components in that state
+ var component_array = components[state];
+ if (!component_array)
+ component_array = components[state] = [];
+
+ // Add component
+ component_array.push(component);
+
+ }
+
+ };
+
+ function allComponents(components, name) {
+
+ // Invoke given function on all components in array
+ for (var i=0; i<components.length; i++)
+ components[i][name]();
+
+ }
+
+ /**
+ * Sets the current visible state.
+ */
+ this.setState = function(state) {
+
+ // Hide components in current state
+ if (current_state && components[current_state])
+ allComponents(components[current_state], "hide");
+
+ // Show all components in new state
+ current_state = state;
+ if (components[state])
+ allComponents(components[state], "show");
+
+ };
+
+ /**
+ * Returns the current visible state.
+ */
+ this.getState = function() {
+ return current_state;
+ };
+
+})();
+
+
+/**
+ * Abstract component which can be registered with GuacUI and shown or hidden
+ * dynamically based on interface mode.
+ *
+ * @constructor
+ */
+GuacUI.Component = function() {
+
+ /**
+ * Called whenever this component needs to be shown and activated.
+ * @event
+ */
+ this.onshow = null;
+
+ /**
+ * Called whenever this component needs to be hidden and deactivated.
+ * @event
+ */
+ this.onhide = null;
+
+};
+
+/**
+ * A Guacamole UI component which can be repositioned by dragging.
+ *
+ * @constructor
+ * @augments GuacUI.Component
+ */
+GuacUI.DraggableComponent = function(element) {
+
+ var draggable_component = this;
+
+ var position_x = 0;
+ var position_y = 0;
+
+ var start_x = 0;
+ var start_y = 0;
+
+ /*
+ * Record drag start when finger hits element
+ */
+ if (element)
+ element.addEventListener("touchstart", function(e) {
+
+ if (e.touches.length == 1) {
+
+ start_x = e.touches[0].screenX;
+ start_y = e.touches[0].screenY;
+
+ }
+
+ e.stopPropagation();
+
+ }, true);
+
+ /*
+ * Update position based on last touch
+ */
+ if (element)
+ element.addEventListener("touchmove", function(e) {
+
+ if (e.touches.length == 1) {
+
+ var new_x = e.touches[0].screenX;
+ var new_y = e.touches[0].screenY;
+
+ position_x += new_x - start_x;
+ position_y += new_y - start_y;
+
+ start_x = new_x;
+ start_y = new_y;
+
+ // Move magnifier to new position
+ draggable_component.move(position_x, position_y);
+
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+
+ }, true);
+
+ if (element)
+ element.addEventListener("touchend", function(e) {
+ e.stopPropagation();
+ }, true);
+
+ /**
+ * Moves this component to the specified location relative to its normal
+ * position.
+ *
+ * @param {Number} x The X coordinate in pixels.
+ * @param {Number} y The Y coordinate in pixels.
+ */
+ this.move = function(x, y) {
+
+ element.style.WebkitTransform =
+ element.style.MozTransform =
+ element.style.OTransform =
+ element.style.msTransform =
+ element.style.transform = "translate("
+ + x + "px, " + y + "px)";
+
+ if (draggable_component.onmove)
+ draggable_component.onmove(x, y);
+
+ };
+
+ /**
+ * Trigered whenever this element is moved.
+ *
+ * @event
+ * @param {Number} x The new X coordinate.
+ * @param {Number} y The new Y coordinate.
+ */
+ this.onmove = null;
+
+};
+
+/**
+ * A connection UI object which can be easily added to a list of connections
+ * for sake of display.
+ */
+GuacUI.ListConnection = function(connection) {
+
+ /**
+ * Reference to this connection.
+ * @private
+ */
+ var guac_connection = this;
+
+ /**
+ * The actual connection associated with this connection UI element.
+ */
+ this.connection = connection;
+
+ /**
+ * Fired when this connection is clicked.
+ * @event
+ */
+ this.onclick = null;
+
+ // Create connection display elements
+ var element = GuacUI.createElement("div", "connection");
+ var caption = GuacUI.createChildElement(element, "div", "caption");
+ var protocol = GuacUI.createChildElement(caption, "div", "protocol");
+ var name = GuacUI.createChildElement(caption, "span", "name");
+ GuacUI.createChildElement(protocol, "div", "icon " + connection.protocol);
+
+ element.addEventListener("click", function(e) {
+
+ // Prevent click from affecting parent
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Fire event if defined
+ if (guac_connection.onclick)
+ guac_connection.onclick();
+
+ }, false);
+
+ // Set name
+ name.textContent = connection.name;
+
+ // Add active usages (if any)
+ var active_users = connection.currentUsage();
+ if (active_users > 0) {
+ var usage = GuacUI.createChildElement(caption, "span", "usage");
+ usage.textContent = "Currently in use by " + active_users + " user(s)";
+ GuacUI.addClass(element, "in-use");
+ }
+
+ /**
+ * Returns the DOM element representing this connection.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+};
+
+/**
+ * A paging component. Elements can be added via the addElement() function,
+ * and will only be shown if they are on the current page, set via setPage().
+ *
+ * Beware that all elements will be added to the given container element, and
+ * all children of the container element will be removed when the page is
+ * changed.
+ */
+GuacUI.Pager = function(container) {
+
+ var guac_pager = this;
+
+ /**
+ * A container for all pager control buttons.
+ */
+ var element = GuacUI.createElement("div", "pager");
+
+ /**
+ * All displayable elements.
+ */
+ var elements = [];
+
+ /**
+ * The number of elements to display per page.
+ */
+ this.page_capacity = 10;
+
+ /**
+ * The number of pages to generate a window for.
+ */
+ this.window_size = 11;
+
+ /**
+ * The current page, where 0 is the first page.
+ */
+ this.current_page = 0;
+
+ /**
+ * The last existing page.
+ */
+ this.last_page = 0;
+
+ function update_display() {
+
+ var i;
+
+ // Calculate first and last elements of page (where the last element
+ // is actually the first element of the next page)
+ var first_element = guac_pager.current_page * guac_pager.page_capacity;
+ var last_element = Math.min(elements.length,
+ first_element + guac_pager.page_capacity);
+
+ // Clear contents, add elements
+ container.innerHTML = "";
+ for (i=first_element; i < last_element; i++)
+ container.appendChild(elements[i]);
+
+ // Update buttons
+ element.innerHTML = "";
+
+ // Create first and prev buttons
+ var first = GuacUI.createChildElement(element, "div", "first-page icon");
+ var prev = GuacUI.createChildElement(element, "div", "prev-page icon");
+
+ // Handle prev/first
+ if (guac_pager.current_page > 0) {
+ first.onclick = function() {
+ guac_pager.setPage(0);
+ };
+
+ prev.onclick = function() {
+ guac_pager.setPage(guac_pager.current_page - 1);
+ };
+ }
+ else {
+ GuacUI.addClass(first, "disabled");
+ GuacUI.addClass(prev, "disabled");
+ }
+
+ // Calculate page jump window start/end
+ var window_start = guac_pager.current_page - (guac_pager.window_size - 1) / 2;
+ var window_end = window_start + guac_pager.window_size - 1;
+
+ // Shift window as necessary
+ if (window_start < 0) {
+ window_end = Math.min(guac_pager.last_page, window_end - window_start);
+ window_start = 0;
+ }
+ else if (window_end > guac_pager.last_page) {
+ window_start = Math.max(0, window_start - window_end + guac_pager.last_page);
+ window_end = guac_pager.last_page;
+ }
+
+ // Add ellipsis if window after beginning
+ if (window_start != 0)
+ GuacUI.createChildElement(element, "div", "more-pages").textContent = "...";
+
+ // Add page jumps
+ for (i=window_start; i<=window_end; i++) {
+
+ // Create clickable element containing page number
+ var jump = GuacUI.createChildElement(element, "div", "set-page");
+ jump.textContent = i+1;
+
+ // Mark current page
+ if (i == guac_pager.current_page)
+ GuacUI.addClass(jump, "current");
+
+ // If not current, add click event
+ else
+ (function(page_number) {
+ jump.onclick = function() {
+ guac_pager.setPage(page_number);
+ };
+ })(i);
+
+ }
+
+ // Add ellipsis if window before end
+ if (window_end != guac_pager.last_page)
+ GuacUI.createChildElement(element, "div", "more-pages").textContent = "...";
+
+ // Create next and last buttons
+ var next = GuacUI.createChildElement(element, "div", "next-page icon");
+ var last = GuacUI.createChildElement(element, "div", "last-page icon");
+
+ // Handle next/last
+ if (guac_pager.current_page < guac_pager.last_page) {
+ next.onclick = function() {
+ guac_pager.setPage(guac_pager.current_page + 1);
+ };
+
+ last.onclick = function() {
+ guac_pager.setPage(guac_pager.last_page);
+ };
+ }
+ else {
+ GuacUI.addClass(next, "disabled");
+ GuacUI.addClass(last, "disabled");
+ }
+
+ }
+
+ /**
+ * Adds the given element to the set of displayable elements.
+ */
+ this.addElement = function(element) {
+ elements.push(element);
+ guac_pager.last_page = Math.max(0,
+ Math.floor((elements.length - 1) / guac_pager.page_capacity));
+ };
+
+ /**
+ * Sets the current page, where 0 is the first page.
+ */
+ this.setPage = function(number) {
+ guac_pager.current_page = number;
+ update_display();
+ };
+
+ /**
+ * Returns the element representing the buttons of this pager.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+};
+
+
+/**
+ * Interface object which displays the progress of a download, ultimately
+ * becoming a download link once complete.
+ *
+ * @constructor
+ * @param {String} filename The name the file will have once complete.
+ */
+GuacUI.Download = function(filename) {
+
+ /**
+ * Reference to this GuacUI.Download.
+ * @private
+ */
+ var guac_download = this;
+
+ /**
+ * The outer div representing the notification.
+ * @private
+ */
+ var element = GuacUI.createElement("div", "download notification");
+
+ /**
+ * Title bar describing the notification.
+ * @private
+ */
+ var title = GuacUI.createChildElement(element, "div", "title-bar");
+
+ /**
+ * Close button for removing the notification.
+ * @private
+ */
+ var close_button = GuacUI.createChildElement(title, "div", "close");
+ close_button.onclick = function() {
+ if (guac_download.onclose)
+ guac_download.onclose();
+ };
+
+ GuacUI.createChildElement(title, "div", "title").textContent =
+ "File Transfer";
+
+ GuacUI.createChildElement(element, "div", "caption").textContent =
+ filename + " ";
+
+ /**
+ * Progress bar and status.
+ * @private
+ */
+ var progress = GuacUI.createChildElement(element, "div", "progress");
+
+ /**
+ * Updates the content of the progress indicator with the given text.
+ *
+ * @param {String} text The text to assign to the progress indicator.
+ */
+ this.updateProgress = function(text) {
+ progress.textContent = text;
+ };
+
+ /**
+ * Removes the progress indicator and replaces it with a download button.
+ */
+ this.complete = function() {
+
+ element.removeChild(progress);
+ GuacUI.addClass(element, "complete");
+
+ var download = GuacUI.createChildElement(element, "div", "download");
+ download.textContent = "Download";
+ download.onclick = function() {
+ if (guac_download.ondownload)
+ guac_download.ondownload();
+ };
+
+ };
+
+ /**
+ * Returns the element representing this notification.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+ /**
+ * Called when the close button of this notification is clicked.
+ * @event
+ */
+ this.onclose = null;
+
+ /**
+ * Called when the download button of this notification is clicked.
+ * @event
+ */
+ this.ondownload = null;
+
+};
+
+/**
+ * A grouping component. Child elements can be added via the addElement()
+ * function. By default, groups display as collapsed.
+ */
+GuacUI.ListGroup = function(caption) {
+
+ /**
+ * Reference to this group.
+ * @private
+ */
+ var guac_group = this;
+
+ /**
+ * Whether this group is empty.
+ * @private
+ */
+ var empty = true;
+
+ /**
+ * A container for for the list group itself.
+ */
+ var element = GuacUI.createElement("div", "group empty");
+
+ // Create connection display elements
+ var caption_element = GuacUI.createChildElement(element, "div", "caption");
+ var caption_icon = GuacUI.createChildElement(caption_element, "div", "icon group");
+ GuacUI.createChildElement(caption_element, "div", "icon type");
+ GuacUI.createChildElement(caption_element, "span", "name").textContent = caption;
+
+ /**
+ * A container for all children of this list group.
+ */
+ var elements = GuacUI.createChildElement(element, "div", "children");
+
+ /**
+ * Whether this group is expanded.
+ *
+ * @type Boolean
+ */
+ this.expanded = false;
+
+ /**
+ * Fired when this group is clicked.
+ * @event
+ */
+ this.onclick = null;
+
+ /**
+ * Returns the element representing this notification.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+ /**
+ * Adds an element as a child of this group.
+ */
+ this.addElement = function(child) {
+
+ // Mark as non-empty
+ if (empty) {
+ GuacUI.removeClass(element, "empty");
+ empty = false;
+ }
+
+ elements.appendChild(child);
+
+ };
+
+ /**
+ * Expands the list group, revealing all children of the group. This
+ * functionality requires supporting CSS.
+ */
+ this.expand = function() {
+ GuacUI.addClass(element, "expanded");
+ guac_group.expanded = true;
+ };
+
+ /**
+ * Collapses the list group, hiding all children of the group. This
+ * functionality requires supporting CSS.
+ */
+ this.collapse = function() {
+ GuacUI.removeClass(element, "expanded");
+ guac_group.expanded = false;
+ };
+
+ // Toggle when icon is clicked
+ caption_icon.addEventListener("click", function(e) {
+
+ // Prevent click from affecting parent
+ e.stopPropagation();
+ e.preventDefault();
+
+ if (guac_group.expanded)
+ guac_group.collapse();
+ else
+ guac_group.expand();
+
+ }, false);
+
+ // Fire event when any other part is clicked
+ element.addEventListener("click", function(e) {
+
+ // Prevent click from affecting parent
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Fire event if defined
+ if (guac_group.onclick)
+ guac_group.onclick();
+
+ }, false);
+
+}
+
+/**
+ * Component which displays a paginated tree view of all groups and their
+ * connections.
+ *
+ * @constructor
+ * @param {GuacamoleService.ConnectionGroup} root_group The group to display
+ * within the view.
+ * @param {Number} flags Any flags (such as MULTISELECT or SHOW_CONNECTIONS)
+ * for modifying the behavior of this group view.
+ * @param {Function} group_filter Function which returns true if the given
+ * group should be displayed and false otherwise.
+ * @param {Function} connection_filter Function which returns true if the given
+ * connection should be displayed and false
+ * otherwise.
+ */
+GuacUI.GroupView = function(root_group, flags,
+ group_filter, connection_filter) {
+
+ /**
+ * Reference to this GroupView.
+ * @private
+ */
+ var group_view = this;
+
+ // Group view components
+ var element = GuacUI.createElement("div", "group-view");
+ var list = GuacUI.createChildElement(element, "div", "list");
+
+ /**
+ * Whether multiselect is enabled.
+ */
+ var multiselect = flags & GuacUI.GroupView.MULTISELECT;
+
+ /**
+ * Whether connections should be included in the view.
+ */
+ var show_connections = flags & GuacUI.GroupView.SHOW_CONNECTIONS;
+
+ /**
+ * Whether the root group should be included in the view.
+ */
+ var show_root = flags & GuacUI.GroupView.SHOW_ROOT_GROUP;
+
+ /**
+ * Set of all group checkboxes, indexed by ID. Only applicable when
+ * multiselect is enabled.
+ * @private
+ */
+ var group_checkboxes = {};
+
+ /**
+ * Set of all connection checkboxes, indexed by ID. Only applicable when
+ * multiselect is enabled.
+ * @private
+ */
+ var connection_checkboxes = {};
+
+ /**
+ * Set of all list groups, indexed by associated group ID.
+ * @private
+ */
+ var list_groups = {};
+
+ /**
+ * Set of all connection groups, indexed by ID.
+ */
+ this.groups = {};
+
+ /**
+ * Set of all connections, indexed by ID.
+ */
+ this.connections = {};
+
+ /**
+ * Fired when a connection is clicked.
+ *
+ * @event
+ * @param {GuacamolService.Connection} connection The connection which was
+ * clicked.
+ */
+ this.onconnectionclick = null;
+
+ /**
+ * Fired when a connection group is clicked.
+ *
+ * @event
+ * @param {GuacamolService.ConnectionGroup} group The connection group which
+ * was clicked.
+ */
+ this.ongroupclick = null;
+
+ /**
+ * Fired when a connection's selected status changes.
+ *
+ * @event
+ * @param {GuacamolService.Connection} connection The connection whose
+ * status changed.
+ * @param {Boolean} selected The new status of the connection.
+ */
+ this.onconnectionchange = null;
+
+ /**
+ * Fired when a connection group's selected status changes.
+ *
+ * @event
+ * @param {GuacamolService.ConnectionGroup} group The connection group whose
+ * status changed.
+ * @param {Boolean} selected The new status of the connection group.
+ */
+ this.ongroupchange = null;
+
+ /**
+ * Returns the element representing this group view.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+ /**
+ * Sets whether the group with the given ID can be selected. This function
+ * only has an effect when multiselect is enabled.
+ *
+ * @param {String} id The ID of the group to alter.
+ * @param {Boolean} value Whether the group should be selected.
+ */
+ this.setGroupEnabled = function(id, value) {
+
+ var checkbox = group_checkboxes[id];
+ if (!checkbox)
+ return;
+
+ // If enabled, show checkbox, allow select
+ if (value) {
+ checkbox.style.visibility = "";
+ checkbox.disabled = false;
+ }
+
+ // Otherwise, hide checkbox
+ else {
+ checkbox.style.visibility = "hidden";
+ checkbox.disabled = true;
+ }
+
+ };
+
+ /**
+ * Sets whether the connection with the given ID can be selected. This
+ * function only has an effect when multiselect is enabled.
+ *
+ * @param {String} id The ID of the connection to alter.
+ * @param {Boolean} value Whether the connection can be selected.
+ */
+ this.setConnectionEnabled = function(id, value) {
+
+ var checkbox = connection_checkboxes[id];
+ if (!checkbox)
+ return;
+
+ // If enabled, show checkbox, allow select
+ if (value) {
+ checkbox.style.visibility = "";
+ checkbox.disabled = false;
+ }
+
+ // Otherwise, hide checkbox
+ else {
+ checkbox.style.visibility = "hidden";
+ checkbox.disabled = true;
+ }
+
+ };
+
+ /**
+ * Sets the current value of the group with the given ID. This function
+ * only has an effect when multiselect is enabled.
+ *
+ * @param {String} id The ID of the group to change.
+ * @param {Boolean} value Whether the group should be selected.
+ */
+ this.setGroupValue = function(id, value) {
+
+ var checkbox = group_checkboxes[id];
+ if (!checkbox)
+ return;
+
+ checkbox.checked = value;
+
+ };
+
+ /**
+ * Sets the current value of the connection with the given ID. This function
+ * only has an effect when multiselect is enabled.
+ *
+ * @param {String} id The ID of the connection to change.
+ * @param {Boolean} value Whether the connection should be selected.
+ */
+ this.setConnectionValue = function(id, value) {
+
+ var checkbox = connection_checkboxes[id];
+ if (!checkbox)
+ return;
+
+ checkbox.checked = value;
+
+ };
+
+ /**
+ * Expands the given group and all parent groups all the way up to root.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group that should
+ * be expanded.
+ */
+ this.expand = function(group) {
+
+ // Skip current group - only need to expand parents
+ group = group.parent;
+
+ // For each group all the way to root
+ while (group !== null) {
+
+ // If list group exists, expand it
+ var list_group = list_groups[group.id];
+ if (list_group)
+ list_group.expand();
+
+ group = group.parent;
+ }
+
+ }
+
+ // Create pager for contents
+ var pager = new GuacUI.Pager(list);
+ pager.page_capacity = 20;
+
+ /**
+ * Adds the contents of the given group via the given appendChild()
+ * function, but not the given group itself.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group whose contents
+ * should be added.
+ * @param {Function} appendChild A function which, given an element, will
+ * add that element the the display as
+ * desired.
+ */
+ function addGroupContents(group, appendChild) {
+
+ var i;
+
+ // Add all contained connections
+ if (show_connections) {
+ for (i=0; i<group.connections.length; i++)
+ addConnection(group.connections[i], appendChild);
+ }
+
+ // Add all contained groups
+ for (i=0; i<group.groups.length; i++)
+ addGroup(group.groups[i], appendChild);
+
+ }
+
+ /**
+ * Adds the given connection via the given appendChild() function.
+ *
+ * @param {GuacamoleService.Connection} connection The connection to add.
+ * @param {Function} appendChild A function which, given an element, will
+ * add that element the the display as
+ * desired.
+ */
+ function addConnection(connection, appendChild) {
+
+ // Do not add connection if filter says "no"
+ if (connection_filter && !connection_filter(connection))
+ return;
+
+ group_view.connections[connection.id] = connection;
+
+ // Add connection to connection list or parent group
+ var guacui_connection = new GuacUI.ListConnection(connection);
+ GuacUI.addClass(guacui_connection.getElement(), "list-item");
+
+ // If multiselect, add checkbox for each connection
+ if (multiselect) {
+
+ var connection_choice = GuacUI.createElement("div", "choice");
+ var connection_checkbox = GuacUI.createChildElement(connection_choice, "input");
+ connection_checkbox.setAttribute("type", "checkbox");
+
+ connection_choice.appendChild(guacui_connection.getElement());
+ appendChild(connection_choice);
+
+ function fire_connection_change(e) {
+
+ // Prevent click from affecting parent
+ e.stopPropagation();
+
+ // Fire event if handler defined
+ if (group_view.onconnectionchange)
+ group_view.onconnectionchange(connection, this.checked);
+
+ }
+
+ // Fire change events when checkbox modified
+ connection_checkbox.addEventListener("click", fire_connection_change, false);
+ connection_checkbox.addEventListener("change", fire_connection_change, false);
+
+ // Add checbox to set of connection checkboxes
+ connection_checkboxes[connection.id] = connection_checkbox;
+
+ }
+ else
+ appendChild(guacui_connection.getElement());
+
+ // Fire click events when connection clicked
+ guacui_connection.onclick = function() {
+ if (group_view.onconnectionclick)
+ group_view.onconnectionclick(connection);
+ };
+
+ }
+
+ /**
+ * Adds the given group via the given appendChild() function.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to add.
+ * @param {Function} appendChild A function which, given an element, will
+ * add that element the the display as
+ * desired.
+ */
+ function addGroup(group, appendChild) {
+
+ // Do not add group if filter says "no"
+ if (group_filter && !group_filter(group))
+ return;
+
+ // Add group to groups collection
+ group_view.groups[group.id] = group;
+
+ // Create element for group
+ var list_group = new GuacUI.ListGroup(group.name);
+ list_groups[group.id] = list_group;
+ GuacUI.addClass(list_group.getElement(), "list-item");
+
+ // Mark group as balancer if appropriate
+ if (group.type === GuacamoleService.ConnectionGroup.Type.BALANCING)
+ GuacUI.addClass(list_group.getElement(), "balancer");
+
+ // Recursively add all children to the new element
+ addGroupContents(group, list_group.addElement);
+
+ // If multiselect, add checkbox for each group
+ if (multiselect) {
+
+ var group_choice = GuacUI.createElement("div", "choice");
+ var group_checkbox = GuacUI.createChildElement(group_choice, "input");
+ group_checkbox.setAttribute("type", "checkbox");
+
+ group_choice.appendChild(list_group.getElement());
+ appendChild(group_choice);
+
+ function fire_group_change(e) {
+
+ // Prevent click from affecting parent
+ e.stopPropagation();
+
+ // Fire event if handler defined
+ if (group_view.ongroupchange)
+ group_view.ongroupchange(group, this.checked);
+
+ }
+
+ // Fire change events when checkbox modified
+ group_checkbox.addEventListener("click", fire_group_change, false);
+ group_checkbox.addEventListener("change", fire_group_change, false);
+
+ // Add checbox to set of group checkboxes
+ group_checkboxes[group.id] = group_checkbox;
+
+ }
+ else
+ appendChild(list_group.getElement());
+
+ // Fire click events when group clicked
+ list_group.onclick = function() {
+ if (group_view.ongroupclick)
+ group_view.ongroupclick(group);
+ };
+
+ }
+
+ // If requested, include the root group as an item
+ if (show_root) {
+ addGroup(root_group, pager.addElement);
+ list_groups[root_group.id].expand();
+ }
+
+ // Otherwise, only add contents of root group
+ else
+ addGroupContents(root_group, pager.addElement);
+
+ // Add buttons if more than one page
+ if (pager.last_page !== 0) {
+ var list_buttons = GuacUI.createChildElement(element, "div", "buttons");
+ list_buttons.appendChild(pager.getElement());
+ }
+
+ // Start at page 0
+ pager.setPage(0);
+
+};
+
+/**
+ * When set, allows multiple groups (or connections to be selected).
+ */
+GuacUI.GroupView.MULTISELECT = 0x1;
+
+/**
+ * When set, also displays connections within the visible groups.
+ */
+GuacUI.GroupView.SHOW_CONNECTIONS = 0x2;
+
+/**
+ * When set, also displays the root group. By default the root group is hidden.
+ */
+GuacUI.GroupView.SHOW_ROOT_GROUP = 0x4;
+
+/**
+ * Simple modal dialog providing a header, body, and footer. No other
+ * functionality is provided other than a reasonable hierarchy of divs and
+ * easy access to their corresponding elements.
+ */
+GuacUI.Dialog = function() {
+
+ /**
+ * The container of the entire dialog. Adding this element to the DOM
+ * displays the dialog, while removing this element hides the dialog.
+ *
+ * @private
+ * @type Element
+ */
+ var element = GuacUI.createElement("div", "dialog-container");
+
+ /**
+ * The dialog itself. This element is not exposed outside this object,
+ * but rather contains the header, body, and footer sections which are
+ * exposed.
+ *
+ * @private
+ * @type Element
+ */
+ var dialog = GuacUI.createChildElement(element, "div", "dialog");
+
+ /**
+ * The header section of the dialog. This section would normally contain
+ * the title.
+ *
+ * @private
+ * @type Element
+ */
+ var header = GuacUI.createChildElement(dialog, "div", "header");
+
+ /**
+ * The body section of the dialog. This section would normally contain any
+ * form fields and content.
+ *
+ * @private
+ * @type Element
+ */
+ var body = GuacUI.createChildElement(dialog, "div", "body");
+
+ /**
+ * The footer section of the dialog. This section would normally contain
+ * the buttons.
+ *
+ * @private
+ * @type Element
+ */
+ var footer = GuacUI.createChildElement(dialog, "div", "footer");
+
+ /**
+ * Returns the header section of this dialog. This section normally
+ * contains the title of the dialog.
+ *
+ * @return {Element} The header section of this dialog.
+ */
+ this.getHeader = function() {
+ return header;
+ };
+
+ /**
+ * Returns the body section of this dialog. This section normally contains
+ * the form fields, etc. of a dialog.
+ *
+ * @return {Element} The body section of this dialog.
+ */
+ this.getBody = function() {
+ return body;
+ };
+
+ /**
+ * Returns the footer section of this dialog. This section is normally
+ * used to contain the buttons of the dialog.
+ *
+ * @return {Element} The footer section of this dialog.
+ */
+ this.getFooter = function() {
+ return footer;
+ };
+
+ /**
+ * Returns the element representing this dialog. Adding this element to
+ * the DOM shows the dialog, while removing this element hides the dialog.
+ *
+ * @return {Element} The element representing this dialog.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+};
diff --git a/guacamole/src/main/webapp/scripts/history.js b/guacamole/src/main/webapp/scripts/history.js
new file mode 100644
index 0000000..f3bbb22
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/history.js
@@ -0,0 +1,175 @@
+/**
+ * Set of thumbnails for each connection, indexed by ID.
+ */
+GuacamoleHistory = new (function() {
+
+ /**
+ * Reference to this GuacamoleHistory.
+ */
+ var guac_history = this;
+
+ /**
+ * The number of entries to allow before removing old entries based on the
+ * cutoff.
+ */
+ var IDEAL_LENGTH = 6;
+
+ /**
+ * The maximum age of a history entry before it is removed, in
+ * milliseconds.
+ */
+ var CUTOFF_AGE = 900000;
+
+ var history = {};
+
+ function truncate() {
+
+ // Build list of entries
+ var entries = [];
+ for (var old_id in history)
+ entries.push(history[old_id]);
+
+ // Avoid history growth beyond defined number of entries
+ if (entries.length > IDEAL_LENGTH) {
+
+ // Sort list
+ entries.sort(GuacamoleHistory.Entry.compare);
+
+ // Remove entries until length is ideal or all are recent
+ var now = new Date().getTime();
+ while (entries.length > IDEAL_LENGTH
+ && now - entries[0].accessed > CUTOFF_AGE) {
+
+ // Remove entry
+ var removed = entries.shift();
+ delete history[removed.id];
+
+ }
+
+ }
+
+ }
+
+
+ /**
+ * Returns the URL for the thumbnail of the connection with the given ID,
+ * or undefined if no thumbnail is associated with that connection.
+ */
+ this.get = function(id) {
+ return history[id] || new GuacamoleHistory.Entry();
+ };
+
+ /**
+ * Updates the thumbnail and access time of the history entry for the
+ * connection with the given ID.
+ */
+ this.update = function(id, thumbnail) {
+
+ // Create updated entry
+ var entry = new GuacamoleHistory.Entry(
+ id,
+ thumbnail,
+ new Date().getTime()
+ );
+
+ // Store entry in history
+ history[id] = entry;
+ truncate();
+
+ // Save updated history
+ localStorage.setItem("GUAC_HISTORY", JSON.stringify(history));
+
+ };
+
+ /**
+ * Reloads all history data.
+ */
+ this.reload = function() {
+
+ // Get old and new for comparison
+ var old_history = history;
+ var new_history = JSON.parse(localStorage.getItem("GUAC_HISTORY") || "{}");
+
+ // Update history
+ history = new_history;
+
+ // Call onchange handler as necessary
+ if (guac_history.onchange) {
+
+ // Produce union of all known IDs
+ var known_ids = {};
+ for (var new_id in new_history) known_ids[new_id] = true;
+ for (var old_id in old_history) known_ids[old_id] = true;
+
+ // For each known ID
+ for (var id in known_ids) {
+
+ // Get entries
+ var old_entry = old_history[id];
+ var new_entry = new_history[id];
+
+ // Call handler for all changed
+ if (!old_entry || !new_entry
+ || old_entry.accessed != new_entry.accessed)
+ guac_history.onchange(id, old_entry, new_entry);
+
+ }
+
+ } // end onchange
+
+ };
+
+ /**
+ * Event handler called whenever a history entry is changed.
+ *
+ * @event
+ * @param {String} id The ID of the connection whose history entry is
+ * changing.
+ * @param {GuacamoleHistory.Entry} old_entry The old value of the entry, if
+ * any.
+ * @param {GuacamoleHistory.Entry} new_entry The new value of the entry, if
+ * any.
+ */
+ this.onchange = null;
+
+ // Reload when modified
+ window.addEventListener("storage", guac_history.reload, false);
+
+ // Initial load
+ guac_history.reload();
+
+})();
+
+/**
+ * A single entry in the indexed connection usage history.
+ *
+ * @constructor
+ * @param {String} id The ID of this connection.
+ * @param {String} thumbnail The URL of the thumbnail to use to represent this
+ * connection.
+ * @param {Number} last_access The time this connection was last accessed, in
+ * seconds.
+ */
+GuacamoleHistory.Entry = function(id, thumbnail, last_access) {
+
+ /**
+ * The ID of the connection associated with this history entry.
+ */
+ this.id = id;
+
+ /**
+ * The thumbnail associated with the connection associated with this history
+ * entry.
+ */
+ this.thumbnail = thumbnail;
+
+ /**
+ * The time the connection associated with this entry was last accessed.
+ */
+ this.accessed = last_access;
+
+};
+
+GuacamoleHistory.Entry.compare = function(a, b) {
+ return a.accessed - b.accessed;
+};
diff --git a/guacamole/src/main/webapp/scripts/lib/blob/LICENSE.md b/guacamole/src/main/webapp/scripts/lib/blob/LICENSE.md
new file mode 100644
index 0000000..7eb56b9
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/lib/blob/LICENSE.md
@@ -0,0 +1,30 @@
+This software is licensed under the MIT/X11 license.
+
+MIT/X11 license
+---------------
+
+Copyright © 2011 [Eli Grey][1].
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+
+ [1]: http://eligrey.com
\ No newline at end of file
diff --git a/guacamole/src/main/webapp/scripts/lib/blob/blob.js b/guacamole/src/main/webapp/scripts/lib/blob/blob.js
new file mode 100644
index 0000000..6d48b39
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/lib/blob/blob.js
@@ -0,0 +1,178 @@
+/* Blob.js
+ * A Blob implementation.
+ * 2013-06-20
+ *
+ * By Eli Grey, http://eligrey.com
+ * By Devin Samarin, https://github.com/eboyjr
+ * License: X11/MIT
+ * See LICENSE.md
+ */
+
+/*global self, unescape */
+/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
+ plusplus: true */
+
+/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
+
+if (typeof Blob !== "function" || typeof URL === "undefined")
+if (typeof Blob === "function" && typeof webkitURL !== "undefined") var URL = webkitURL;
+else var Blob = (function (view) {
+ "use strict";
+
+ var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || view.MSBlobBuilder || (function(view) {
+ var
+ get_class = function(object) {
+ return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
+ }
+ , FakeBlobBuilder = function BlobBuilder() {
+ this.data = [];
+ }
+ , FakeBlob = function Blob(data, type, encoding) {
+ this.data = data;
+ this.size = data.length;
+ this.type = type;
+ this.encoding = encoding;
+ }
+ , FBB_proto = FakeBlobBuilder.prototype
+ , FB_proto = FakeBlob.prototype
+ , FileReaderSync = view.FileReaderSync
+ , FileException = function(type) {
+ this.code = this[this.name = type];
+ }
+ , file_ex_codes = (
+ "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
+ ).split(" ")
+ , file_ex_code = file_ex_codes.length
+ , real_URL = view.URL || view.webkitURL || view
+ , real_create_object_URL = real_URL.createObjectURL
+ , real_revoke_object_URL = real_URL.revokeObjectURL
+ , URL = real_URL
+ , btoa = view.btoa
+ , atob = view.atob
+ , can_apply_typed_arrays = false
+ , can_apply_typed_arrays_test = function(pass) {
+ can_apply_typed_arrays = !pass;
+ }
+
+ , ArrayBuffer = view.ArrayBuffer
+ , Uint8Array = view.Uint8Array
+ ;
+ FakeBlob.fake = FB_proto.fake = true;
+ while (file_ex_code--) {
+ FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
+ }
+ try {
+ if (Uint8Array) {
+ can_apply_typed_arrays_test.apply(0, new Uint8Array(1));
+ }
+ } catch (ex) {}
+ if (!real_URL.createObjectURL) {
+ URL = view.URL = {};
+ }
+ URL.createObjectURL = function(blob) {
+ var
+ type = blob.type
+ , data_URI_header
+ ;
+ if (type === null) {
+ type = "application/octet-stream";
+ }
+ if (blob instanceof FakeBlob) {
+ data_URI_header = "data:" + type;
+ if (blob.encoding === "base64") {
+ return data_URI_header + ";base64," + blob.data;
+ } else if (blob.encoding === "URI") {
+ return data_URI_header + "," + decodeURIComponent(blob.data);
+ } if (btoa) {
+ return data_URI_header + ";base64," + btoa(blob.data);
+ } else {
+ return data_URI_header + "," + encodeURIComponent(blob.data);
+ }
+ } else if (real_create_object_URL) {
+ return real_create_object_URL.call(real_URL, blob);
+ }
+ };
+ URL.revokeObjectURL = function(object_URL) {
+ if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
+ real_revoke_object_URL.call(real_URL, object_URL);
+ }
+ };
+ FBB_proto.append = function(data/*, endings*/) {
+ var bb = this.data;
+ // decode data to a binary string
+ if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
+ if (can_apply_typed_arrays) {
+ bb.push(String.fromCharCode.apply(String, new Uint8Array(data)));
+ } else {
+ var
+ str = ""
+ , buf = new Uint8Array(data)
+ , i = 0
+ , buf_len = buf.length
+ ;
+ for (; i < buf_len; i++) {
+ str += String.fromCharCode(buf[i]);
+ }
+ }
+ } else if (get_class(data) === "Blob" || get_class(data) === "File") {
+ if (FileReaderSync) {
+ var fr = new FileReaderSync;
+ bb.push(fr.readAsBinaryString(data));
+ } else {
+ // async FileReader won't work as BlobBuilder is sync
+ throw new FileException("NOT_READABLE_ERR");
+ }
+ } else if (data instanceof FakeBlob) {
+ if (data.encoding === "base64" && atob) {
+ bb.push(atob(data.data));
+ } else if (data.encoding === "URI") {
+ bb.push(decodeURIComponent(data.data));
+ } else if (data.encoding === "raw") {
+ bb.push(data.data);
+ }
+ } else {
+ if (typeof data !== "string") {
+ data += ""; // convert unsupported types to strings
+ }
+ // decode UTF-16 to binary string
+ bb.push(unescape(encodeURIComponent(data)));
+ }
+ };
+ FBB_proto.getBlob = function(type) {
+ if (!arguments.length) {
+ type = null;
+ }
+ return new FakeBlob(this.data.join(""), type, "raw");
+ };
+ FBB_proto.toString = function() {
+ return "[object BlobBuilder]";
+ };
+ FB_proto.slice = function(start, end, type) {
+ var args = arguments.length;
+ if (args < 3) {
+ type = null;
+ }
+ return new FakeBlob(
+ this.data.slice(start, args > 1 ? end : this.data.length)
+ , type
+ , this.encoding
+ );
+ };
+ FB_proto.toString = function() {
+ return "[object Blob]";
+ };
+ return FakeBlobBuilder;
+ }(view));
+
+ return function Blob(blobParts, options) {
+ var type = options ? (options.type || "") : "";
+ var builder = new BlobBuilder();
+ if (blobParts) {
+ for (var i = 0, len = blobParts.length; i < len; i++) {
+ builder.append(blobParts[i]);
+ }
+ }
+ return builder.getBlob(type);
+ };
+}(self));
diff --git a/guacamole/src/main/webapp/scripts/lib/filesaver/LICENSE.md b/guacamole/src/main/webapp/scripts/lib/filesaver/LICENSE.md
new file mode 100644
index 0000000..7eb56b9
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/lib/filesaver/LICENSE.md
@@ -0,0 +1,30 @@
+This software is licensed under the MIT/X11 license.
+
+MIT/X11 license
+---------------
+
+Copyright © 2011 [Eli Grey][1].
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+
+ [1]: http://eligrey.com
\ No newline at end of file
diff --git a/guacamole/src/main/webapp/scripts/lib/filesaver/filesaver.js b/guacamole/src/main/webapp/scripts/lib/filesaver/filesaver.js
new file mode 100644
index 0000000..1d858c5
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/lib/filesaver/filesaver.js
@@ -0,0 +1,216 @@
+/* FileSaver.js
+ * A saveAs() FileSaver implementation.
+ * 2013-01-23
+ *
+ * By Eli Grey, http://eligrey.com
+ * License: X11/MIT
+ * See LICENSE.md
+ */
+
+/*global self */
+/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
+ plusplus: true */
+
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
+
+var saveAs = saveAs
+ || (navigator.msSaveBlob && navigator.msSaveBlob.bind(navigator))
+ || (function(view) {
+ "use strict";
+ var
+ doc = view.document
+ // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
+ , get_URL = function() {
+ return view.URL || view.webkitURL || view;
+ }
+ , URL = view.URL || view.webkitURL || view
+ , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
+ , can_use_save_link = "download" in save_link
+ , click = function(node) {
+ var event = doc.createEvent("MouseEvents");
+ event.initMouseEvent(
+ "click", true, false, view, 0, 0, 0, 0, 0
+ , false, false, false, false, 0, null
+ );
+ node.dispatchEvent(event);
+ }
+ , webkit_req_fs = view.webkitRequestFileSystem
+ , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
+ , throw_outside = function (ex) {
+ (view.setImmediate || view.setTimeout)(function() {
+ throw ex;
+ }, 0);
+ }
+ , force_saveable_type = "application/octet-stream"
+ , fs_min_size = 0
+ , deletion_queue = []
+ , process_deletion_queue = function() {
+ var i = deletion_queue.length;
+ while (i--) {
+ var file = deletion_queue[i];
+ if (typeof file === "string") { // file is an object URL
+ URL.revokeObjectURL(file);
+ } else { // file is a File
+ file.remove();
+ }
+ }
+ deletion_queue.length = 0; // clear queue
+ }
+ , dispatch = function(filesaver, event_types, event) {
+ event_types = [].concat(event_types);
+ var i = event_types.length;
+ while (i--) {
+ var listener = filesaver["on" + event_types[i]];
+ if (typeof listener === "function") {
+ try {
+ listener.call(filesaver, event || filesaver);
+ } catch (ex) {
+ throw_outside(ex);
+ }
+ }
+ }
+ }
+ , FileSaver = function(blob, name) {
+ // First try a.download, then web filesystem, then object URLs
+ var
+ filesaver = this
+ , type = blob.type
+ , blob_changed = false
+ , object_url
+ , target_view
+ , get_object_url = function() {
+ var object_url = get_URL().createObjectURL(blob);
+ deletion_queue.push(object_url);
+ return object_url;
+ }
+ , dispatch_all = function() {
+ dispatch(filesaver, "writestart progress write writeend".split(" "));
+ }
+ // on any filesys errors revert to saving with object URLs
+ , fs_error = function() {
+ // don't create more object URLs than needed
+ if (blob_changed || !object_url) {
+ object_url = get_object_url(blob);
+ }
+ if (target_view) {
+ target_view.location.href = object_url;
+ } else {
+ window.open(object_url, "_blank");
+ }
+ filesaver.readyState = filesaver.DONE;
+ dispatch_all();
+ }
+ , abortable = function(func) {
+ return function() {
+ if (filesaver.readyState !== filesaver.DONE) {
+ return func.apply(this, arguments);
+ }
+ };
+ }
+ , create_if_not_found = {create: true, exclusive: false}
+ , slice
+ ;
+ filesaver.readyState = filesaver.INIT;
+ if (!name) {
+ name = "download";
+ }
+ if (can_use_save_link) {
+ object_url = get_object_url(blob);
+ save_link.href = object_url;
+ save_link.download = name;
+ click(save_link);
+ filesaver.readyState = filesaver.DONE;
+ dispatch_all();
+ return;
+ }
+ // Object and web filesystem URLs have a problem saving in Google Chrome when
+ // viewed in a tab, so I force save with application/octet-stream
+ // http://code.google.com/p/chromium/issues/detail?id=91158
+ if (view.chrome && type && type !== force_saveable_type) {
+ slice = blob.slice || blob.webkitSlice;
+ blob = slice.call(blob, 0, blob.size, force_saveable_type);
+ blob_changed = true;
+ }
+ // Since I can't be sure that the guessed media type will trigger a download
+ // in WebKit, I append .download to the filename.
+ // https://bugs.webkit.org/show_bug.cgi?id=65440
+ if (webkit_req_fs && name !== "download") {
+ name += ".download";
+ }
+ if (type === force_saveable_type || webkit_req_fs) {
+ target_view = view;
+ }
+ if (!req_fs) {
+ fs_error();
+ return;
+ }
+ fs_min_size += blob.size;
+ req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
+ fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
+ var save = function() {
+ dir.getFile(name, create_if_not_found, abortable(function(file) {
+ file.createWriter(abortable(function(writer) {
+ writer.onwriteend = function(event) {
+ target_view.location.href = file.toURL();
+ deletion_queue.push(file);
+ filesaver.readyState = filesaver.DONE;
+ dispatch(filesaver, "writeend", event);
+ };
+ writer.onerror = function() {
+ var error = writer.error;
+ if (error.code !== error.ABORT_ERR) {
+ fs_error();
+ }
+ };
+ "writestart progress write abort".split(" ").forEach(function(event) {
+ writer["on" + event] = filesaver["on" + event];
+ });
+ writer.write(blob);
+ filesaver.abort = function() {
+ writer.abort();
+ filesaver.readyState = filesaver.DONE;
+ };
+ filesaver.readyState = filesaver.WRITING;
+ }), fs_error);
+ }), fs_error);
+ };
+ dir.getFile(name, {create: false}, abortable(function(file) {
+ // delete file if it already exists
+ file.remove();
+ save();
+ }), abortable(function(ex) {
+ if (ex.code === ex.NOT_FOUND_ERR) {
+ save();
+ } else {
+ fs_error();
+ }
+ }));
+ }), fs_error);
+ }), fs_error);
+ }
+ , FS_proto = FileSaver.prototype
+ , saveAs = function(blob, name) {
+ return new FileSaver(blob, name);
+ }
+ ;
+ FS_proto.abort = function() {
+ var filesaver = this;
+ filesaver.readyState = filesaver.DONE;
+ dispatch(filesaver, "abort");
+ };
+ FS_proto.readyState = FS_proto.INIT = 0;
+ FS_proto.WRITING = 1;
+ FS_proto.DONE = 2;
+
+ FS_proto.error =
+ FS_proto.onwritestart =
+ FS_proto.onprogress =
+ FS_proto.onwrite =
+ FS_proto.onabort =
+ FS_proto.onerror =
+ FS_proto.onwriteend =
+ null;
+
+ view.addEventListener("unload", process_deletion_queue, false);
+ return saveAs;
+}(self));
diff --git a/guacamole/src/main/webapp/scripts/root-ui.js b/guacamole/src/main/webapp/scripts/root-ui.js
new file mode 100644
index 0000000..3815d8b
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/root-ui.js
@@ -0,0 +1,516 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * General set of UI elements and UI-related functions regarding user login and
+ * connection management.
+ */
+var GuacamoleRootUI = {
+
+ "sections": {
+ "login_form" : document.getElementById("login-form"),
+ "recent_connections" : document.getElementById("recent-connections"),
+ "all_connections" : document.getElementById("all-connections")
+ },
+
+ "messages": {
+ "login_error" : document.getElementById("login-error"),
+ "no_recent_connections" : document.getElementById("no-recent")
+ },
+
+ "fields": {
+ "username" : document.getElementById("username"),
+ "password" : document.getElementById("password"),
+ "clipboard" : document.getElementById("clipboard")
+ },
+
+ "buttons": {
+ "login" : document.getElementById("login"),
+ "logout" : document.getElementById("logout"),
+ "manage" : document.getElementById("manage")
+ },
+
+ "settings": {
+ "auto_fit" : document.getElementById("auto-fit"),
+ "disable_sound" : document.getElementById("disable-sound")
+ },
+
+ "views": {
+ "login" : document.getElementById("login-ui"),
+ "connections" : document.getElementById("connection-list-ui")
+ },
+
+ "session_state" : new GuacamoleSessionState(),
+ "parameters" : null
+
+};
+
+// Get parameters from query string
+GuacamoleRootUI.parameters = window.location.search.substring(1) || null;
+
+/**
+ * A connection UI object which can be easily added to a list of connections
+ * for sake of display.
+ *
+ * @param {String} id The ID of this object, including prefix.
+ * @param {String} name The name that should be displayed.
+ */
+GuacamoleRootUI.RecentConnection = function(id, name) {
+
+ /**
+ * The ID of this object, including prefix.
+ * @type String
+ */
+ this.id = id;
+
+ /**
+ * The displayable name of this object.
+ * @type String
+ */
+ this.name = name;
+
+ // Create connection display elements
+ var element = GuacUI.createElement("div", "connection");
+ var thumbnail = GuacUI.createChildElement(element, "div", "thumbnail");
+ var caption = GuacUI.createChildElement(element, "div", "caption");
+ var name_element = GuacUI.createChildElement(caption, "span", "name");
+
+ // Connect on click
+ element.addEventListener("click", function(e) {
+
+ // Prevent click from affecting parent
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Open connection
+ GuacUI.openObject(id, GuacamoleRootUI.parameters);
+
+ }, false);
+
+ // Set name
+ name_element.textContent = name;
+
+ // Add screenshot if available
+ var thumbnail_url = GuacamoleHistory.get(id).thumbnail;
+ if (thumbnail_url) {
+
+ // Create thumbnail element
+ var thumb_img = GuacUI.createChildElement(thumbnail, "img");
+ thumb_img.src = thumbnail_url;
+
+ }
+
+ /**
+ * Returns the DOM element representing this connection.
+ */
+ this.getElement = function() {
+ return element;
+ };
+
+ /**
+ * Sets the thumbnail URL of this existing connection. Note that this will
+ * only work if the connection already had a thumbnail associated with it.
+ */
+ this.setThumbnail = function(url) {
+
+ // If no image element, create it
+ if (!thumb_img) {
+ thumb_img = document.createElement("img");
+ thumb_img.src = url;
+ thumbnail.appendChild(thumb_img);
+ }
+
+ // Otherwise, set source of existing
+ else
+ thumb_img.src = url;
+
+ };
+
+};
+
+/**
+ * Attempts to login the given user using the given password, throwing an
+ * error if the process fails.
+ *
+ * @param {String} username The name of the user to login as.
+ * @param {String} password The password to use to authenticate the user.
+ */
+GuacamoleRootUI.login = function(username, password) {
+
+ // Get username and password from form
+ var data =
+ "username=" + encodeURIComponent(username)
+ + "&password=" + encodeURIComponent(password)
+
+ // Include query parameters in submission data
+ if (GuacamoleRootUI.parameters)
+ data += "&" + GuacamoleRootUI.parameters;
+
+ // Log in
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", "login", false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
+ xhr.send(data);
+
+ // Handle failures
+ if (xhr.status != 200)
+ throw new Error("Invalid login");
+
+};
+
+/**
+ * Set of all thumbnailed connections, indexed by ID. Here, each connection
+ * is a GuacamoleRootUI.RecentConnection.
+ */
+GuacamoleRootUI.recentConnections = {};
+
+/**
+ * Set of all connections, indexed by ID. Each connection is a
+ * GuacamoleService.Connection.
+ */
+GuacamoleRootUI.connections = {};
+
+/**
+ * Adds the given RecentConnection to the recent connections list.
+ */
+GuacamoleRootUI.addRecentConnection = function(id, name) {
+
+ // Create recent connection object
+ var connection = new GuacamoleRootUI.RecentConnection(id, name);
+
+ // Add connection object to list of thumbnailed connections
+ GuacamoleRootUI.recentConnections[connection.id] =
+ connection;
+
+ // Add connection to recent list
+ GuacamoleRootUI.sections.recent_connections.appendChild(
+ connection.getElement());
+
+ // Hide "No recent connections" message
+ GuacamoleRootUI.messages.no_recent_connections.style.display = "none";
+
+};
+
+
+/**
+ * Resets the interface such that the login UI is displayed if
+ * the user is not authenticated (or authentication fails) and
+ * the connection list UI (or the client for the only available
+ * connection, if there is only one) is displayed if the user is
+ * authenticated.
+ */
+GuacamoleRootUI.reset = function() {
+
+ function hasEntry(object) {
+ for (var name in object)
+ return true;
+ return false;
+ }
+
+ // Read root group
+ var root_group;
+ try {
+ root_group = GuacamoleService.Connections.list(GuacamoleRootUI.parameters);
+
+ // Show admin elements if admin permissions available
+ var permissions = GuacamoleService.Permissions.list(null, GuacamoleRootUI.parameters);
+ if (permissions.administer
+ || permissions.create_connection
+ || permissions.create_user
+ || hasEntry(permissions.update_user)
+ || hasEntry(permissions.remove_user)
+ || hasEntry(permissions.administer_user)
+ || hasEntry(permissions.update_connection)
+ || hasEntry(permissions.remove_connection)
+ || hasEntry(permissions.administer_connection))
+ GuacUI.addClass(document.body, "admin");
+ else
+ GuacUI.removeClass(document.body, "admin");
+
+ }
+ catch (e) {
+
+ // Show login UI if unable to get connections
+ GuacamoleRootUI.views.login.style.display = "";
+ GuacamoleRootUI.views.connections.style.display = "none";
+
+ return;
+
+ }
+
+
+ // Create group view
+ var group_view = new GuacUI.GroupView(root_group, GuacUI.GroupView.SHOW_CONNECTIONS);
+ GuacamoleRootUI.sections.all_connections.appendChild(group_view.getElement());
+
+ // Add any connections with thumbnails
+ for (var connection_id in group_view.connections) {
+
+ // Get corresponding connection
+ var connection = group_view.connections[connection_id];
+
+ // If thumbnail exists, add to recent connections
+ if (GuacamoleHistory.get("c/" + connection_id).thumbnail)
+ GuacamoleRootUI.addRecentConnection("c/" + connection_id, connection.name);
+
+ }
+
+ // Add any groups with thumbnails
+ for (var group_id in group_view.groups) {
+
+ // Get corresponding group
+ var group = group_view.groups[group_id];
+
+ // If thumbnail exists, add to recent connections
+ if (GuacamoleHistory.get("g/" + group_id).thumbnail)
+ GuacamoleRootUI.addRecentConnection("g/" + group_id, group.name);
+
+ }
+
+ // Open connections when clicked
+ group_view.onconnectionclick = function(connection) {
+ GuacUI.openConnection(connection.id, GuacamoleRootUI.parameters);
+ };
+
+ // Open connection groups when clicked
+ group_view.ongroupclick = function(group) {
+
+ // Connect if balancing
+ if (group.type === GuacamoleService.ConnectionGroup.Type.BALANCING)
+ GuacUI.openConnectionGroup(group.id, GuacamoleRootUI.parameters);
+
+ };
+
+ // Save all connections for later reference
+ GuacamoleRootUI.connections = group_view.connections;
+
+ // If connections could be retrieved, display list
+ GuacamoleRootUI.views.login.style.display = "none";
+ GuacamoleRootUI.views.connections.style.display = "";
+
+};
+
+GuacamoleHistory.onchange = function(id, old_entry, new_entry) {
+
+ // Get existing connection, if any
+ var connection = GuacamoleRootUI.recentConnections[id];
+
+ // If we are adding or updating a connection
+ if (new_entry) {
+
+ // Ensure connection is added
+ if (!connection) {
+
+ // If connection not actually defined, storage must be being
+ // modified externally. Stop early.
+ if (!GuacamoleRootUI.connections[id]) return;
+
+ // Create new connection
+ GuacamoleRootUI.addRecentConnection(id, connection.name);
+
+ }
+
+ // Set new thumbnail
+ connection.setThumbnail(new_entry.thumbnail);
+
+ }
+
+ // Otherwise, delete existing connection
+ else {
+
+ GuacamoleRootUI.sections.recent_connections.removeChild(
+ connection.getElement());
+
+ delete GuacamoleRootUI.recentConnections[id];
+
+ // Display "No recent connections" message if none left
+ if (GuacamoleRootUI.recentConnections.length === 0)
+ GuacamoleRootUI.messages.no_recent_connections.style.display = "";
+
+ }
+
+};
+
+/*
+ * This window has no name. We need it to have no name. If someone navigates
+ * to the root UI within the same window as a previous connection, we need to
+ * remove the name from that window such that new attempts to use that previous
+ * connection do not replace the contents of this very window.
+ */
+window.name = "";
+
+/*
+ * Update session state when auto-fit checkbox is changed
+ */
+
+GuacamoleRootUI.settings.auto_fit.onchange =
+GuacamoleRootUI.settings.auto_fit.onclick = function() {
+
+ GuacamoleRootUI.session_state.setProperty(
+ "auto-fit", GuacamoleRootUI.settings.auto_fit.checked);
+
+};
+
+/*
+ * Update session state when disable-sound checkbox is changed
+ */
+
+GuacamoleRootUI.settings.disable_sound.onchange =
+GuacamoleRootUI.settings.disable_sound.onclick = function() {
+
+ GuacamoleRootUI.session_state.setProperty(
+ "disable-sound", GuacamoleRootUI.settings.disable_sound.checked);
+
+};
+
+/*
+ * Update clipboard contents when changed
+ */
+
+window.onblur =
+GuacamoleRootUI.fields.clipboard.onchange = function() {
+
+ // Set value if changed
+ var new_value = GuacamoleRootUI.fields.clipboard.value;
+ if (GuacamoleRootUI.session_state.getProperty("clipboard") != new_value)
+ GuacamoleRootUI.session_state.setProperty("clipboard", new_value);
+
+};
+
+/*
+ * Update element states when session state changes
+ */
+
+GuacamoleRootUI.session_state.onchange =
+function(old_state, new_state, name) {
+
+ // Clipboard
+ if (name == "clipboard")
+ GuacamoleRootUI.fields.clipboard.value = new_state[name];
+
+ // Auto-fit display
+ else if (name == "auto-fit")
+ GuacamoleRootUI.fields.auto_fit.checked = new_state[name];
+
+ // Disable Sound
+ else if (name == "disable-sound")
+ GuacamoleRootUI.fields.disable_sound.checked = new_state[name];
+
+};
+
+/*
+ * Initialize clipboard with current data
+ */
+
+if (GuacamoleRootUI.session_state.getProperty("clipboard"))
+ GuacamoleRootUI.fields.clipboard.value =
+ GuacamoleRootUI.session_state.getProperty("clipboard");
+
+/*
+ * Default to true if auto-fit not specified
+ */
+
+if (GuacamoleRootUI.session_state.getProperty("auto-fit") === undefined)
+ GuacamoleRootUI.session_state.setProperty("auto-fit", true);
+
+/*
+ * Initialize auto-fit setting in UI
+ */
+
+GuacamoleRootUI.settings.auto_fit.checked =
+ GuacamoleRootUI.session_state.getProperty("auto-fit");
+
+/*
+ * Initialize disable-sound setting in UI
+ */
+GuacamoleRootUI.settings.disable_sound.checked =
+ GuacamoleRootUI.session_state.getProperty("disable-sound");
+
+/*
+ * Set handler for logout
+ */
+
+GuacamoleRootUI.buttons.logout.onclick = function() {
+ window.location.href = "logout";
+};
+
+/*
+ * Set handler for admin
+ */
+
+GuacamoleRootUI.buttons.manage.onclick = function() {
+ window.location.href = "admin.xhtml";
+};
+
+/*
+ * Set handler for login
+ */
+
+GuacamoleRootUI.sections.login_form.onsubmit = function() {
+
+ try {
+
+ // Attempt login
+ GuacamoleRootUI.login(
+ GuacamoleRootUI.fields.username.value,
+ GuacamoleRootUI.fields.password.value
+ );
+
+ // Ensure username/password fields are blurred after login attempt
+ GuacamoleRootUI.fields.username.blur();
+ GuacamoleRootUI.fields.password.blur();
+
+ // Reset UI
+ GuacamoleRootUI.reset();
+
+ }
+ catch (e) {
+
+ // Display error, reset and refocus password field
+ GuacamoleRootUI.messages.login_error.textContent = e.message;
+
+ // Reset and recofus password field
+ GuacamoleRootUI.fields.password.value = "";
+ GuacamoleRootUI.fields.password.focus();
+
+ }
+
+ // Always cancel submit
+ return false;
+
+};
+
+/*
+ * Turn off autocorrect and autocapitalization on usename
+ */
+
+GuacamoleRootUI.fields.username.setAttribute("autocorrect", "off");
+GuacamoleRootUI.fields.username.setAttribute("autocapitalize", "off");
+
+/*
+ * Initialize UI
+ */
+
+GuacamoleRootUI.reset();
+
+/*
+ * Make sure body has an associated touch event handler such that CSS styles
+ * will work in browsers that require this.
+ */
+document.body.ontouchstart = function() {};
diff --git a/guacamole/src/main/webapp/scripts/service.js b/guacamole/src/main/webapp/scripts/service.js
new file mode 100644
index 0000000..c427356
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/service.js
@@ -0,0 +1,1398 @@
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Main Guacamole web service namespace.
+ * @namespace
+ */
+var GuacamoleService = GuacamoleService || {};
+
+/**
+ * An arbitary Guacamole connection group, having the given type, ID and name.
+ *
+ * @constructor
+ * @param {Number} type The type of this connection group - either ORGANIZATIONAL
+ * or BALANCING.
+ * @param {String} id An arbitrary ID, likely assigned by the auth provider.
+ * @param {String} name The human-readable name of this group.
+ */
+GuacamoleService.ConnectionGroup = function(type, id, name) {
+
+ /**
+ * The type of this connection group.
+ * @type Number
+ */
+ this.type = type;
+
+ /**
+ * The unique ID of this connection group.
+ * @type String
+ */
+ this.id = id;
+
+ /**
+ * The human-readable name associated with this connection group.
+ * @type String
+ */
+ this.name = name;
+
+ /**
+ * The parent connection group of this group. If this group is the root
+ * group, this will be null.
+ *
+ * @type GuacamoleService.ConnectionGroup
+ */
+ this.parent = null;
+
+ /**
+ * All connection groups contained within this group.
+ * @type GuacamoleService.ConnectionGroup[]
+ */
+ this.groups = [];
+
+ /**
+ * All connections contained within this group.
+ * @type GuacamoleService.Connection[]
+ */
+ this.connections = [];
+
+};
+
+/**
+ * Set of all possible types for ConnectionGroups.
+ */
+GuacamoleService.ConnectionGroup.Type = {
+
+ /**
+ * Organizational groups exist solely to hold connections or other groups,
+ * and provide no other semantics.
+ *
+ * @type Number
+ */
+ "ORGANIZATIONAL" : 0,
+
+ /**
+ * Balancing groups act as connections. Users that have READ permission on
+ * balancing groups can use the group as if it were a connection, and that
+ * group will choose an appropriate connection within itself for that user
+ * to use.
+ *
+ * @type Number
+ */
+ "BALANCING" : 1
+
+};
+
+/**
+ * An arbitrary Guacamole connection, consisting of an ID/protocol pair.
+ *
+ * @constructor
+ * @param {String} protocol The protocol used by this connection.
+ * @param {String} id The ID associated with this connection.
+ * @param {String} name The human-readable name associated with this connection.
+ */
+GuacamoleService.Connection = function(protocol, id, name) {
+
+ /**
+ * Reference to this connection.
+ */
+ var guac_connection = this;
+
+ /**
+ * The parent connection group of this connection.
+ * @type GuacamoleService.ConnectionGroup
+ */
+ this.parent = null;
+
+ /**
+ * The protocol associated with this connection.
+ */
+ this.protocol = protocol;
+
+ /**
+ * The ID associated with this connection.
+ */
+ this.id = id;
+
+ /**
+ * All parameters associated with this connection, if available.
+ */
+ this.parameters = {};
+
+ /**
+ * The name of this connection. This name is arbitrary and local to the
+ * group containing the connection.
+ *
+ * @type String
+ */
+ this.name = name;
+
+ /**
+ * An array of GuacamoleService.Connection.Record listing the usage
+ * history of this connection.
+ */
+ this.history = [];
+
+ /**
+ * Returns the number of active users of this connection (which may be
+ * multiple instances under the same user) by walking the history records.
+ *
+ * @return {Number} The number of active users of this connection.
+ */
+ this.currentUsage = function() {
+
+ // Number of users of this connection
+ var usage = 0;
+
+ // Walk history counting active entries
+ for (var i=0; i<guac_connection.history.length; i++) {
+ if (guac_connection.history[i].active)
+ usage++;
+ }
+
+ return usage;
+
+ };
+
+};
+
+/**
+ * Creates a new GuacamoleService.Connection.Record describing a single
+ * session for the given username and having the given start/end times.
+ *
+ * @constructor
+ * @param {String} username The username of the user who used the connection.
+ * @param {Number} start The time that the connection began (in UNIX epoch
+ * milliseconds).
+ * @param {Number} end The time that the connection ended (in UNIX epoch
+ * milliseconds). This parameter is optional.
+ * @param {Boolean} active Whether the connection is currently active.
+ */
+GuacamoleService.Connection.Record = function(username, start, end, active) {
+
+ /**
+ * The username of the user associated with this record.
+ * @type String
+ */
+ this.username = username;
+
+ /**
+ * The time the corresponding connection began.
+ * @type Date
+ */
+ this.start = new Date(start);
+
+ /**
+ * The time the corresponding connection terminated (if any).
+ * @type Date
+ */
+ this.end = null;
+
+ /**
+ * Whether this connection is currently active.
+ */
+ this.active = active;
+
+ /**
+ * The duration of this connection, in seconds. This value is only
+ * defined if the end time is available.
+ * @type Number
+ */
+ this.duration = null;
+
+ // If end time given, intialize end time
+ if (end) {
+ this.end = new Date(end);
+ this.duration = (end - start) / 1000;
+ }
+
+};
+
+/**
+ * A basic set of permissions that can be assigned to a user, describing
+ * whether they can create other users/connections and describing which
+ * users/connections they have permission to read or modify.
+ */
+GuacamoleService.PermissionSet = function() {
+
+ /**
+ * Whether permission to create users is granted.
+ */
+ this.create_user = false;
+
+ /**
+ * Whether permission to create connections is granted.
+ */
+ this.create_connection = false;
+
+ /**
+ * Whether permission to create connection groups is granted.
+ */
+ this.create_connection_group = false;
+
+ /**
+ * Whether permission to administer the system in general is granted.
+ */
+ this.administer = false;
+
+ /**
+ * Object with a property entry for each readable user.
+ */
+ this.read_user = {};
+
+ /**
+ * Object with a property entry for each updatable user.
+ */
+ this.update_user = {};
+
+ /**
+ * Object with a property entry for each removable user.
+ */
+ this.remove_user = {};
+
+ /**
+ * Object with a property entry for each administerable user.
+ */
+ this.administer_user = {};
+
+ /**
+ * Object with a property entry for each readable connection.
+ */
+ this.read_connection = {};
+
+ /**
+ * Object with a property entry for each updatable connection.
+ */
+ this.update_connection = {};
+
+ /**
+ * Object with a property entry for each removable connection.
+ */
+ this.remove_connection = {};
+
+ /**
+ * Object with a property entry for each administerable connection.
+ */
+ this.administer_connection = {};
+
+ /**
+ * Object with a property entry for each readable connection group.
+ */
+ this.read_connection_group = {};
+
+ /**
+ * Object with a property entry for each updatable connection group.
+ */
+ this.update_connection_group = {};
+
+ /**
+ * Object with a property entry for each removable connection group.
+ */
+ this.remove_connection_group = {};
+
+ /**
+ * Object with a property entry for each administerable connection group.
+ */
+ this.administer_connection_group = {};
+
+};
+
+/**
+ * Handles the reponse from the given XMLHttpRequest object, throwing an error
+ * with a meaningful message if the request failed.
+ *
+ * @param {XMLHttpRequest} xhr The XMLHttpRequest to check the response of.
+ */
+GuacamoleService.handleResponse = function(xhr) {
+
+ // For HTTP Forbidden, just return permission denied
+ if (xhr.status == 403)
+ throw new Error("Permission denied.");
+
+ // Otherwise, if unsuccessful, throw error with message derived from
+ // response
+ if (xhr.status != 200) {
+
+ // Retrieve error message
+ var message = xhr.getResponseHeader("Guacamole-Error-Message")
+ || xhr.statusText;
+
+ // Throw error with derived message
+ throw new Error(message);
+
+ }
+
+};
+
+/**
+ * Collection of service functions which deal with connections. Each function
+ * makes an explicit HTTP query to the server, and parses the response.
+ */
+GuacamoleService.Connections = {
+
+ /**
+ * Comparator which compares two arbitrary objects by their name property.
+ */
+ "comparator" : function(a, b) {
+ return a.name.localeCompare(b.name);
+ },
+
+ /**
+ * Returns the root connection group, containing a hierarchy of all other
+ * groups and connections for which the current user has access.
+ *
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ * @return {GuacamoleService.ConnectionGroup} The root group, containing
+ * a hierarchy of all other
+ * groups and connections to
+ * which the current user has
+ * access.
+ */
+ "list" : function(parameters) {
+
+ /**
+ * Parse the contents of the given connection element within XML,
+ * returning a corresponding GuacamoleService.Connection.
+ *
+ * @param {GuacamoleService.ConnectionGroup} The connection group
+ * containing this connection.
+ * @param {Element} element The element being parsed.
+ * @return {GuacamoleService.Connection} The connection represented by
+ * the element just parsed.
+ */
+ function parseConnection(parent, element) {
+
+ var i;
+
+ var connection = new GuacamoleService.Connection(
+ element.getAttribute("protocol"),
+ element.getAttribute("id"),
+ element.getAttribute("name")
+ );
+
+ // Set parent
+ connection.parent = parent;
+
+ // Add parameter values for each parmeter received
+ var paramElements = element.getElementsByTagName("param");
+ for (i=0; i<paramElements.length; i++) {
+
+ var paramElement = paramElements[i];
+ var name = paramElement.getAttribute("name");
+
+ connection.parameters[name] = paramElement.textContent;
+
+ }
+
+ // Parse history, if available
+ var historyElements = element.getElementsByTagName("history");
+ if (historyElements.length === 1) {
+
+ // For each record in history
+ var history = historyElements[0];
+ var recordElements = history.getElementsByTagName("record");
+ for (i=0; i<recordElements.length; i++) {
+
+ // Get record
+ var recordElement = recordElements[i];
+ var record = new GuacamoleService.Connection.Record(
+ recordElement.textContent,
+ parseInt(recordElement.getAttribute("start")),
+ parseInt(recordElement.getAttribute("end")),
+ recordElement.getAttribute("active") === "yes"
+ );
+
+ // Append to connection history
+ connection.history.push(record);
+
+ }
+
+ }
+
+ // Return parsed connection
+ return connection;
+
+ }
+
+ /**
+ * Recursively parse the contents of the given group element within XML,
+ * returning a corresponding GuacamoleService.ConnectionGroup.
+ *
+ * @param {GuacamoleService.ConnectionGroup} The connection group
+ * containing this group.
+ * @param {Element} element The element being parsed.
+ * @return {GuacamoleService.ConnectionGroup} The connection group
+ * represented by the element
+ * just parsed.
+ */
+ function parseGroup(parent, element) {
+
+ var id = element.getAttribute("id");
+ var name = element.getAttribute("name");
+ var type_string = element.getAttribute("type");
+
+ // Translate type name
+ var type;
+ if (type_string === "organizational")
+ type = GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL;
+ else if (type_string === "balancing")
+ type = GuacamoleService.ConnectionGroup.Type.BALANCING;
+
+ // Create corresponding group
+ var group = new GuacamoleService.ConnectionGroup(type, id, name);
+
+ // Set parent
+ group.parent = parent;
+
+ // For each child element
+ var current = element.firstChild;
+ while (current !== null) {
+
+ var i, child;
+ var children = current.childNodes;
+
+ if (current.localName === "connections") {
+
+ // Parse all child connections
+ for (i=0; i<children.length; i++) {
+ var child = children[i];
+ if (child.localName === "connection")
+ group.connections.push(parseConnection(group, child));
+ }
+
+ }
+ else if (current.localName === "groups") {
+
+ // Parse all child groups
+ for (i=0; i<children.length; i++) {
+ var child = children[i];
+ if (child.localName === "group")
+ group.groups.push(parseGroup(group, child));
+ }
+
+ }
+
+ // Next element
+ current = current.nextSibling;
+
+ }
+
+ // Sort groups and connections
+ group.groups.sort(GuacamoleService.Connections.comparator);
+ group.connections.sort(GuacamoleService.Connections.comparator);
+
+ // Return created group
+ return group;
+
+ }
+
+ // Construct request URL
+ var list_url = "connections";
+ if (parameters) list_url += "?" + parameters;
+
+ // Get connection list
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", list_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+ return parseGroup(null, xhr.responseXML.documentElement);
+
+ },
+
+ /**
+ * Creates a new connection.
+ *
+ * @param {GuacamoleService.Connection} connection The connection to create.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "create" : function(connection, parameters) {
+
+ // Construct request URL
+ var users_url = "connections/create?name=" + encodeURIComponent(connection.name);
+ if (parameters) users_url += "&" + parameters;
+
+ // Init POST data
+ var data = "protocol=" + encodeURIComponent(connection.protocol);
+
+ // Add group if given
+ if (connection.parent)
+ data += "&parentID=" + encodeURIComponent(connection.parent.id);
+
+ // Add parameters
+ for (var name in connection.parameters)
+ data += "&_" + encodeURIComponent(name)
+ + "=" + encodeURIComponent(connection.parameters[name]);
+
+ // Add user
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", users_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Updates an existing connection. All properties are updated except
+ * the location of the connection, which is ignored.
+ *
+ * @param {GuacamoleService.Connection} connection The connection to create.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "update" : function(connection, parameters) {
+
+ // Construct request URL
+ var users_url = "connections/update?id=" + encodeURIComponent(connection.id);
+ if (parameters) users_url += "&" + parameters;
+
+ // Init POST data
+ var data =
+ "name=" + encodeURIComponent(connection.name)
+ + "&protocol=" + encodeURIComponent(connection.protocol);
+
+ // Add parameters
+ for (var name in connection.parameters)
+ data += "&_" + encodeURIComponent(name)
+ + "=" + encodeURIComponent(connection.parameters[name]);
+
+ // Add user
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", users_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Updates the location of an existing connection. This does not result
+ * in any change to the connection provided as a parameter.
+ *
+ * @param {GuacamoleService.Connection} connection The connection to create.
+ * @param {GuacamoleService.ConnectionGroup} dest The destination group.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "move" : function(connection, dest, parameters) {
+
+ // Construct request URL
+ var connection_url = "connections/move?id=" + encodeURIComponent(connection.id);
+ if (parameters) connection_url += "&" + parameters;
+
+ // Init POST data
+ var data = "parentID=" + encodeURIComponent(dest.id);
+
+ // Move connection
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", connection_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Deletes the connection having the given identifier.
+ *
+ * @param {String} id The identifier of the connection to delete.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "remove" : function(id, parameters) {
+
+ // Construct request URL
+ var connections_url = "connections/delete?id=" + encodeURIComponent(id);
+ if (parameters) connections_url += "&" + parameters;
+
+ // Add user
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", connections_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ }
+
+};
+
+/**
+ * Collection of service functions which deal with connections groups. Each
+ * function makes an explicit HTTP query to the server, and parses the response.
+ */
+GuacamoleService.ConnectionGroups = {
+
+ /**
+ * Creates a new connection group.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to create.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "create" : function(group, parameters) {
+
+ // Construct request URL
+ var groups_url = "connectiongroups/create?name=" + encodeURIComponent(group.name);
+ if (parameters) groups_url += "&" + parameters;
+
+ // Init POST data
+ var data;
+ if (group.type === GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL)
+ data = "type=organizational";
+ else if (group.type === GuacamoleService.ConnectionGroup.Type.BALANCING)
+ data = "type=balancing";
+
+ // Add parent group if given
+ if (group.parent)
+ data += "&parentID=" + encodeURIComponent(group.parent.id);
+
+ // Create group
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", groups_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Updates an existing connection group. All properties are updated except
+ * the location of the group, which is ignored.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to create.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "update" : function(group, parameters) {
+
+ // Construct request URL
+ var groups_url = "connectiongroups/update?id=" + encodeURIComponent(group.id);
+ if (parameters) groups_url += "&" + parameters;
+
+ // Init POST data
+ var data = "name=" + encodeURIComponent(group.name);
+
+ // Add type
+ if (group.type === GuacamoleService.ConnectionGroup.Type.ORGANIZATIONAL)
+ data += "&type=organizational";
+ else if (group.type === GuacamoleService.ConnectionGroup.Type.BALANCING)
+ data += "&type=balancing";
+
+ // Update group
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", groups_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Sets the location of an existing connection group. This does not result
+ * in any change to the group provided as a parameter.
+ *
+ * @param {GuacamoleService.ConnectionGroup} group The group to create.
+ * @param {GuacamoleService.ConnectionGroup} dest The destination group.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "move" : function(group, dest, parameters) {
+
+ // Construct request URL
+ var groups_url = "connectiongroups/move?id=" + encodeURIComponent(group.id);
+ if (parameters) groups_url += "&" + parameters;
+
+ // Init POST data
+ var data = "parentID=" + encodeURIComponent(dest.id);
+
+ // Move group
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", groups_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Deletes the connection group having the given identifier.
+ *
+ * @param {String} id The identifier of the group to delete.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "remove" : function(id, parameters) {
+
+ // Construct request URL
+ var groups_url = "connectiongroups/delete?id=" + encodeURIComponent(id);
+ if (parameters) groups_url += "&" + parameters;
+
+ // Delete group
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", groups_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ }
+
+};
+
+/**
+ * Collection of service functions which deal with users. Each function
+ * makes an explicit HTTP query to the server, and parses the response.
+ */
+GuacamoleService.Users = {
+
+ /**
+ * Returns an array of usernames for which the current user has access.
+ *
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ * @return {String[]} An array of usernames for which the current user has
+ * access.
+ */
+ "list" : function(parameters) {
+
+ // Construct request URL
+ var users_url = "users";
+ if (parameters) users_url += "?" + parameters;
+
+ // Get user list
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", users_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ // Otherwise, get list
+ var users = new Array();
+
+ var userElements = xhr.responseXML.getElementsByTagName("user");
+ for (var i=0; i<userElements.length; i++)
+ users.push(userElements[i].getAttribute("name"));
+
+ // Sort by username
+ users.sort();
+
+ return users;
+
+ },
+
+ /**
+ * Updates the user having the given username.
+ *
+ * @param {String} username The username of the user to create.
+ * @param {String} password The password to assign to the user (optional).
+ * @param {GuacamoleService.PermissionSet} permissions_added All permissions that were added.
+ * @param {GuacamoleService.PermissionSet} permissions_removed All permissions that were removed.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "update" : function(username, password, permissions_added,
+ permissions_removed, parameters) {
+
+ // Construct request URL
+ var users_url = "users/update";
+ if (parameters) users_url += "?" + parameters;
+
+ // Init POST data
+ var data = "name=" + encodeURIComponent(username);
+ if (password) data += "&password=" + encodeURIComponent(password);
+
+ var name;
+
+ // System permissions
+ if (permissions_added.create_user) data += "&%2Bsys=create-user";
+ if (permissions_added.create_connection) data += "&%2Bsys=create-connection";
+ if (permissions_added.create_connection_group) data += "&%2Bsys=create-connection-group";
+ if (permissions_added.administer) data += "&%2Bsys=admin";
+
+ // User permissions
+ for (name in permissions_added.read_user)
+ data += "&%2Buser=read:" + encodeURIComponent(name);
+ for (name in permissions_added.administer_user)
+ data += "&%2Buser=admin:" + encodeURIComponent(name);
+ for (name in permissions_added.update_user)
+ data += "&%2Buser=update:" + encodeURIComponent(name);
+ for (name in permissions_added.remove_user)
+ data += "&%2Buser=delete:" + encodeURIComponent(name);
+
+ // Connection permissions
+ for (name in permissions_added.read_connection)
+ data += "&%2Bconnection=read:" + encodeURIComponent(name);
+ for (name in permissions_added.administer_connection)
+ data += "&%2Bconnection=admin:" + encodeURIComponent(name);
+ for (name in permissions_added.update_connection)
+ data += "&%2Bconnection=update:" + encodeURIComponent(name);
+ for (name in permissions_added.remove_connection)
+ data += "&%2Bconnection=delete:" + encodeURIComponent(name);
+
+ // Connection group permissions
+ for (name in permissions_added.read_connection_group)
+ data += "&%2Bconnection-group=read:" + encodeURIComponent(name);
+ for (name in permissions_added.administer_connection_group)
+ data += "&%2Bconnection-group=admin:" + encodeURIComponent(name);
+ for (name in permissions_added.update_connection_group)
+ data += "&%2Bconnection-group=update:" + encodeURIComponent(name);
+ for (name in permissions_added.remove_connection_group)
+ data += "&%2Bconnection-group=delete:" + encodeURIComponent(name);
+
+ // Creation permissions
+ if (permissions_removed.create_user) data += "&-sys=create-user";
+ if (permissions_removed.create_connection) data += "&-sys=create-connection";
+ if (permissions_removed.create_connection_group) data += "&-sys=create-connection-group";
+ if (permissions_removed.administer) data += "&-sys=admin";
+
+ // User permissions
+ for (name in permissions_removed.read_user)
+ data += "&-user=read:" + encodeURIComponent(name);
+ for (name in permissions_removed.administer_user)
+ data += "&-user=admin:" + encodeURIComponent(name);
+ for (name in permissions_removed.update_user)
+ data += "&-user=update:" + encodeURIComponent(name);
+ for (name in permissions_removed.remove_user)
+ data += "&-user=delete:" + encodeURIComponent(name);
+
+ // Connection permissions
+ for (name in permissions_removed.read_connection)
+ data += "&-connection=read:" + encodeURIComponent(name);
+ for (name in permissions_removed.administer_connection)
+ data += "&-connection=admin:" + encodeURIComponent(name);
+ for (name in permissions_removed.update_connection)
+ data += "&-connection=update:" + encodeURIComponent(name);
+ for (name in permissions_removed.remove_connection)
+ data += "&-connection=delete:" + encodeURIComponent(name);
+
+ // Connection group permissions
+ for (name in permissions_removed.read_connection_group)
+ data += "&-connection-group=read:" + encodeURIComponent(name);
+ for (name in permissions_removed.administer_connection_group)
+ data += "&-connection-group=admin:" + encodeURIComponent(name);
+ for (name in permissions_removed.update_connection_group)
+ data += "&-connection-group=update:" + encodeURIComponent(name);
+ for (name in permissions_removed.remove_connection_group)
+ data += "&-connection-group=delete:" + encodeURIComponent(name);
+
+ // Update user
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", users_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Creates a new user having the given username.
+ *
+ * @param {String} username The username of the user to create.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "create" : function(username, parameters) {
+
+ // Construct request URL
+ var users_url = "users/create?name=" + encodeURIComponent(username);
+ if (parameters) users_url += "&" + parameters;
+
+ // Add user
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", users_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ },
+
+ /**
+ * Deletes the user having the given username.
+ *
+ * @param {String} username The username of the user to delete.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ */
+ "remove" : function(username, parameters) {
+
+ // Construct request URL
+ var users_url = "users/delete?name=" + encodeURIComponent(username);
+ if (parameters) users_url += "&" + parameters;
+
+ // Add user
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", users_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ }
+
+};
+
+/**
+ * Collection of service functions which deal with permissions. Each function
+ * makes an explicit HTTP query to the server, and parses the response.
+ */
+GuacamoleService.Permissions = {
+
+ /**
+ * Returns a PermissionSet describing the permissions given to a
+ * specified user.
+ *
+ * @param {String} username The username of the user to list permissions
+ * of.
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ * @return {GuacamoleService.PermissionSet} A PermissionSet describing the
+ * permissions given to the
+ * specified user.
+ */
+ "list" : function(username, parameters) {
+
+ // Construct request URL
+ var list_url = "permissions";
+ if (parameters) list_url += "?" + parameters;
+
+ // Init POST data
+ var data;
+ if (username)
+ data = "user=" + encodeURIComponent(username);
+ else
+ data = null;
+
+ // Get permission list
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", list_url, false);
+ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
+ xhr.send(data);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ // Otherwise, build PermissionSet
+ var i, type, name;
+ var permissions = new GuacamoleService.PermissionSet();
+
+ // Read system permissions
+ var connectionsElements = xhr.responseXML.getElementsByTagName("system");
+ for (i=0; i<connectionsElements.length; i++) {
+
+ // Get type
+ type = connectionsElements[i].getAttribute("type");
+ switch (type) {
+
+ // Create connection permission
+ case "create-connection":
+ permissions.create_connection = true;
+ break;
+
+ // Create connection group permission
+ case "create-connection-group":
+ permissions.create_connection_group = true;
+ break;
+
+ // Create user permission
+ case "create-user":
+ permissions.create_user = true;
+ break;
+
+ // System admin permission
+ case "admin":
+ permissions.administer = true;
+ break;
+
+ }
+
+ }
+
+ // Read connection permissions
+ var connectionElements = xhr.responseXML.getElementsByTagName("connection");
+ for (i=0; i<connectionElements.length; i++) {
+
+ // Get name and type
+ type = connectionElements[i].getAttribute("type");
+ name = connectionElements[i].getAttribute("name");
+
+ switch (type) {
+
+ // Read permission
+ case "read":
+ permissions.read_connection[name] = true;
+ break;
+
+ // Update permission
+ case "update":
+ permissions.update_connection[name] = true;
+ break;
+
+ // Admin permission
+ case "admin":
+ permissions.administer_connection[name] = true;
+ break;
+
+ // Delete permission
+ case "delete":
+ permissions.remove_connection[name] = true;
+ break;
+
+ }
+
+ }
+
+ // Read connection group permissions
+ var connectionGroupElements = xhr.responseXML.getElementsByTagName("connection-group");
+ for (i=0; i<connectionGroupElements.length; i++) {
+
+ // Get name and type
+ type = connectionGroupElements[i].getAttribute("type");
+ name = connectionGroupElements[i].getAttribute("name");
+
+ switch (type) {
+
+ // Read permission
+ case "read":
+ permissions.read_connection_group[name] = true;
+ break;
+
+ // Update permission
+ case "update":
+ permissions.update_connection_group[name] = true;
+ break;
+
+ // Admin permission
+ case "admin":
+ permissions.administer_connection_group[name] = true;
+ break;
+
+ // Delete permission
+ case "delete":
+ permissions.remove_connection_group[name] = true;
+ break;
+
+ }
+
+ }
+
+ // Read user permissions
+ var userElements = xhr.responseXML.getElementsByTagName("user");
+ for (i=0; i<userElements.length; i++) {
+
+ // Get name and type
+ type = userElements[i].getAttribute("type");
+ name = userElements[i].getAttribute("name");
+
+ switch (type) {
+
+ // Read permission
+ case "read":
+ permissions.read_user[name] = true;
+ break;
+
+ // Update permission
+ case "update":
+ permissions.update_user[name] = true;
+ break;
+
+ // Admin permission
+ case "admin":
+ permissions.administer_user[name] = true;
+ break;
+
+ // Delete permission
+ case "delete":
+ permissions.remove_user[name] = true;
+ break;
+
+ }
+
+ }
+
+ return permissions;
+
+ }
+
+};
+
+/**
+ * Representation of a protocol supported by Guacamole, having a given name,
+ * title, and set of parameters.
+ */
+GuacamoleService.Protocol = function(name, title, parameters) {
+
+ /**
+ * The unique name associated with this protocol. This is the name that is
+ * used to identify the protocol to Guacamole.
+ */
+ this.name = name;
+
+ /**
+ * A human-readable title describing this protocol. This is what the user
+ * will use to identify the protocol.
+ */
+ this.title = title;
+
+ /**
+ * Array of all available parameters, in desired order of presentation.
+ * @type GuacamoleService.Protocol.Parameter[]
+ */
+ this.parameters = parameters || [];
+
+};
+
+/**
+ * A parameter belonging to a protocol. Each parameter has a name which
+ * identifies the parameter to the protocol, a human-readable title,
+ * a value for boolean parameters, and a type which dictates
+ * its presentation to the user.
+ */
+GuacamoleService.Protocol.Parameter = function(name, title, type, value, options) {
+
+ /**
+ * The name of this parameter.
+ */
+ this.name = name;
+
+ /**
+ * A human-readable title describing this parameter.
+ */
+ this.title = title;
+
+ /**
+ * The type of this parameter.
+ */
+ this.type = type;
+
+ /**
+ * The value of this parameter.
+ */
+ this.value = value;
+
+ /**
+ * All available options, if applicable, in desired order of presentation.
+ * @type GuacamoleService.Protocol.Parameter.Option[]
+ */
+ this.options = options || [];
+
+};
+
+/**
+ * An option for a parameter. A parameter has options if it only has a specified
+ * and enumerated legal set of values.
+ */
+GuacamoleService.Protocol.Parameter.Option = function(value, title) {
+
+ /**
+ * The value of this option. This is the value that will be assigned to the
+ * parameter if this option is chosen.
+ */
+ this.value = value;
+
+ /**
+ * The title of this option. This is the value that will be presented to the
+ * user for selection.
+ */
+ this.title = title;
+
+};
+
+/**
+ * A free-form text field.
+ */
+GuacamoleService.Protocol.Parameter.TEXT = 0;
+
+/**
+ * A password field.
+ */
+GuacamoleService.Protocol.Parameter.PASSWORD = 1;
+
+/**
+ * A numeric field.
+ */
+GuacamoleService.Protocol.Parameter.NUMERIC = 2;
+
+/**
+ * A boolean (checkbox) field.
+ */
+GuacamoleService.Protocol.Parameter.BOOLEAN = 3;
+
+/**
+ * An enumerated (select) field.
+ */
+GuacamoleService.Protocol.Parameter.ENUM = 4;
+
+/**
+ * Collection of service functions which deal with protocols. Each function
+ * makes an explicit HTTP query to the server, and parses the response.
+ */
+GuacamoleService.Protocols = {
+
+ /**
+ * Returns an array containing all available protocols and all
+ * corresponding parameters, as well as hints regarding expected datatype
+ * and allowed/default values.
+ *
+ * Note that this function is a stub returning a simple object until the
+ * corresponding server-side component is created.
+ *
+ * @param {String} parameters Any parameters which should be passed to the
+ * server for the sake of authentication
+ * (optional).
+ * @return {GuacamoleService.Protocol[]} An array containing all available
+ * protocols.
+ */
+ "list" : function(parameters) {
+
+ // Construct request URL
+ var list_url = "protocols";
+ if (parameters) list_url += "?" + parameters;
+
+ // Get permission list
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", list_url, false);
+ xhr.send(null);
+
+ // Handle response
+ GuacamoleService.handleResponse(xhr);
+
+ // Array of all protocols
+ var protocols = [];
+
+ // Parse all protocols
+ var protocolElements = xhr.responseXML.getElementsByTagName("protocol");
+ for (var i=0; i<protocolElements.length; i++) {
+
+ // Get protocol element
+ var protocolElement = protocolElements[i];
+
+ // Create corresponding protocol
+ var protocol = new GuacamoleService.Protocol(
+ protocolElement.getAttribute("name"),
+ protocolElement.getAttribute("title")
+ );
+
+ // Parse all parameters
+ var paramElements = protocolElement.getElementsByTagName("param");
+ for (var j=0; j<paramElements.length; j++) {
+
+ // Get parameter element
+ var paramElement = paramElements[j];
+
+ // Create corresponding parameter
+ var parameter = new GuacamoleService.Protocol.Parameter(
+ paramElement.getAttribute("name"),
+ paramElement.getAttribute("title")
+ );
+
+ // Parse type
+ switch (paramElement.getAttribute("type")) {
+
+ // Text parameter
+ case "text":
+ parameter.type = GuacamoleService.Protocol.Parameter.TEXT;
+ break;
+
+ // Password parameter
+ case "password":
+ parameter.type = GuacamoleService.Protocol.Parameter.PASSWORD;
+ break;
+
+ // Numeric parameter
+ case "numeric":
+ parameter.type = GuacamoleService.Protocol.Parameter.NUMERIC;
+ break;
+
+ // Boolean parameter
+ case "boolean":
+ parameter.type = GuacamoleService.Protocol.Parameter.BOOLEAN;
+ parameter.value = paramElement.getAttribute("value");
+ break;
+
+ // Enumerated parameter
+ case "enum":
+ parameter.type = GuacamoleService.Protocol.Parameter.ENUM;
+ break;
+
+ }
+
+ // Parse all options
+ var optionElements = paramElement.getElementsByTagName("option");
+ for (var k=0; k<optionElements.length; k++) {
+
+ // Get option element
+ var optionElement = optionElements[k];
+
+ parameter.options.push(
+ new GuacamoleService.Protocol.Parameter.Option(
+ optionElement.getAttribute("value"),
+ optionElement.textContent
+ ));
+
+ } // end for each option
+
+ // Add parameter
+ protocol.parameters.push(parameter);
+
+ } // end for each parameter
+
+ // Add protocol
+ protocols.push(protocol);
+
+ } // end for each protocol
+
+ return protocols;
+
+ }
+
+};
\ No newline at end of file
diff --git a/guacamole/src/main/webapp/scripts/session.js b/guacamole/src/main/webapp/scripts/session.js
new file mode 100644
index 0000000..9b25a89
--- /dev/null
+++ b/guacamole/src/main/webapp/scripts/session.js
@@ -0,0 +1,107 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Maintains state across multiple Guacamole pages via HTML5 Web Storage.
+ * @constructor
+ */
+function GuacamoleSessionState() {
+
+ /**
+ * Reference to this GuacamoleSessionState.
+ * @private
+ */
+ var guac_state = this;
+
+ /**
+ * The last read state object.
+ * @private
+ */
+ var state = localStorage.getItem("GUACAMOLE_STATE") || {};
+
+ /**
+ * Reloads the internal state, sending onchange events for all changed,
+ * deleted, or new properties.
+ */
+ this.reload = function() {
+
+ // Pull current state
+ var new_state = JSON.parse(localStorage.getItem("GUACAMOLE_STATE") || "{}");
+
+ // Assign new state
+ var old_state = state;
+ state = new_state;
+
+ // Check if any values are different
+ for (var name in new_state) {
+
+ // If value changed, call handler
+ var old = old_state[name];
+ if (old != new_state[name]) {
+
+ // Call change handler
+ if (guac_state.onchange)
+ guac_state.onchange(state, new_state, name);
+
+ }
+
+ }
+
+ };
+
+ /**
+ * Sets the given property to the given value.
+ *
+ * @param {String} name The name of the property to change.
+ * @param value An arbitrary value.
+ */
+ this.setProperty = function(name, value) {
+ state[name] = value;
+ localStorage.setItem("GUACAMOLE_STATE", JSON.stringify(state));
+ };
+
+ /**
+ * Returns the value stored under the property having the given name.
+ *
+ * @param {String} name The name of the property to read.
+ * @return The value of the given property.
+ */
+ this.getProperty = function(name) {
+ return state[name];
+ };
+
+ /**
+ * Event which is fired whenever a property value is changed externally.
+ *
+ * @event
+ * @param old_state An object whose properties' values are the old values
+ * of this GuacamoleSessionState.
+ * @param new_state An object whose properties' values are the new values
+ * of this GuacamoleSessionState.
+ * @param {String} name The name of the property that is being changed.
+ */
+ this.onchange = null;
+
+ // Reload when modified
+ window.addEventListener("storage", guac_state.reload, false);
+
+ // Initial load
+ guac_state.reload();
+
+}
diff --git a/guacamole/src/main/webapp/styles/animation.css b/guacamole/src/main/webapp/styles/animation.css
new file mode 100644
index 0000000..80bb237
--- /dev/null
+++ b/guacamole/src/main/webapp/styles/animation.css
@@ -0,0 +1,35 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * fadein: Fade from fully transparent to fully opaque.
+ */
+ at keyframes fadein {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+ at -moz-keyframes fadein {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+ at -webkit-keyframes fadein {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
diff --git a/guacamole/src/main/webapp/styles/client.css b/guacamole/src/main/webapp/styles/client.css
new file mode 100644
index 0000000..94ce614
--- /dev/null
+++ b/guacamole/src/main/webapp/styles/client.css
@@ -0,0 +1,420 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+body {
+ background: black;
+ font-family: FreeSans, Helvetica, Arial, sans-serif;
+ padding: 0;
+ margin: 0;
+}
+
+img {
+ border: none;
+}
+
+.software-cursor {
+ cursor: url('../images/mouse/dot.gif'),url('../images/mouse/blank.cur'),default;
+ overflow: hidden;
+}
+
+.guac-error .software-cursor {
+ cursor: default;
+}
+
+* {
+ -webkit-tap-highlight-color: rgba(0,0,0,0);
+}
+
+.event-target {
+ position: fixed;
+ opacity: 0;
+}
+
+/* Dialogs */
+
+div.dialogOuter {
+ display: table;
+ height: 100%;
+ width: 100%;
+ position: fixed;
+ left: 0;
+ top: 0;
+ background: rgba(0, 0, 0, 0.75);
+}
+
+div.dialogMiddle {
+ width: 100%;
+ text-align: center;
+ display: table-cell;
+ vertical-align: middle;
+}
+
+div.dialog {
+ padding: 1em;
+
+ max-width: 75%;
+ text-align: left;
+
+ display: inline-block;
+}
+
+div.dialog h1 {
+ margin: 0;
+ margin-bottom: 0.25em;
+ text-align: center;
+}
+
+div.dialog div.buttons {
+ margin: 0;
+ margin-top: 0.5em;
+ text-align: center;
+}
+
+button {
+
+ border-style: solid;
+ border-width: 1px;
+
+ padding: 0.25em;
+ padding-right: 1em;
+ padding-left: 1em;
+
+}
+
+button:active {
+
+ padding-top: 0.35em;
+ padding-left: 1.1em;
+
+ padding-bottom: 0.15em;
+ padding-right: 0.9em;
+
+}
+
+button#reconnect {
+ display: none;
+}
+
+.guac-error button#reconnect {
+ display: inline;
+
+ background: #200;
+ border-color: #822;
+ color: #944;
+}
+
+.guac-error button#reconnect:hover {
+ background: #822;
+ border-color: #B33;
+ color: black;
+}
+
+
+div.dialog p {
+ margin: 0;
+}
+
+div.displayOuter {
+ height: 100%;
+ width: 100%;
+ position: absolute;
+ left: 0;
+ top: 0;
+ display: table;
+}
+
+div.displayMiddle {
+ width: 100%;
+ display: table-cell;
+ vertical-align: middle;
+ text-align: center;
+}
+
+div#display * {
+ position: relative;
+}
+
+div#display > * {
+ margin-left: auto;
+ margin-right: auto;
+}
+
+div.magnifier-background {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 1;
+ overflow: hidden;
+}
+
+div.magnifier {
+
+ position: absolute;
+ left: 0;
+ top: 0;
+
+ box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.75);
+ width: 50%;
+ height: 50%;
+ overflow: hidden;
+
+}
+
+.pan-overlay,
+.type-overlay {
+ position: fixed;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 1;
+}
+
+.pan-overlay .indicator {
+ position: fixed;
+ background-size: 32px 32px;
+ -moz-background-size: 32px 32px;
+ -webkit-background-size: 32px 32px;
+ -khtml-background-size: 32px 32px;
+ background-position: center;
+ background-repeat: no-repeat;
+ opacity: 0.8;
+}
+
+.pan-overlay .indicator.up {
+
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 32px;
+
+ background-image: url('../images/arrows/arrows-u.png');
+
+}
+
+.pan-overlay .indicator.down {
+
+ bottom: 0;
+ left: 0;
+ right: 0;
+ height: 32px;
+
+ background-image: url('../images/arrows/arrows-d.png');
+
+}
+
+.pan-overlay .indicator.left {
+
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 32px;
+
+ background-image: url('../images/arrows/arrows-l.png');
+
+}
+
+.pan-overlay .indicator.right {
+
+ top: 0;
+ bottom: 0;
+ right: 0;
+ width: 32px;
+
+ background-image: url('../images/arrows/arrows-r.png');
+
+}
+
+/* Viewport Clone */
+
+div#viewportClone {
+ display: table;
+ height: 100%;
+ width: 100%;
+ position: fixed;
+ left: 0;
+ top: 0;
+
+ visibility: hidden;
+}
+
+.status {
+ text-shadow: 0 0 0.25em black, 0 0 0.25em black, 0 0 0.25em black, 0 0 0.25em black;
+ font-size: xx-large;
+ color: white;
+}
+
+.guac-error .status {
+ text-shadow: 0 0 0.25em black, 0 0 0.25em black, 0 0 0.25em black, 0 0 0.25em black;
+ color: #D44;
+}
+
+p.hint {
+
+ border: 0.25em solid rgba(255, 255, 255, 0.25);
+ background: black;
+ opacity: 0.75;
+
+ color: white;
+
+ max-width: 10em;
+ padding: 1em;
+ margin: 1em;
+
+ position: absolute;
+ left: 0;
+ top: 0;
+
+ box-shadow: 0.25em 0.25em 0.25em rgba(0, 0, 0, 0.75);
+
+}
+
+#notificationArea {
+ position: fixed;
+ right: 0.5em;
+ bottom: 0.5em;
+ max-width: 25%;
+ min-width: 10em;
+}
+
+.notification {
+
+ font-size: 0.9em;
+
+ border: 1px solid rgba(255, 255, 255, 0.25);
+ background: black;
+ opacity: 0.9;
+
+ color: white;
+
+ padding: 0.5em;
+ margin: 1em;
+ overflow: hidden;
+
+ box-shadow: 0.25em 0.25em 0.25em rgba(0, 0, 0, 0.75);
+
+}
+
+.notification div {
+ display: inline-block;
+}
+
+.notification .title-bar {
+ display: block;
+ white-space: nowrap;
+ font-weight: bold;
+
+ border-bottom: 1px solid white;
+ padding-bottom: 0.5em;
+ margin-bottom: 0.5em;
+}
+
+.notification .title-bar * {
+ vertical-align: middle;
+}
+
+.notification .caption {
+ color: silver;
+}
+
+.notification .close {
+
+ background: url('../images/action-icons/guac-close.png');
+ background-size: 10px 10px;
+ -moz-background-size: 10px 10px;
+ -webkit-background-size: 10px 10px;
+ -khtml-background-size: 10px 10px;
+
+ width: 10px;
+ height: 10px;
+
+ float: right;
+ cursor: pointer;
+
+}
+
+ at keyframes progress {
+ from {background-position: 0px 0px;}
+ to {background-position: 64px 0px;}
+}
+
+ at -webkit-keyframes progress {
+ from {background-position: 0px 0px;}
+ to {background-position: 64px 0px;}
+}
+
+.download.notification .caption {
+ width: 100%;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.download.notification .progress,
+.download.notification .download {
+
+ margin-top: 1em;
+ margin-left: 0.75em;
+ padding: 0.25em;
+ min-width: 5em;
+
+ border: 1px solid gray;
+ border-radius: 0.2em;
+
+ text-align: center;
+ float: right;
+
+}
+
+.download.notification .progress {
+
+ background: #444 url('../images/progress.png');
+ background-size: 16px 16px;
+ -moz-background-size: 16px 16px;
+ -webkit-background-size: 16px 16px;
+ -khtml-background-size: 16px 16px;
+
+ animation-name: progress;
+ animation-duration: 2s;
+ animation-timing-function: linear;
+ animation-iteration-count: infinite;
+
+ -webkit-animation-name: progress;
+ -webkit-animation-duration: 2s;
+ -webkit-animation-timing-function: linear;
+ -webkit-animation-iteration-count: infinite;
+
+}
+
+.download.notification .download {
+ background: rgb(16, 87, 153);
+ cursor: pointer;
+}
+
+#preload {
+ visibility: hidden;
+ position: absolute;
+ left: 0;
+ right: 0;
+ width: 0;
+ height: 0;
+ overflow: hidden;
+}
\ No newline at end of file
diff --git a/guacamole/src/main/webapp/styles/keyboard.css b/guacamole/src/main/webapp/styles/keyboard.css
new file mode 100644
index 0000000..d2608cd
--- /dev/null
+++ b/guacamole/src/main/webapp/styles/keyboard.css
@@ -0,0 +1,150 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+.keyboard-container {
+ text-align: center;
+
+ position: fixed;
+ left: 0;
+ bottom: 0;
+ width: 100%;
+ margin: 0;
+ padding: 0;
+
+ border-top: 1px solid black;
+ background: #222;
+ opacity: 0.85;
+
+ z-index: 1;
+}
+
+.guac-keyboard {
+ display: inline-block;
+ width: 100%;
+
+ margin: 0;
+ padding: 0;
+ cursor: default;
+
+ text-align: left;
+ vertical-align: middle;
+}
+
+.guac-keyboard .guac-keyboard-key-container {
+ display: inline-block;
+}
+
+.guac-keyboard .guac-keyboard-key {
+ background: #444;
+ border: 1px outset #888;
+ -moz-border-radius: 0.1em;
+ -webkit-border-radius: 0.1em;
+ -khtml-border-radius: 0.1em;
+ border-radius: 0.1em;
+}
+
+.guac-keyboard .guac-keyboard-cap {
+ color: white;
+ font-family: sans-serif;
+ font-size: 50%;
+ font-weight: lighter;
+ text-align: center;
+ white-space: pre;
+}
+
+.guac-keyboard .guac-keyboard-key:hover {
+ cursor: pointer;
+}
+
+.guac-keyboard .guac-keyboard-key.highlight {
+ background: #666;
+ border-color: #666;
+}
+
+.guac-keyboard.guac-keyboard-modifier-shift .guac-keyboard-key.shift,
+.guac-keyboard.guac-keyboard-modifier-numsym .guac-keyboard-key.numsym {
+ background: #882;
+ border-color: #DD4;
+}
+
+.guac-keyboard.guac-keyboard-modifier-control .guac-keyboard-key.control,
+.guac-keyboard.guac-keyboard-modifier-numsym .guac-keyboard-key.numsym {
+ background: #882;
+ border-color: #DD4;
+}
+
+.guac-keyboard.guac-keyboard-modifier-alt .guac-keyboard-key.alt,
+.guac-keyboard.guac-keyboard-modifier-numsym .guac-keyboard-key.numsym {
+ background: #882;
+ border-color: #DD4;
+}
+
+.guac-keyboard.guac-keyboard-modifier-super .guac-keyboard-key.super,
+.guac-keyboard.guac-keyboard-modifier-numsym .guac-keyboard-key.numsym {
+ background: #882;
+ border-color: #DD4;
+}
+
+.guac-keyboard .guac-keyboard-key.guac-keyboard-pressed {
+ background: #822;
+ border-color: #D44;
+ border-style: inset;
+}
+
+.guac-keyboard .guac-keyboard-row {
+ line-height: 0;
+}
+
+.guac-keyboard .guac-keyboard-column {
+ display: inline-block;
+ text-align: center;
+ vertical-align: top;
+}
+
+.guac-keyboard .guac-keyboard-gap {
+ display: inline-block;
+}
+
+/* Hide keycaps requiring modifiers which are NOT currently active. */
+.guac-keyboard:not(.guac-keyboard-modifier-caps)
+.guac-keyboard-cap.guac-keyboard-requires-caps,
+
+.guac-keyboard:not(.guac-keyboard-modifier-numsym)
+.guac-keyboard-cap.guac-keyboard-requires-numsym,
+
+.guac-keyboard:not(.guac-keyboard-modifier-shift)
+.guac-keyboard-cap.guac-keyboard-requires-shift,
+
+/* Hide keycaps NOT requiring modifiers which ARE currently active, where that
+ modifier is used to determine which cap is displayed for the current key. */
+.guac-keyboard.guac-keyboard-modifier-shift
+.guac-keyboard-key.guac-keyboard-uses-shift
+.guac-keyboard-cap:not(.guac-keyboard-requires-shift),
+
+.guac-keyboard.guac-keyboard-modifier-numsym
+.guac-keyboard-key.guac-keyboard-uses-numsym
+.guac-keyboard-cap:not(.guac-keyboard-requires-numsym),
+
+.guac-keyboard.guac-keyboard-modifier-caps
+.guac-keyboard-key.guac-keyboard-uses-caps
+.guac-keyboard-cap:not(.guac-keyboard-requires-caps) {
+
+ display: none;
+
+}
diff --git a/guacamole/src/main/webapp/styles/login.css b/guacamole/src/main/webapp/styles/login.css
new file mode 100644
index 0000000..2927032
--- /dev/null
+++ b/guacamole/src/main/webapp/styles/login.css
@@ -0,0 +1,350 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+* {
+ -webkit-tap-highlight-color: rgba(0,0,0,0);
+}
+
+input[type=checkbox], input[type=text], textarea {
+ -webkit-tap-highlight-color: rgba(128,192,128,0.5);
+}
+
+input[type=submit], button {
+ -webkit-appearance: none;
+}
+
+body {
+ background: #EEE;
+ font-family: FreeSans, Helvetica, Arial, sans-serif;
+ padding: 0;
+ margin: 0;
+}
+
+#manage {
+ display: none;
+}
+
+.admin #manage {
+ display: inline-block;
+}
+
+div#login-ui {
+ height: 100%;
+ width: 100%;
+ position: fixed;
+ left: 0;
+ top: 0;
+ display: table;
+}
+
+p#login-error {
+ text-align: center;
+ background: #FDD;
+ color: red;
+ margin: 0.2em;
+}
+
+div#login-logo {
+ position: relative;
+ bottom: 0;
+ display: inline-block;
+ vertical-align: middle;
+}
+
+div#login-dialog-middle {
+ width: 100%;
+ display: table-cell;
+ vertical-align: middle;
+ text-align: center;
+}
+
+div#login-dialog {
+
+ max-width: 75%;
+ text-align: left;
+
+ display: inline-block;
+}
+
+div#login-dialog h1 {
+ margin-top: 0;
+ margin-bottom: 0em;
+ text-align: center;
+}
+
+div#login-dialog #buttons {
+ padding-top: 0.5em;
+ text-align: right;
+}
+
+div#login-dialog #buttons input,
+div#logout-panel button {
+
+ background: #8A6;
+ border: 1px solid rgba(0, 0, 0, 0.4);
+ -moz-border-radius: 0.6em;
+ -webkit-border-radius: 0.6em;
+ -khtml-border-radius: 0.6em;
+ border-radius: 0.6em;
+
+ color: white;
+ text-shadow: -1px -1px rgba(0, 0, 0, 0.3);
+ font-weight: bold;
+ font-size: 1.125em;
+
+ box-shadow: inset -1px -1px 0.25em rgba(0, 0, 0, 0.25),
+ inset 1px 1px 0.25em rgba(255, 255, 255, 0.25),
+ -1px -1px 0.25em rgba(0, 0, 0, 0.25),
+ 1px 1px 0.25em rgba(255, 255, 255, 0.25);
+
+ padding: 0.35em;
+ padding-right: 1em;
+ padding-left: 1em;
+ min-width: 5em;
+
+}
+
+div#login-dialog #buttons input:hover,
+div#logout-panel button:hover {
+ background: #9C7;
+}
+
+div#login-dialog #buttons input:active,
+div#logout-panel button:active {
+
+ padding-left: 1.1em;
+ padding-right: 0.9em;
+ padding-top: 0.45em;
+ padding-bottom: 0.25em;
+
+ box-shadow:
+ inset 1px 1px 0.25em rgba(0, 0, 0, 0.25),
+ -1px -1px 0.25em rgba(0, 0, 0, 0.25),
+ 1px 1px 0.25em rgba(255, 255, 255, 0.25);
+}
+
+div#login-dialog #login-fields {
+
+ vertical-align: middle;
+
+ padding: 1em;
+ background: #DDD;
+ border: 1px solid #999;
+ -moz-border-radius: 0.25em;
+ -webkit-border-radius: 0.25em;
+ -khtml-border-radius: 0.25em;
+ border-radius: 0.25em;
+
+}
+
+div#login-dialog th {
+ text-shadow: 1px 1px white;
+}
+
+div#login-dialog #login-fields input {
+ border: 1px solid #777;
+ -moz-border-radius: 0.2em;
+ -webkit-border-radius: 0.2em;
+ -khtml-border-radius: 0.2em;
+ border-radius: 0.2em;
+ width: 100%;
+}
+
+div#login-dialog #login-fields img.logo {
+ position: fixed;
+ margin: 10px;
+ left: 0;
+ bottom: 0;
+ opacity: 0.1;
+ z-index: -1;
+}
+
+div#version-dialog {
+ position: fixed;
+ right: 0;
+ bottom: 0;
+ text-align: right;
+
+ font-style: italic;
+ font-size: 0.75em;
+ color: black;
+ opacity: 0.5;
+
+ padding: 0.5em;
+}
+
+img {
+ border: none;
+}
+
+img#license {
+ float: right;
+ margin: 2px;
+}
+
+div#connection-list-ui h1 {
+
+ margin: 0;
+ padding: 0.5em;
+
+ font-size: 2em;
+ vertical-align: middle;
+ text-align: center;
+
+}
+
+div#connection-list-ui h2 {
+
+ padding: 0.5em;
+ margin: 0;
+ font-size: 1.5em;
+
+ font-weight: lighter;
+ text-shadow: 1px 1px white;
+
+ border-top: 1px solid #AAA;
+ border-bottom: 1px solid #AAA;
+ background: #DDD;
+
+}
+
+div#connection-list-ui img {
+ vertical-align: middle;
+}
+
+div#logout-panel {
+ padding: 0.45em;
+ text-align: right;
+ float: right;
+}
+
+.history-unavailable div#recent-connections {
+ display: none;
+}
+
+div#recent-connections,
+div#clipboardDiv,
+div#settings,
+div#all-connections {
+ margin: 1em;
+ padding: 0;
+}
+
+#all-connections .list-buttons {
+ text-align: center;
+ padding: 0;
+}
+
+div#recent-connections {
+ text-align: center;
+}
+
+#no-recent {
+
+ color: black;
+ text-shadow: 1px 1px white;
+ opacity: 0.5;
+
+ font-size: 2em;
+ font-weight: bolder;
+}
+
+div#recent-connections div.connection {
+ -moz-border-radius: 0.5em;
+ -webkit-border-radius: 0.5em;
+ -khtml-border-radius: 0.5em;
+ border-radius: 0.5em;
+ display: inline-block;
+ padding: 1em;
+ margin: 1em;
+ text-align: center;
+ max-width: 75%;
+ overflow: hidden;
+}
+
+.group,
+.connection {
+ cursor: pointer;
+}
+
+.connection:hover {
+ background: #CDA;
+}
+
+.group,
+.connection .name {
+ color: black;
+ font-weight: normal;
+ padding: 0.1em;
+}
+
+.connection .thumbnail {
+ margin: 0.5em;
+}
+
+.connection .thumbnail img {
+ border: 1px solid black;
+ box-shadow: 1px 1px 5px black;
+ max-width: 75%;
+}
+
+div#all-connections .connection {
+ display: block;
+ text-align: left;
+}
+
+div#recent-connections .connection .thumbnail {
+ display: block;
+}
+
+div#all-connections .connection {
+ padding: 0.1em;
+}
+
+div#recent-connections .protocol {
+ display: none;
+}
+
+.caption * {
+ vertical-align: middle;
+}
+
+.caption .name {
+ margin-left: 0.25em;
+}
+
+#clipboardDiv textarea {
+ width: 100%;
+ border: 1px solid #AAA;
+ -moz-border-radius: 0.25em;
+ -webkit-border-radius: 0.25em;
+ -khtml-border-radius: 0.25em;
+ border-radius: 0.25em;
+}
+
+#settings dt {
+ border-bottom: 1px dotted #AAA;
+ padding-bottom: 0.25em;
+}
+
+#settings dd {
+ margin: 1.5em;
+ margin-left: 2.5em;
+ font-size: 0.75em;
+}
\ No newline at end of file
diff --git a/guacamole/src/main/webapp/styles/ui.css b/guacamole/src/main/webapp/styles/ui.css
new file mode 100644
index 0000000..fe4f72f
--- /dev/null
+++ b/guacamole/src/main/webapp/styles/ui.css
@@ -0,0 +1,611 @@
+
+/*
+ * Guacamole - Clientless Remote Desktop
+ * Copyright (C) 2010 Michael Jumper
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+ at import url('animation.css');
+
+* {
+ -webkit-tap-highlight-color: rgba(0,0,0,0);
+}
+
+input[type=checkbox], input[type=number], input[type=text], textarea {
+ -webkit-tap-highlight-color: rgba(128,192,128,0.5);
+}
+
+input[type=submit], button {
+ -webkit-appearance: none;
+}
+
+div.location, input[type=text], input[type=number], input[type=password] {
+ border: 1px solid #777;
+ -moz-border-radius: 0.2em;
+ -webkit-border-radius: 0.2em;
+ -khtml-border-radius: 0.2em;
+ border-radius: 0.2em;
+ width: 100%;
+ padding: 0.25em;
+ font-size: 10pt;
+ background: white;
+ cursor: text;
+}
+
+button {
+
+ background: #8A6;
+ border: 1px solid rgba(0, 0, 0, 0.4);
+ -moz-border-radius: 0.6em;
+ -webkit-border-radius: 0.6em;
+ -khtml-border-radius: 0.6em;
+ border-radius: 0.6em;
+
+ color: white;
+ text-shadow: -1px -1px rgba(0, 0, 0, 0.3);
+ font-weight: bold;
+ font-size: 1.125em;
+
+ box-shadow: inset -1px -1px 0.25em rgba(0, 0, 0, 0.25),
+ inset 1px 1px 0.25em rgba(255, 255, 255, 0.25),
+ -1px -1px 0.25em rgba(0, 0, 0, 0.25),
+ 1px 1px 0.25em rgba(255, 255, 255, 0.25);
+
+ padding: 0.35em;
+ padding-right: 1em;
+ padding-left: 1em;
+ min-width: 5em;
+
+}
+
+button:hover {
+ background: #9C7;
+}
+
+button:active {
+
+ padding-left: 1.1em;
+ padding-right: 0.9em;
+ padding-top: 0.45em;
+ padding-bottom: 0.25em;
+
+ box-shadow:
+ inset 1px 1px 0.25em rgba(0, 0, 0, 0.25),
+ -1px -1px 0.25em rgba(0, 0, 0, 0.25),
+ 1px 1px 0.25em rgba(255, 255, 255, 0.25);
+}
+
+button.danger {
+ background: #A43;
+}
+
+button.danger:hover {
+ background: #C54;
+}
+
+body {
+ background: #EEE;
+ font-family: FreeSans, Helvetica, Arial, sans-serif;
+ padding: 0;
+ margin: 0;
+}
+
+img {
+ border: none;
+ vertical-align: middle;
+}
+
+div#version-dialog {
+ position: fixed;
+ right: 0;
+ bottom: 0;
+ text-align: right;
+
+ font-style: italic;
+ font-size: 0.75em;
+ color: black;
+ opacity: 0.5;
+
+ padding: 0.5em;
+}
+
+h1 {
+
+ margin: 0;
+ padding: 0.5em;
+
+ font-size: 2em;
+ vertical-align: middle;
+ text-align: center;
+
+}
+
+h2 {
+
+ border-top: 1px solid #AAA;
+ border-bottom: 1px solid #AAA;
+ background: rgba(0, 0, 0, 0.07);
+
+ padding: 0.5em;
+ margin: 0;
+ font-size: 1.5em;
+
+ font-weight: lighter;
+ text-shadow: 1px 1px white;
+
+}
+
+div.section {
+ margin: 0;
+ padding: 1em;
+}
+
+/*
+ * Dialogs
+ */
+
+.dialog-container {
+ position: fixed;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ right: 0;
+ background: rgba(0, 0, 0, 0.5);
+ padding: 1em;
+}
+
+.dialog {
+
+ max-width: 100%;
+ width: 8in;
+ margin-left: auto;
+ margin-right: auto;
+ max-height: 100%;
+ overflow: auto;
+
+ border: 1px solid rgba(0, 0, 0, 0.5);
+ background: #E7E7E7;
+
+ -moz-border-radius: 0.2em;
+ -webkit-border-radius: 0.2em;
+ -khtml-border-radius: 0.2em;
+ border-radius: 0.2em;
+
+ box-shadow: 0.1em 0.1em 0.2em rgba(0, 0, 0, 0.6);
+
+}
+
+.dialog > * {
+ margin: 1em;
+}
+
+.dialog .header {
+ margin: 0;
+}
+
+.dialog td {
+ position: relative;
+}
+
+.dialog .overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ right: 0;
+ z-index: 1;
+}
+
+.dialog .dropdown {
+
+ position: absolute;
+ z-index: 2;
+ margin-top: -1px;
+
+ width: 3in;
+ max-height: 2in;
+ overflow: auto;
+
+ border: 1px solid rgba(0, 0, 0, 0.5);
+ background: white;
+
+ font-size: 10pt;
+
+}
+
+.dialog .footer {
+ text-align: center;
+}
+
+/*
+ * List elements
+ */
+
+.list-item {
+
+ display: block;
+ text-align: left;
+ cursor: pointer;
+
+ position: relative;
+
+}
+
+.icon {
+ width: 24px;
+ height: 24px;
+ background-size: 16px 16px;
+ -moz-background-size: 16px 16px;
+ -webkit-background-size: 16px 16px;
+ -khtml-background-size: 16px 16px;
+ background-repeat: no-repeat;
+ background-position: center center;
+ opacity: 0.5;
+ display: inline-block;
+ vertical-align: middle;
+}
+
+.list-item * {
+ vertical-align: middle;
+}
+
+.list-item .caption {
+ padding: 0.1em;
+}
+
+.list-item .name {
+ color: black;
+ font-weight: normal;
+ padding: 0.1em;
+ margin-left: 0.25em;
+}
+
+.list-item .usage {
+ float: right;
+ font-style: italic;
+ color: gray;
+}
+
+.list-item.in-use {
+ opacity: 0.5;
+}
+
+.choice .list-item .usage {
+ display: none;
+}
+
+.choice .list-item.in-use {
+ opacity: 1;
+}
+
+/*
+ * List element styling
+ */
+
+.list-item.selected {
+ background: #DEB;
+}
+
+.list-item.selected > .icon {
+ opacity: 1.0;
+}
+
+.list-item:not(.selected) .caption:hover {
+ background: #CDA;
+}
+
+.choice .list-item {
+ display: inline-block;
+}
+
+.choice input[type='checkbox'] {
+ vertical-align: top;
+ height: 24px;
+ padding: 0;
+ margin: 0;
+}
+
+.disabled .list-item:not(.selected) {
+ opacity: 0.25;
+}
+
+.disabled .list-item:not(.selected):hover {
+ background: inherit;
+}
+
+/*
+ * List element fields (editing)
+ */
+
+/*
+.form {
+
+ position: absolute;
+ display: inline-block;
+ vertical-align: middle;
+ z-index: 1;
+
+ border: 1px solid rgba(0, 0, 0, 0.5);
+ background: #E7E7E7;
+ padding: 0;
+ margin: 0.25em;
+
+ -moz-border-radius: 0.2em;
+ -webkit-border-radius: 0.2em;
+ -khtml-border-radius: 0.2em;
+ border-radius: 0.2em;
+
+ box-shadow: 0.1em 0.1em 0.2em rgba(0, 0, 0, 0.6);
+
+}
+*/
+
+.form .fields th,
+.form .permissions th {
+ font-weight: normal;
+ vertical-align: middle;
+ text-align: left;
+}
+
+.form h2 {
+ border-top: none;
+}
+
+.form h3 {
+ font-size: 1em;
+ margin-bottom: 0.25em;
+}
+
+.form {
+ cursor: auto;
+ animation-name: fadein;
+ -webkit-animation-name: fadein;
+ animation-duration: 0.125s;
+ -webkit-animation-duration: 0.125s;
+}
+
+.object-buttons {
+
+ text-align: right;
+
+ border-top: 1px solid rgba(0, 0, 0, 0.1);
+ padding-top: 0.5em;
+ margin: 0.5em;
+
+}
+
+/*
+ * List element icons
+ */
+
+.icon.user {
+ background-image: url('../images/user-icons/guac-user.png');
+}
+
+.icon.user.add {
+ background-image: url('../images/action-icons/guac-user-add.png');
+}
+
+.icon.connection {
+ background-image: url('../images/protocol-icons/guac-plug.png');
+}
+
+.icon.connection.add {
+ background-image: url('../images/action-icons/guac-monitor-add.png');
+}
+
+.protocol {
+ display: inline-block;
+}
+
+.protocol .icon {
+ width: 24px;
+ height: 24px;
+ background-image: url('../images/protocol-icons/guac-plug.png');
+ background-size: 16px 16px;
+ -moz-background-size: 16px 16px;
+ -webkit-background-size: 16px 16px;
+ -khtml-background-size: 16px 16px;
+ background-repeat: no-repeat;
+ background-position: center center;
+ opacity: 0.5;
+}
+
+.protocol .icon.ssh {
+ background-image: url('../images/protocol-icons/guac-text.png');
+}
+
+.protocol .icon.vnc,
+.protocol .icon.rdp {
+ background-image: url('../images/protocol-icons/guac-monitor.png');
+}
+
+.connection .thumbnail {
+ display: none;
+}
+
+/*
+ * Groups
+ */
+
+.group > .children {
+ margin-left: 13px;
+ padding-left: 6px;
+ display: none;
+}
+
+.group.expanded > .children {
+ display: block;
+ border-left: 1px dotted rgba(0, 0, 0, 0.25);
+}
+
+.group > .caption .icon.type {
+ display: none;
+}
+
+.group.balancer > .caption .icon.type {
+ display: inline-block;
+ background-image: url('../images/protocol-icons/guac-monitor.png');
+}
+
+.group > .caption .icon.group {
+ opacity: 0.75;
+ background-image: url('../images/group-icons/guac-closed.png');
+}
+
+.group.expanded > .caption .icon.group {
+ background-image: url('../images/group-icons/guac-open.png');
+}
+
+.group.empty > .caption .icon.group {
+ opacity: 0.25;
+ background-image: url('../images/group-icons/guac-open.png');
+}
+
+.group.empty.balancer > .caption .icon.group {
+ display: none;
+}
+
+/*
+ * Settings formatting
+ */
+
+.form dt,
+.settings dt {
+ border-bottom: 1px dotted #AAA;
+ padding-bottom: 0.25em;
+}
+
+.form dd,
+.settings dd {
+ margin: 1.5em;
+ margin-left: 2.5em;
+ font-size: 0.75em;
+}
+
+#connections input.name,
+#users input.name {
+ max-width: 80%;
+ width: 20em;
+}
+
+#connection-list,
+#user-list {
+ border: 1px solid rgba(0, 0, 0, 0.25);
+ min-height: 20em;
+ -moz-border-radius: 0.2em;
+ -webkit-border-radius: 0.2em;
+ -khtml-border-radius: 0.2em;
+ border-radius: 0.2em;
+}
+
+#connections #add-connection,
+#connections #add-connection-group,
+#users #add-user {
+ font-size: 0.8em;
+}
+
+#connection-add-form,
+#user-add-form {
+ margin: 0.5em;
+}
+
+body:not(.manage-connections) .require-manage-connections,
+body:not(.manage-users) .require-manage-users {
+ display: none;
+}
+
+body:not(.add-connections) #add-connection,
+body:not(.add-connection-groups) #add-connection-group,
+body:not(.add-users) #user-add-form {
+ display: none;
+ display: none;
+}
+
+div#logout-panel {
+ padding: 0.45em;
+ text-align: right;
+ float: right;
+}
+
+.history th,
+.history td {
+ padding-left: 1em;
+ padding-right: 1em;
+}
+
+.first-page,
+.prev-page,
+.set-page,
+.next-page,
+.last-page {
+ cursor: pointer;
+ vertical-align: middle;
+}
+
+.first-page.disabled,
+.prev-page.disabled,
+.set-page.disabled,
+.next-page.disabled,
+.last-page.disabled {
+ cursor: auto;
+ opacity: 0.25;
+}
+
+.set-page,
+.more-pages {
+ display: inline-block;
+ padding: 0.25em;
+ text-align: center;
+ min-width: 1.25em;
+}
+
+.set-page {
+ text-decoration: underline;
+}
+
+.set-page.current {
+ cursor: auto;
+ text-decoration: none;
+ font-weight: bold;
+ background: rgba(0, 0, 0, 0.1);
+ border: 1px solid rgba(0, 0, 0, 0.1);
+ -moz-border-radius: 0.2em;
+ -webkit-border-radius: 0.2em;
+ -khtml-border-radius: 0.2em;
+ border-radius: 0.2em;
+}
+
+.icon.first-page {
+ background-image: url('../images/action-icons/guac-first-page.png');
+}
+
+.icon.prev-page {
+ background-image: url('../images/action-icons/guac-prev-page.png');
+}
+
+.icon.next-page {
+ background-image: url('../images/action-icons/guac-next-page.png');
+}
+
+.icon.last-page {
+ background-image: url('../images/action-icons/guac-last-page.png');
+}
+
+.buttons,
+.list-pager-buttons {
+ text-align: center;
+ margin: 1em;
+}
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..8e47164
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,65 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.glyptodon.guacamole</groupId>
+ <artifactId>guacamole-client</artifactId>
+ <packaging>pom</packaging>
+ <version>0.8.3</version>
+ <name>guacamole-client</name>
+ <url>http://guac-dev.org/</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <modules>
+
+ <!-- Guacamole web application -->
+ <module>guacamole</module>
+
+ <!-- Guacamole Java API -->
+ <module>guacamole-common</module>
+
+ <!-- Guacamole webapp extension API -->
+ <module>guacamole-ext</module>
+
+ <!-- Guacamole JavaScript API -->
+ <module>guacamole-common-js</module>
+
+ </modules>
+
+ <build>
+ <plugins>
+
+ <!-- Assembly plugin - for easy distribution -->
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.4</version>
+
+ <!-- Build project archive -->
+ <configuration>
+ <finalName>${project.artifactId}-${project.version}</finalName>
+ <appendAssemblyId>false</appendAssemblyId>
+ <descriptors>
+ <descriptor>project-assembly.xml</descriptor>
+ </descriptors>
+ </configuration>
+
+ <!-- Bind archive build to package phase -->
+ <executions>
+ <execution>
+ <id>make-source-archive</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+
+ </plugin>
+
+ </plugins>
+ </build>
+
+</project>
diff --git a/project-assembly.xml b/project-assembly.xml
new file mode 100644
index 0000000..ec1d724
--- /dev/null
+++ b/project-assembly.xml
@@ -0,0 +1,24 @@
+<assembly
+ xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0
+ http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+
+ <id>project</id>
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+
+ <fileSets>
+ <fileSet>
+ <directory>${project.basedir}</directory>
+ <outputDirectory>/</outputDirectory>
+ <useDefaultExcludes>true</useDefaultExcludes>
+ <excludes>
+ <exclude>**/*.log</exclude>
+ <exclude>**/${project.build.directory}/**</exclude>
+ </excludes>
+ </fileSet>
+ </fileSets>
+
+</assembly>
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-edu/pkg-team/guacamole-client.git
More information about the debian-edu-commits
mailing list