guacamole chapter 14

4
 Chapter 14. guacamole-common The Java API provided by the Guacamole project is called guacamole-common. It provides a basic means of tunneling data between the JavaScript client provided by guacamole-common-js and the native proxy daemon, guacd. There are other classes provided as well which make dealing with the Guacamole protocol and reading from guacamole.properties  easier, but in general, the purpose of this library is to facilitate the creation of custom tunnels between the JavaScript client and guacd. HTTP tunnel The Guacamole Java API implements the HTTP tunnel using a servlet called GuacamoleHTTPTunnelServlet . This servlet handles all requests coming to it over HTTP from the JavaScript client, and translated them into connect, read, or write requests, which each get dispatched to the doConnect() , doRead() , and doWrite() functions accordingly. Normally, you wouldn't touch the doRead()  and doWrite() functions, as these have already been written to properly handle the requests of the JavaScript tunnel, and if you feel the need to touch these functions, you are probably better off writing your own tunnel implementation, although such a thing is difficult to do in a performant way. When developing an application based on the Guacamole API, you should use GuacamoleHTTPTunnelServlet  by extending it, implementing your own version of doConnect() , which is the only abstract function it defines. The tutorial later in this book demonstrating how to write a Guacamole- based web application shows the basics of doing this, but generally, doConnect()  is an excellent place for authentication or other validation, as it is the responsibility of doConnect()  to create (or not create) the actual tunnel. If doConnect()  does not create the tunnel, communication between the JavaScript client and guacd cannot take place, which is an ideal power to have as an authenticator. The doConnect() function is expected to "attach" a GuacamoleTunnel  to the web session, abstracted by GuacamoleSession . Attaching a tunnel to the session allows future tunnel requests to retrieve the same tunnel and use it, thus allowing one tunnel to be split across multiple requests. Assuming the doConnect() function successfully creates the tunnel, it must then return the created tunnel. The already-implemented parts of GuacamoleHTTPTunnelServlet  then return the unique identifier of this tunnel to the JavaScript client, allowing its own tunnel implementation to continue to communicate with the tunnel existing on the Java side. Instances of GuacamoleTunnel  are created associated with a GuacamoleSocket , which is the abstract interface surrounding the low-level connection to guacd. Overall, there is a socket ( GuacamoleSocket ) which provides a TCP connection to guacd. This socket is exposed to GuacamoleTunnel , which provides abstract protocol access around what is actually (but secretly, through the abstraction of the API) a TCP socket. The GuacamoleSession  allows instances of GuacamoleTunnel  to be shared across requests, and GuacamoleHTTPTunnelServlet  pulls these tunnels from the session as necessary to fulfill requests made by the JavaScript client. The Guacamole web application extends this tunnel servlet in order to implement authentication at the lowest possible level, effectively prohibiting communication between the client and any remote desktops unless they have properly authenticated. Your own implementation can be considerably simpler, especially if you don't need authentication: public class MyGuacamoleTunnelServlet  extends GuacamoleHTTP TunnelServlet {  @Override  protected GuacamoleTunn el doConnect(Http ServletRequest request)  throws GuacamoleExcep tion {

Upload: huynhtran

Post on 05-Nov-2015

212 views

Category:

Documents


0 download

DESCRIPTION

free

TRANSCRIPT

  • 12/6/2015 Chapter14.guacamolecommon

    http://guacdev.org/doc/gug/guacamolecommon.html 1/4

    Chapter14.guacamolecommonTheJavaAPIprovidedbytheGuacamoleprojectiscalledguacamolecommon.Itprovidesabasicmeansoftunneling data between the JavaScript client provided by guacamolecommonjs and the native proxydaemon,guacd.ThereareotherclassesprovidedaswellwhichmakedealingwiththeGuacamoleprotocolandreadingfromguacamole.propertieseasier,butingeneral,thepurposeofthislibraryistofacilitatethecreationofcustomtunnelsbetweentheJavaScriptclientandguacd.

    HTTPtunnelThe Guacamole Java API implements the HTTP tunnel using a servlet calledGuacamoleHTTPTunnelServlet. This servlet handles all requests coming to it over HTTP from theJavaScriptclient,andtranslatedthemintoconnect,read,orwriterequests,whicheachgetdispatchedtothedoConnect(),doRead(),anddoWrite()functionsaccordingly.

    Normally,youwouldn'ttouchthedoRead()anddoWrite()functions,asthesehavealreadybeenwrittentoproperlyhandletherequestsoftheJavaScripttunnel,andifyoufeeltheneedtotouchthesefunctions,youareprobablybetteroffwritingyourown tunnel implementation,althoughsucha thing isdifficult todo inaperformantway.

    When developing an application based on the Guacamole API, you should useGuacamoleHTTPTunnelServletbyextending it, implementing your own version ofdoConnect(), which istheonlyabstractfunctionitdefines.ThetutoriallaterinthisbookdemonstratinghowtowriteaGuacamolebasedwebapplicationshowsthebasicsofdoingthis,butgenerally,doConnect() isanexcellentplaceforauthenticationorothervalidation,asitistheresponsibilityofdoConnect()tocreate(ornotcreate)theactualtunnel.IfdoConnect()doesnotcreatethetunnel,communicationbetweentheJavaScriptclientandguacdcannottakeplace,whichisanidealpowertohaveasanauthenticator.

    ThedoConnect() function is expected to "attach" aGuacamoleTunnel to theweb session, abstracted byGuacamoleSession. Attaching a tunnel to the session allows future tunnel requests to retrieve the sametunnelanduseit,thusallowingonetunneltobesplitacrossmultiplerequests.AssumingthedoConnect()function successfully creates the tunnel, it must then return the created tunnel. The alreadyimplementedparts of GuacamoleHTTPTunnelServlet then return the unique identifier of this tunnel to the JavaScriptclient,allowingitsowntunnelimplementationtocontinuetocommunicatewiththetunnelexistingontheJavaside.

    Instances of GuacamoleTunnel are created associated with a GuacamoleSocket, which is the abstractinterfacesurroundingthelowlevelconnectiontoguacd.Overall,thereisasocket(GuacamoleSocket)whichprovidesaTCPconnectiontoguacd.ThissocketisexposedtoGuacamoleTunnel,whichprovidesabstractprotocolaccessaroundwhatisactually(butsecretly,throughtheabstractionoftheAPI)aTCPsocket.TheGuacamoleSession allows instances of GuacamoleTunnel to be shared across requests, andGuacamoleHTTPTunnelServletpullsthesetunnelsfromthesessionasnecessarytofulfillrequestsmadebytheJavaScriptclient.

    TheGuacamolewebapplicationextendsthistunnelservletinordertoimplementauthenticationatthelowestpossiblelevel,effectivelyprohibitingcommunicationbetweentheclientandanyremotedesktopsunlesstheyhaveproperlyauthenticated.Yourown implementationcanbeconsiderablysimpler,especially if youdon'tneedauthentication:

    publicclassMyGuacamoleTunnelServletextendsGuacamoleHTTPTunnelServlet{

    @OverrideprotectedGuacamoleTunneldoConnect(HttpServletRequestrequest)throwsGuacamoleException{

  • 12/6/2015 Chapter14.guacamolecommon

    http://guacdev.org/doc/gug/guacamolecommon.html 2/4

    //Connecttoguacdhere(thisisaSTUB)GuacamoleSocketsocket;

    //EstablishthetunnelusingtheconnectedsocketGuacamoleTunneltunnel=newGuacamoleTunnel(socket);

    //AttachtunneltosessionGuacamoleSessionsession=newGuacamoleSession(httpSession);session.attachTunnel(tunnel);

    //Returnpreattachedtunnelreturntunnel;

    }

    }

    UsingtheGuacamoleprotocolguacamolecommonprovidesbasic lowlevelsupport for theGuacamoleprotocol.This lowlevelsupport isleveraged by the HTTP tunnel implementation to satisfy the requirements of the JavaScript clientimplementation,astheJavaScriptclientexpectsthehandshakeproceduretohavealreadytakenplace.Thissupport exists through the GuacamoleReader and GuacamoleWriter classes, which are similar to Java'sReaderandWriterclasses,exceptthattheydealwith theGuacamoleprotocolspecifically,andthushaveslightlydifferentcontracts.

    GuacamoleReader

    GuacamoleReaderprovidesaverybasicread() functionwhichisrequiredtoreturnoneormorecompleteinstructions inachar array. It also provides the typicalavailable() function,which informs youwhetherread() is likely to block the next time it is called, and an even more abstract version of read() calledreadInstruction() which returns one instruction at a time, wrapped within a GuacamoleInstructioninstance.

    Normally, you would not need to use this class yourself. It is used by ConfiguredGuacamoleSocket tocomplete theGuacamoleprotocolhandshakeprocedure,and it isusedbyGuacamoleHTTPTunnelServletwithindoRead()toimplementthereadinghalfofthetunnel.

    The only concrete implementation ofGuacamoleReader isReaderGuacamoleReader, which wraps a JavaReader, using that as the source for data to parse into Guacamole instructions. Again, you would notnormallydirectlyusethisclass,norinstantiateityourself.Aworking,concreteinstanceofGuacamoleReadercanberetrievedfromanyGuacamoleSocketorGuacamoleTunnel.

    GuacamoleWriter

    GuacamoleWriter provides a very basic write() function and a more abstract version calledwriteInstruction()whichwritesinstancesofGuacamoleInstruction.Thesefunctionsareanalogoustotheread()andreadInstruction()functionsprovidedbyGuacamoleReader,andhavesimilarrestrictions:thecontractimposedbywrite()requiresthatwritteninstructionsbecomplete

    The only concrete implementation ofGuacamoleWriter isWriterGuacamoleWriter, which wraps a JavaWriter,usingthatasthedestinationforGuacamoleinstructiondata,butyouwouldnotnormallydirectlyusethisclass,norinstantiateityourself.ItisusedbyConfiguredGuacamoleSockettocompletetheGuacamoleprotocol handshake procedure, and it is used by GuacamoleHTTPTunnelServlet within doWrite() toimplementthewritinghalfofthetunnel.

    Ifnecessary,aGuacamoleWritercanberetrievedfromanyGuacamoleSocketorGuacamoleTunnel,butinmostcases,theclassesprovidedbytheGuacamoleJavaAPIwhichalreadyuseGuacamoleWriterwillbesufficient.

  • 12/6/2015 Chapter14.guacamolecommon

    http://guacdev.org/doc/gug/guacamolecommon.html 3/4

    ReadingpropertiesThe Guacamole Java API provides simple access to guacamole.properties for convenience, althoughsuchsupportisnotstrictlyrequired.ThissupportisprovidedthroughtheGuacamoleProperiesutilityclass,which cannot be instantiated and provides two simple property retrieval functions: getProperty() andgetRequiredProperty(), thedifferencebeingthat the formercanreturnnull ifaproperty isnotdefined,whilethelatterwillthrowanexceptioninstead.ThesefunctionsaregenericandtypesafeandwillreturnthecorrectJavaclassortypewhengivenaninstanceofaproperty.

    InGuacamole,eachpropertyisdeclaredasanimplementationofGuacamoleProperty,andmustprovideanimplementation of getName(), which returns the name of the property as it should exist withinguacamole.properties,andparseValue(),whichisgiventheStringvalueofthepropertyasreadfromguacamole.properties,andmust return thedeclared typeof theGuacamoleProperty implementation. Agood example of how this works is the IntegerGuacamoleProperty implementation included withinguacamolecommon:

    publicabstractclassIntegerGuacamolePropertyimplementsGuacamoleProperty{

    @OverridepublicIntegerparseValue(Stringvalue)throwsGuacamoleException{

    //Ifnopropertyprovided,returnnull.if(value==null)returnnull;

    try{Integerinteger=newInteger(value);returninteger;}catch(NumberFormatExceptione){thrownewGuacamoleServerException("Property\""+getName()+"\"mustbeaninteger.",e);}

    }

    }

    Notice that this implementation does not actually provide getName(). Instead, it only implementsparseValue(),theintentbeingtomakeotherdevelopers'liveseasierwhentheyneedtoretrieveanintegerpropertyfromguacamole.properties.Usingthisclass,retrievinganintegerpropertyissimple:

    publicclassMyClass{

    publicstaticfinalIntegerGuacamolePropertyIMPORTANT_INT=newIntegerGuacamoleProperty(){

    @OverridepublicStringgetName(){return"importantint";}

    };

    }

    ...lateronwithinMyClass...

    intimportant=GuacamoleProperties.getRequiredProperty(IMPORTANT_INT);

  • 12/6/2015 Chapter14.guacamolecommon

    http://guacdev.org/doc/gug/guacamolecommon.html 4/4

    guacamolecommonprovidesacoupleofsimilarclassesforretrievingcommontypesofproperties,suchasaString orFile, and implementing your own to facilitate properties that parse into arrays or aList, etc.shouldbereasonablysimple.