ws programming tutorial

Upload: pnavadhani

Post on 10-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Ws Programming Tutorial

    1/53

    NORDUGRID

    NORDUGRID-MANUAL-94/5/2009

    Web Service programming Tutorial

    This document is still under development, but dont hesitate sending your comments and suggestions to

    [email protected].

    Michael Glodek , Steffen Moller

    [email protected]

  • 8/8/2019 Ws Programming Tutorial

    2/53

    2

  • 8/8/2019 Ws Programming Tutorial

    3/53

    Contents

    1 Introduction 51.1 Hosting Environment Daemon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    1.1.1 The ARC Echo Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    2 The Time Web Service 92.1 Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2 Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    3 Web Services Description Language 153.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    3.2 How to prepare a WSDL document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.2.1 Preparation of the Echo WSDL le with Eclipse . . . . . . . . . . . . . . . . . . . . . 163.2.2 Inspection of Web Services with Taverna . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    3.3 What else to do with WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    4 The Echo Web Service 214.1 Description with WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.2 Implementation of the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    4.2.1 Communication with SOAP: The SOAP Fault Message . . . . . . . . . . . . . . . . . 224.2.2 The Service in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    4.3 Implementation of the Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.3.1 The Client in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    5 The TLS Echo Web Service 295.1 Transport Layer Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295.2 Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335.3 Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    6 Secure Echo Web Service 396.1 Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406.2 Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    7 Appendix 477.1 Useful tutorials and documentations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477.2 Important XSD les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    3

  • 8/8/2019 Ws Programming Tutorial

    4/53

    Contents

    4

  • 8/8/2019 Ws Programming Tutorial

    5/53

    1 Introduction

    This document gently introduces to the preparation of standalone Web Services and cognated clients withthe Advance Resource Connector (ARC). The reader is guided through a series of practically orientedexamples. Each is accompanied by explanations of the main concepts of the software architecture. Noparticular skills are required to follow the presented steps. It is however benecial to have some basiccomprehension of the programming language C++, the le format XML and any regular UNIX shell.To start, the user shall have an installation of ARC-1, as it is performed with current RPM or .deb packages .

    The ARC server provides access to services. These are executed on the same machine that the server isinstalled on. Some services, like the A-REX service, will delegate computational efforts to other machinesvia additional software like a local queueing system. But the A-REX service itself does not migrate away

    to other machines - at least this has not been implemented yet. Services may comprise computational tasks(e.g., some secret and strongly patented algorithm), allow arbitrary computations (like ARCs A-REX orAmazons clouds) or provide access to other resources like a particular database or to arbitrary disk space(like ARCs hopi or bartender).

    Services are invoked using software programs, which are referred to as clients. These programs may directlyperform the interactions of human users or request a performance of other services of another server (herethe rst service is in the role of a client, too). The tasks of servers and clients are well dened. If servers arenot busy reacting to a clients request, then they are waiting. The task of servers can be subdivided into:

    Wait for client request Receive the request Perform the desired service Create a response for the client Send response to the client Wait for next client request

    While the server waits passively for a request, the client acts actively: Create a request Transmit the request to the server which provides the desired service. Wait for the reply Receive the response from the server.

    Servers provide access to a single or a set of services. In ARC services are provided by the HostingEnvironment Demon (HED) which enables the installation of several services on one network access point.

    In general, the implementation of a client is easier than the implementation of the server. ARC is designedas a middleware which encapsulates typical challenges of server-client infrastructures (security, exceptionhandling, extensibility) and abstracts from the underlying computer architecture (heterogeneity of comput-ers, computer location, protocols). The core of ARC is the prior mentioned HED (Hosting EnvironmentDaemon). To the administrator HED is mostly visible as the single binary that is started and conguredby a le that describes services that shall be prepared by HED. Conceptionally, the HED determines howservices shall be organised both as a principle, and for any given ARC-run server. HED determines the very

    explicit presence or absence of a service at a particular address. Its many congurable layers are describedlater in this tutorial. At the time of writing, the endpoint of the HED will be a SOAP based Web Service.see http://wiki.nordugrid.org for explicit instructions for setup

    5

  • 8/8/2019 Ws Programming Tutorial

    6/53

    1 Introduction

    SOAP is a long established XML-based standard for Web Service communication. ARC abstracts from thisformat, but nevertheless it is useful to be aware of the underlying message transport mechanism.

    1.1 Hosting Environment Daemon

    The HED which was already mentioned in the section above is an essential part of the ARC middleware. Itstask is to provide the hosting of various services at the application level and is based on the idea modularity.The HED consists of components called Message Chain Components (MCC), Plexer, Services, and severalmodules, which shall aid the programmer to simplify the development of the Web Services: Cong, Loader,Logging, XMLNode et cetera. The MCCs are ordered within a layered structure. Each MCC providesa certain functionality such as communication between two applications (MCC TCP), secure data transfer(MCC TLS) or client-server architecture (MCC HTTP). Figure 1.1 illustrates a typical setup of a server-sidedHED.

    Figure 1.1: Example of a HED structure providing a Web Service The HED consists of several layers whichare connected with each other. The arrow indicate the message ow of the used conguration. TheMCCs and Services may hold a SecHandler in order to give additional security. Additional modules (onthe left) are used within the HED.

    The MCCs are connected which each other and passing incoming and outgoing message to the upperor the respective lower layer. In case of outgoing messages a MCC is wrapping the data of the upperlayer as a payload into their own protocol (while incomming message will be unwrapped). The lowestlayer has to be a transport protocol like TCP which enables the transmission between two applications.Technically there are even lower layers required needed for the communication but they are already realisedwithin the operating system and the network card. TCP is well suited for the application because itprovides a reliable and ordered delivery of a byte stream. Above the TCP layer is the Hypertext TransferProtocol (HTTP). In case a security layer is desired (i.e. for authentication), the TLS (Transport LayerSecurity formerly known as SSL, Secure Sockets Layer) has to be inserted between the TCP and HTTPlayers. The HTTP provides the client-server architecture. It is stateless but offers several extensionsfor requests, header information and status codes. Furthermore HTTP enables the usage of UniformResource Locators (URL) which is used by ARC to multiplex between different services. The multiplex-ing layer can also be dened within the HED and is called Plexer. Depending on the path of the URL

    the Plexer passes messages to a dened SOAP service which again passes the message to the Web Service [1].

    The structure of the HED can be congured freely by modifying the server conguration le. A rst

    6

  • 8/8/2019 Ws Programming Tutorial

    7/53

    1.1 Hosting Environment Daemon

    impression how the HED can be congured shall be given in the following example which corresponds to theHED shown in Figure 1.1. It uses the ARC echo service that is shipped for testing purposes with the ARCsource code.

    1.1.1 The ARC Echo Web Service

    The rst example shall give a basic understanding in how to congure the HED for setting up a novelservice. The task is to setup the regular ARC Echo Web Service. On the command line, all that needsto be done is to invoke the arched daemon with a suitable server conguration le. Such a tting serverconguration le is shown in Listing 1.1. It is written in XML. Its structure is based on the XSD schemalisted in 7.2 in Listing 7.1.

    Listing 1.1: HED conguration le.

    1 2 3 4 5 /var / run/arched.pid6 /var/ log/arched. log7 8 9

    10 /usr / l ib/arc/11 12 13 mcctcp14 mcct ls15 mcchttp16 mccsoap17 echo18 19 20 21

    22 6000023 24 25 POST26 27 28 29 30 31 ^/Echo $ 32 33 34 [ 35 ]36 37 38

    The rst line of the XML le contains the XML declaration. Several attributes can be dened here but atleast the XML version should be specied. The conguration as a whole is encapsulated by the elementArcCong . It also performs the setting of namespaces, which are expected to be mostly invariant across allserver installations. The Server element, to be found at line 4, provides basic settings for the daemon suchas the location of the Pid-le or ofthe Log-le. The ModuleManager holds the path to the plugin libraries.Several paths may be dened here. Due to the fact that the rst library matching the plugin name is loaded,the order is relevant. The path should be at least assigned to the ARC installation directory. Otherwise,the set of ARC MCC plugins might not be found. The next elements are holding the name of the pluginsto be loaded (line 13). The names have to correspond to the names of the dynamic libraries within the pathdened in the ModuleManager . Finally, the chain, which creates the layered structure, is declared withinthe element Chain . It is composed of the elements Component , Plexer and Service . Due to a MCC pluginmay contain several components, one has to specify more exact which one to load. This is to be done usingthe name attribute i.e. the plugin mcchttp realises two components: http.service and http.client . Since weare dening a conguration le for a service, the http.service should be used. Furthermore the elements

    7

  • 8/8/2019 Ws Programming Tutorial

    8/53

    1 Introduction

    may have the attribute id as a unique identier within the le. Regarding the components and the servicesa plugin (implemented as a *.so le that is searched in the paths previously specied) has to be loadedwhich provides the implementation of its functionality. The further conguration depends on the pluginsindividual functionality.

    A Chain will determine the path that an event takes to be noticed. The rst component of the chain isthe tcp.service . As to be seen, the port 60000 is assigned to the server to listen to. The port can be anarbitrary number. However, the number 60000 is commonly used for a HED providing the A-REX WebService (the one organising the computation on a site) and the number 50000 is found commonly used fora HED running Web Services for storage. This way, one can organise a single server to offer multiple HEDinstances. The stream which is received by this component is passed to the component dened by the next attribute. In the present case, it will be passed to the component with the id attribute named http . In thisway, the message is be passed to higher layers until it reaches the Plexer . Depending on the path of theURL which was demanded by the HTTP, the Plexer multiplexes the request to the right Web Service Theplexer will thus allow to have multiple Web Service listen to the same port. The path, declared within thenext attribute, corresponds to a regular expression and leads to the service with the id named echo. Hence,the service will now be reachable under URL http://localhost:60000/echo . It will nally process the messageand create a new message which will be returned all the way back to the TCP component. The Echo WebService itself is provided by the ARC package. Additional invariant parameters are passed by the elementsprex and suffix . They set the characters which will enclose the echoed string.

    To create the daemon corresponding to the dened server conguration le, ARC provides the programcalled arched . The manner of invokation is to been seen in Listing 1.2.

    Listing 1.2: Invokation of the Arched Daemon. hmf

    $ a rched - c a rcecho_no_ss l . xml && echo Daemon s t ar t ed | | e cho Daemon fa il edDaemon star ted

    $

    The name of the program is followed by the parameter -c. The string following that argument contains thepath to the conguration le. Once the server is running, the client can be used as described in Listing 1.3.

    Listing 1.3: Usage of the Arc echo client. hmf

    $ arcecho ht tp: / / localhost :60000/Echo text[ t ex t ]

    In this example, the server and the client are running on the same computer such that the hostnamelocalhost can be utilized. For debugging it is advisable to check the logle which was assigned inside theserver conguration le. It is commonly found at /var/log/arched.log.The following chapters explain how to develop custom Web Services. The rst one will be the simple TimeWeb Service.

    8

  • 8/8/2019 Ws Programming Tutorial

    9/53

    2 The Time Web Service

    The rst implementation of a Web Service will be a simple time service. When the service receives a requestof a client, it will respond with a string containing the system time. For simplicity, the service will notparse the request but always return the current time. It is therefore easier than the example of an EchoWeb Service which additionally has to extract the incoming message in order to get the string which shallbe echoed. In the following subsections the implementation of the service and the client will be presented.

    The source code of the examples given in this tutorial are available in the directory src that accompaniesthe electronic version of this document.

    2.1 Service

    In ARC, the services are implementated as plugins such that they can easily be included or excluded bymodiying the server conguration le as it was seen in Listing 1.1. The class needed to be implemented forthe Web Service inherits from the class Service , which itself is dened in the ARC library. The proper classdenition of the object TimeService is dened in the corresponding header as shown in Listing 2.1.

    Listing 2.1: Header le of the Time Web Service.

    1 /* * 2 * H e ad e r f i l e o f Ti m e Web S e rv i ce3 * 4 * T he t as k o f t h e s er vi ce i s a l w ay t o r e p ly w it h t he5 * c u rr e nt s y st e m t i me .6 */ 78 #ifndef __TIMESERVICE_H__9 #define __TIMESERVICE_H__

    1011 #include 12 #include < arc/Logger.h>1314 namespace ArcService15 {1617 class TimeService: publ ic Arc: :Service18 {19 protected:2021 /* * 22 * A rc - i n t e rn l o gg e r. R e d ir e ct s t h e l o g m e s s a ge s i n t o t h e23 * f i le s p ec i fi e d w i t h in t he s e rv e r c o n f i gu r at i o n f i l e .24 */ 25 Arc: :Logger logger;2627 /* * 28 * X ML n a m es p ac e o f t h e o u tg o in g S O AP m e ss a ge .29 */ 30 Arc: :NS ns_;3132 public:3334 /* * 35 * C o ns t r uc t o r o f t h e Ti m e We b S e r v ic e .36 */ 37 TimeService(Arc: :Config *cfg) ;3839 /* * 40 * D e st r u ct o r o f t h e Ti m e We b S e rv i ce .41 */ 42 vir tual ~TimeService(void) ;

    43If this was not shipped with the document you are reading, then please inspect

    http://svn.nordugrid.org/trac/nordugrid/browser/arc1/trunk/doc/ws-programming-tutorial.

    9

  • 8/8/2019 Ws Programming Tutorial

    10/53

    2 The Time Web Service

    44 /* * 45 * I m pl e m en t at i o n o f t he v i rt u al m e th o d d e fi n ed i n M C C In t e rf a c e46 * ( to b e f ou nd i n M C C . h) .47 * @ p ar a m i n ms g i n co m in g m e ss a ge48 * @ p ar a m i n ms g o u tg o in g m e ss a ge49 * @ r et u rn S t at u s o f t he a c hi e ve d r e su l t50 */ 51 vir tual Arc: :MCC_Status process(Arc: :Message& inmsg, Arc: :Message& outmsg);52 };5354 } / /namespace ArcService5556 #endif

    The class Service renders the possibility to implement the method process . Listing 2.2 contains theC++ implementation of the Time Web Service plugin. The key element for each plugin is the structPluginDescriptor named PLUGINS TABLE NAME to be seen in line 32. Within the struct, a uniqueplugin name, the type of the plugin, its version and a pointer to a function which returns the instance of the time service has to be dened. The function which returns the pointer of the instance is desclared inline 18. Within the interface an object PluginArgument is demanded as a parameter. But since the pluginthat is now written inherits from the class Service , one can expect the PluginArgument to be of a specialsubclass ServicePluginArgument . The ServicePluginArgument provides access to the server congurationand to the message chain of the service which later may be useful.

    The Time Web Service is implemented using the namespace ArcService . The constructor can be found inline 52 and the deconstructor in line 62. In the context of the simple service they dont contribute anyfunctionality. Only the constructor is dening the XML null-namespace for the time service.

    Listing 2.2: Implementation of the Time Web Service.

    1 #include 2 #include 34 #include 5 #include 6

    7#include " t imeservice.h"

    89 /* *

    10 * Wi th i n t h e f o ll o w in g v a ri a bl e P L U GI N S _TA B LE _ N AM E a p o in t er t o a 11 * m e th o d w i t h a c e rt a in s i gn a tu r e h as t o b e s t or e d .12 * 13 * T h is m e th o d h as t o b e c a pa b le t o p r oc e ss t he a rgu m en t P l u gi n A rg u m en t14 * a nd m u st r e tu r n a p o in t er t o a p lu g in , w h ic h i s a c tu a ll y t he t i m es e r vi c e .15 * 16 * T h er e fo r e t h e m e t h od i n i ti a li z e s t h e t i me s e rv i ce a nd r e tu r ns i t .17 */ 18 sta t ic Arc: :Plugin* get_service(Arc: :PluginArgument* arg)19 {20 / / T h e d y na m ic c a st c an h a nd l e N U L L21 Arc: :ServicePluginArgument* mccarg = dynamic_cast (arg) ;22 i f ( !mccarg) re turn NULL;2324 re turn new ArcService: :TimeService((Arc: :Config*)(*mccarg)) ;25 }

    262728 /* * 29 * T h is P L U GI N S _TA B LE _ N AM E i s d e fi n in g b a si c e n ti t ie s o f t he i m p le m e nt e d .30 * s er vi ce . I t i s u se d t o g e t t he c or re ct e nt ry p oi nt t o t he p lu gi n .31 */ 32 Arc: :PluginDescriptor PLUGINS_TABLE_NAME[] = {33 {34 "t ime", / * U ni qu e n am e o f p lu gi n i n s co pe o f i ts k in d * / 35 "HED:SERVICE", / * Ty pe / k i nd o f p l ug i n * / 36 1, / * Ve r s i on o f p l u g in ( 0 i f n ot a p pl i ca b l e ) * / 37 &get_service / * P o in t er t o c o n st r uc t o r f u nc t io n * / 38 },39 { N UL L , N U LL , 0 , N UL L } / * T h e a r ra y i s t e r m i na t e d b y e l em e nt * / 40 / * w i t h a ll c o mp o n en t s s e t t o N U L L * / 41 };4243 using namespace Arc;4445 namespace ArcService46 {4748 /* *

    10

  • 8/8/2019 Ws Programming Tutorial

    11/53

    2.1 Service

    49 * C o n st r uc t o r. C a ll s t h e s u pe r c o ns t ru c to r , i n i ti a li z i ng t he l o gg e r a n d 50 * s e tt i ng t he n a me s p ac e o f t h e p a yl o ad .51 */ 52 TimeService: :TimeService(Arc: :Config *cfg)53 : Service(cfg) , logger(Logger: : rootLogger , "Time")54 {55 / / S e tt i ng t he n ul l - n a m es p a ce f or t he o u tg o in g p a yl o ad 56 ns_[""]="urn: t ime";57 }5859 /* * 60 * D e c on s t ru c t or. N o th i ng t o b e d o ne h e re .61 */ 62 TimeService: :~TimeService(void)63 {64 }6566 /* * 67 * I m p le m e nt a ti o n o f t h e v i rt u al m e th o d d e fi n ed i n M C C In t e rf a ce . h ( t o b e f o un d i n M C C . h ) .68 * 69 * T h is m e th o d p r oc e s se s t h e i n co m in g m e ss a ge a n d g e ne r a te s a n o u tg o in g m e ss a ge .70 * F o r t h i s i s a v e ry s i mp l e s e rv i ce , t he t i me a l wa y s b e in g r e tu r ne d w i th o ut e x am i ni n g71 * t h e t h e i n co m i ng m e ss a ge .72 * 73 * @ p ar a m i n ms g i n co m in g m e ss a ge74 * @ p ar a m i n ms g o u tg o in g m e ss a ge75 * @ r et u rn S t at u s o f t h e r e s u lt a c hi e ve d

    76 */ 77 Arc: :MCC_Status TimeService: :process(Arc: :Message& inmsg,Arc: :Message& outmsg)78 {79 logger.msg(Arc: :DEBUG, "Timeservice has been s tar ted. . .") ;8081 / / G e t t im e a nd c re at e a n s t r in g o ut o f i t82 t ime_t t imer;83 t imer=t ime(NULL);84 std: :s t r ing loct ime = asct ime(local t ime(&timer)) ;85 loct ime = loct ime.substr(0, loct ime. length()-1) ;8687 / / C r ea t e a n o u tp u t m e ss a ge w i th a t a g t i m e c o n ta i n in g a n ot h er 88 / / t ag t i m eR e s po n s e w h ic h a g ai n s h al l c o nt a in t he t i me s t ri n g89 Arc: :PayloadSOAP* outpayload = NULL;90 outpayload = new Arc: :PayloadSOAP(ns_);91 outpayload ->NewChild("time").NewChild("timeResponse")=loctime;9293 outmsg.Payload(outpayload);9495 / / C rea te we l l fo rma ted , u se r f r iend ly ( second a rgumen t ) XML s t r ing96 std: :s t r ing xmlstr ing;97 outpayload ->GetDoc( xmlstring , true);98 logger.msg(Arc: :DEBUG, "Response message: \n\n%s",xmlstr ing.c_str()) ;99

    100 logger.msg(Arc: :DEBUG, "Timeservice done. . .") ;101102 re turn Arc: :MCC_Status(Arc: :STATUS_OK);103 }104105 } / /namespace

    The method process , dened in line 77, realises the desired service. The parameters inmsg and outmsg arereferences to the incoming and outgoing messages. Furthermore, the method process returns the objectMCCStatus that is representing the result of the service achieved. Within the method process , the service

    rst determines the current time using a system library and then creates a SOAP payload using the objectPayloadSOAP on line 89. The object PayloadSOAP provides enough functionality to create a XML messagethat is conform to the SOAP protocol. The appearance of the generated request and its response will bediscussed later on page 14.

    In the current case, the payload consists of two elements, one nested into the other. The element time holdsthe element timeResponse which again holds the string containing the current time. Within the line 93 thepayload is stored in the message. When nothing unexpected happened while the message was processed,the function returns an MCCStatus which was instanciated with the state OK , as to be seen in line 102.

    To run the service, it needs to be compiled into a dynamic library. Here this is named libtimeservice.so .The name is arbitrary but needs to be in sync with the conguration le of the HED. For the installation,the library needs to be copied to a directory that is accessible for the HED. Any would do, but mostlikely one will select one that is locally mounted, in order to reduce dependencies on external hard-ware. For his example, the installation direction was set to /tmp/arc/tutorial/lib . It was also specied by

    11

  • 8/8/2019 Ws Programming Tutorial

    12/53

    2 The Time Web Service

    the ModuleManager of the server conguration le. Once the server is running, the paths cannot be changed.

    A suitable server conguration le which engages the time service is shown in Listing 2.3. A new Path element has been introduced into the element ModuleMananger in line 7. It assigns the location of thecreated dynamic library. On line 16 the library is explictly mentioned to be loaded as a plugin. Anotherimportant change has been done within the Plexer element in line 29: a rule has been introduced whichredirects the request to the time service, if the path of URL is time . Please note that the URL setting iscase sensitive and corresponds to a regular expression.

    Listing 2.3: Conguration for the Time Web Service.

    1 2 3 4 /var / run/arched.pid5 /var/ log/arched. log6 7 8 9 /tmp/arc/ tutor ia l / l ib/

    10 /usr / l ib/arc/11 12 mcctcp13 mcct ls14 mcchttp15 mccsoap16 timeservice17 18 19 20 6000021 22 23 POST24 25 26

    27

    28 29 ^/ t ime $ 30 31 32 33 34 35

    In order to start the service, the arched command, shown in Listing 2.4, has to be used. It is recommendedto examine the log le /var/log/arched.log if the server conguration le has been modied to assert thestart was successful.

    Listing 2.4: Invokation if the arched daemon containing the Time Web Service

    $ a rched - c a rched_ timese rv ice .xml && echo Daemon s t ar t ed | | e cho Daemon s t ar t f a il edDaemon star ted

    2.2 Client

    Up to now we have implemented a server program which is running on a particular machine and waiting forother programs to ask for the time. What is still needed is the client to send the request to the server and

    interprete the response.This section is introducing the implementation of the client. Its main task is to interprete the returnedmessage. In order to be able to communicate with the service providing daemon, the client needs to use an

    12

  • 8/8/2019 Ws Programming Tutorial

    13/53

    2.2 Client

    identical protocol stack. Likewise to the HED, it will also be created dynamically using the MCCs. But asone will see, the creation of the protocol stack on client side is very simple.

    The source code of the client can be inspected in Listing 2.5 and consists basically of one main function.Within the line 15 the object Logger is initialized. Due to the conguration of the the Logger in the followinglines, the messages passed to it will be redirected to the standard error stream. For the components of the protocol stack, which are likewise loaded dynamically, one needs to specify the installation directory of ARC in line 21.

    Listing 2.5: Souce code of the client program

    1 #include 2 #include 3 #include 4 #include 56 #include 7 #include 89 using namespace Arc;

    1011 i nt ma in ( in t a rgc , char** a rgv )12 {1314 / / I n it i at e t he L o gg e r a n d s e t i t t o t h e s t an d ar d e r ro r s t re a m 15 Arc: :Logger logger(Arc: :Logger: :getRootLogger() , " t ime");16 Arc: :LogStream logcerr(s td: :cerr) ;17 Arc: :Logger: :getRootLogger() .addDest inat ion(logcerr) ;18 Arc: :Logger: : rootLogger.setThreshold(Arc: :WARNING);1920 / / S et t he A R C i n s ta l l at i o n d i re c to r y21 Arc: :ArcLocat ion: : Ini t (" /usr / l ib/arc") ;22 set locale(LC_ALL, "") ;2324 / / U R L t o t h e e n dp o in t25 std: :s t r ing ur ls t ring("ht tp: / / localhost :60000/ t ime");26 printf("URL: %s\n",ur ls t r ing.c_str()) ;2728

    29 / / Load use r conf igu ra t ion (de fau l t ~ / . a r c / c l i en t .xml )30 std: :s t r ing conff i le ;31 Arc: :UserConfig usercfg(conff i le) ;32 i f ( !u serc fg ) {33 printf("Fai led configurat ion ini t ia l izat ion\n") ;34 re turn 1;35 }3637 / / B a si c M CC c o nf i g ur a ti o n 38 Arc: :MCCConfig cfg;39 Arc: :URL service(ur ls t r ing);4041 / / C r ea t es a t y pi c al S O AP c l ie n t b a s e d o n t h e42 / / M C CC o nf i g a nd t h e s e r v i ce U RL43 Arc: :Cl ientSOAP cl ient(cfg, service) ;4445 / / D e fi n in g t he n a me s pa c e a nd c r ea t e a r e qu e st46 Arc: :NS ns("" , "urn: t ime");47 Arc: :PayloadSOAP request(ns) ;

    48 request .NewChild("t ime") .NewChild("t imeRequest") = "";495051 / / P r oc e ss r e qu e st a nd g e t r e sp o ns e52 Arc: :PayloadSOAP * response = NULL;53 Arc: :MCC_Status s ta tus = cl ient .process(&request , &response) ;5455 / / Te st f o r p o ss i bl e e r ro r s56 i f ( ! s t a tus ) {57 printf("Error %s",((s td: :s t r ing)status) .c_str()) ;58 i f ( response)59 delete response;60 re turn 1;61 }6263 i f ( ! r e sponse ) {64 printf("No SOAP response") ;65 re turn 1;66 }676869 / / E x t r ac t a n sw e r o u t o f t he X ML r e sp o ns e a n d p r i nt i t t o t h e s t a n da r d o u t70 std: :s t r ing answer = (s td: :s t r ing)((*response)[" t ime"][" t imeResponse"]) ;

    13

  • 8/8/2019 Ws Programming Tutorial

    14/53

    2 The Time Web Service

    71 s td :: cout

  • 8/8/2019 Ws Programming Tutorial

    15/53

    3 Web Services Description Language

    3.1 Background

    For Web Services, the mere communication, as for instance we know if from traditional CGI programming,is not everything. The communication is performed via the SOAP protocol, and there are several implemen-tations of SOAP on top of CGI. What the here explained WSDL (Web Services Description Language) isabout is the talking about Web Services. In a now standardised XML-based format, one can emply WSDLto describe both technically and for regular users the performance of the Web Service.

    WSDL may be imagined as a meta language. Beside the description of the service, WSDL renders thepossibility that services can be discovered by service brokers . The discovery of services may be useful foran automatic adaption of a running client, i.e. if the endpoint of the service changes or to share the loadof demands. The WSDL service specication enables a foreign programmer to implement a suitable clientwhich interfaces the service in a proper way. WSDL describes the structure of the messages, the intendeduse of the messages, the supported protocols and the endpoint of the service (URL).

    WSDL documents are composed of ve main elements: Types The element types contains the description of the message structures and is written in the

    language XSD (XML Schema Denition). The data types used for the messages of the Echo WebService are dened starting with the line 14.

    Message Within the element message a subset of the previously dened types are assigned to be amessage. In case of the Echo Web Service two messages are designated: echoRequest and echoResponse,compare lines line 52 and 55.

    Port type The element portType is used to assign the messages to an interface. Four interfacetypes can be distinguished: One-way (input), request-response (input, output), solicit-response (input,output, fault) and notication (output). The Echo Web Service realises a solicit-response interfacewhich is declared subsequent to line 61.

    Binding The protocol and the data format used for the message transmission are denoted inthe element binding . Possible style attributes are document or rpc (Remote Procedure Call). Thetransport attribute denes the protocol which is regularly HTTP. For each operation a correspondingSOAP action has to be dened which assignes a messages to be either literal or encoded [2]. The serviceimplemented in this chapter will use the binding document / literal and the protocol HTTP which is tobe seen in the lines follow line 71.

    Service Within the last WSDL element service the endpoint of the service gets specied. As to beseen in line 85 the endpoint of the Echo Web Service is assigned to http://localhost:60000/echo .

    To understand an WSDL document, one best starts from the Service entry, commonly located at the end. Itwill describe what the service is all about. From there, move upwards to learn about the operations and theirparameters. Most items in the WSDL document have their own tags that provide names or descriptions.

    3.2 How to prepare a WSDL document

    It should be said that the preparation of WSDL documents not ultimate fun to do. And it is tricky in thesense that one does mistakes easily that are difficult to spot.

    The here referenced brokering is meant to act on a global registry of services and has little practical meaning. It is notto be confused with the brokering of grid resources, for which ARC-1 provides a web service on its own, which is a keyfunctionality of any computational grid.

    15

  • 8/8/2019 Ws Programming Tutorial

    16/53

    3 Web Services Description Language

    Figure 3.1: Eclipse dialog to create a new le. WSDL is selected.

    Figure 3.2: The default settings are ne for a WSDL service that communicates with ARC.

    The community hence started to use computational tools to draft these documents. The most prominentof these is probably Eclipse. Since its version 3.4 (you might need to install it directly from http://www.eclipse.org if your distribution is a bit behind or if you are working with Windows) it offers a web toolsplatform (WTP) module with which WSDL les can be crafted graphically. To install it, point the urlhttp://download.eclipse.org/webtools/updates/ to the Eclipse updater, if it is not already listed.

    3.2.1 Preparation of the Echo WSDL le with Eclipse

    To prepare a WSDL document with Eclipse, one should nd the right le type in the typical Eclipse dialogwindow. This is shown in gure 3.1. The empty WSDL document is not empty, but the application startswith a minimal setup: a service that expects some input and provides some immediate return value. This isalready much like the echo web service. One basically only needs to add the documentation of the serviceand to name the parameters. To do so, just click on the items displayed in the graphical representationand/or nd respective entries in the tabs below.

    3.2.2 Inspection of Web Services with Taverna

    One will ne many specications that are needed by WSDL to glue the different parts of the WSDL letogether. The service references the bindings and the bindings reference the port and so on. One should notbecome overly nervous about it. The regular programmer does not see those internal names. A good sanity

    16

    http://www.eclipse.org/http://www.eclipse.org/http://www.eclipse.org/http://www.eclipse.org/
  • 8/8/2019 Ws Programming Tutorial

    17/53

    3.2 How to prepare a WSDL document

    Figure 3.3: The project rst shown has already a strong similarity to the Echo web service that is planned for.

    Figure 3.4: A rst usable web service description is achieved solely by specifying the address and passing thearguments the known type string .

    Figure 3.5: The WSDL for echo in a very simplistic manner.

    17

  • 8/8/2019 Ws Programming Tutorial

    18/53

    3 Web Services Description Language

    Figure 3.6: Taverna learned about the Echo Web Service and presents it. No internal names of WSDL appear, onlythe name of operations and paramters are shown.

    Figure 3.7: A completely functional (albeit small) workow in Taverna that addresses the Echo Web Service pre-pared with HED.

    check for the programmers view on a WSDL le is to load it from within the workow suite Taverna .

    The activities menu in Taverna offers the item New Activity . It will request the specication of an URL ora local path that points to a WSDL le. The services presented in there will then be added to the list of WSDL resources. So will the echo workow that was just prepared with Eclipse. When it is dragged to the

    canvas in the middle, as shown in gure 3.6, it appears as an interactive object. To the right, the parametersof the operation are displayed.

    With a string constant as a constant input added, alternatively one could link a congurable workow inputas input to the echo Web Service, and the workows output linked as a sink to the output of the workow,the workow is complete. It can now be executed, presuming that the localhost is indeed running archedwith the echo service as described in section ?? .

    When comparing the GUI representation of Eclipse as shown with in gure 3.5 or that of the just shownTaverna representation with the raw WSDL of listing 3.1, it becomes apparent, that the raw form of theWSDL, as shown below, is more complicated. It seems to invent nested structures that are just not present,since it is only simple strings that are exchanged. The good news here is, that one would have reachedexactly that more complicated looks when following the original setup without assignment of the simpletype string. WSDL needs special types for every operation. And eclipse provides them, even when the

    Taverna is available from http://taverna.sf.net . ARC offers a plugin that allows the direct communication of Tavernawith resources runnign ARC-0. An interface to ARC-1 is still pending. In principle, there is none needed. In practice, westill need more practice to decide.

    18

    http://taverna.sf.net/http://taverna.sf.net/http://taverna.sf.net/
  • 8/8/2019 Ws Programming Tutorial

    19/53

    3.3 What else to do with WSDL

    input types are shown in a more simple manner.

    This has the advantage, that you can use this WSDL le to describe the regular ARC echo service, eventhough the original programmer might not have used Eclipse to create it. Or has he? Gabor?

    3.3 What else to do with WSDLThere are several efforts to organise the world of web services and their interactions. Taverna was alreadymentioned above. Amongst the most advanced scientic community with respect to Web Services are theBioinformaticians. Topics that come to mind are:

    BioMoby www.biomoby.org

    m

    y Grid and m y Experiment www.myexperiment.org Distributed Annotation System (DAS) http://www.biodas.org

    But this is left for a future version of this tutorial. . . and/or possibly Hajos Bachelor thesis.

    19

    http://www.biomoby.org/http://www.myexperiment.org/http://www.biodas.org/http://www.biodas.org/http://www.myexperiment.org/http://www.biomoby.org/
  • 8/8/2019 Ws Programming Tutorial

    20/53

    3 Web Services Description Language

    Listing 3.1: WSDL le for Echo created with Eclipse.

    1 2

    3 4 5 6 7 8 9

    10 11 12 13 14 15 16 17 18 19 20 21 22 23 This parameter specifies what should be said24 25 26 27 This parameter shows the echo28 29 30 In th is po rtType , t he opera t ions o f t he web se rv ice a re b rought

    toge the r. There could be mult ipl e .31 For in st ance , t he echo web se rv ice could bu ffe r t he inpu t w i th one opera tion , and r e lease i t

    with another.

    32 I t would then work l i ke a s t ack< /wsdl :documen ta tion>33 34 35 36 This is the input to this web service37 38 This is the output of the web service39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 An example fo r a WSDL f i le t hat descr ibes the echo Web Se rv ice o f

    ARC55 56 Echo may be on va rious URLs wi th va rious po rt s . Here we have

    chosen po rt 60000 . An o f ten seen a l t ernat ive i s 5000057 58 59 60

    20

  • 8/8/2019 Ws Programming Tutorial

    21/53

    4 The Echo Web Service

    The Echo Web Service was already presented in the introduction, basically as the ground truth to learnif the installation of the HED is functional. And it was frequently referenced in the previous chapter onWSDL. In this section, we will implement our own version of the Echo Web Service.

    Its task is to return the content of the received message back to the client. As a special feature that weintroduce solely for educatory purposes, the service provides two additional operations called ordinaryand reverse. Depending on the operation chosen by the client, the message gets returned unmodied orreversed. The goal of this chapter is to deepen the knowledge on message processing.

    The section starts with another roundup on the WSDL for the Echo service, continues with the implemen-tation of the server and nally describes the client.

    4.1 Description with WSDL

    The WSDL le that species the here presented Echo Web Service is shown in Listing 4.1.

    Listing 4.1: WSDL le describing the echo service. Filename: echo.wsdl

    1 2 1112 13 14 15 16 17 18 19 20 21 22 23 24 25 26

    2728 29 30 31 32 33 34 35 36 37 38 3940 41 42 43 44 45 4647 48 49

    21

  • 8/8/2019 Ws Programming Tutorial

    22/53

    4 The Echo Web Service

    50 51 52 53 54 55 56 57 5859 60 61 62 63 64 65 66 67 6869 70 71 72 73 74 75 76

    77 78 79 80 81 82 8384 85 86 87 88 89 9091

    4.2 Implementation of the Server

    This section presents the implementation of the service dened in the WSDL le of the previous section andshown in Listing 4.2. For the user of a web service, it is not important to know the programming languagethat this was implemented in. This tutorial uses the C++ libraries of HED. Though ARC also provideseverything that one would need to implement the service with a scripting language like Python. A laterversion of this tutorial hopefully describes both APIs side by side.

    4.2.1 Communication with SOAP: The SOAP Fault Message

    A SOAP fault message is always located within the body element and can appear only once. It indicateserror messages in case the port type solicit-response (input, output, fault) has been chosen. An elementcalled fault encapsulates different types of elements that describe the fault. These elements are listed inTable 4.1. The fault code describes the generic class of the fault. The ARC implementation assigns each

    Table 4.1: Elements of the fault message.

    Element Description

    faultcode Code which shall identify the fault.faultstring A human readable explanation of the fault.faultactor Information about who caused the fault to happen.detail Holds application specic error information.

    22

  • 8/8/2019 Ws Programming Tutorial

    23/53

    4.2 Implementation of the Server

    fault a certain number. The fault code along with its description is described within the Table 4.2

    Table 4.2: Possible fault codes.

    Fault code Error Description

    0 undened 1 unknown Reason for failure couldnt be identied.2 VersionMismatch Found an invalid namespace for the SOAP Envelope ele-

    ment.3 MustUnderstand The processing of the SOAP header is optional unless the

    ag mustUnderstand is set true. If, according to thatcase, the SOAP service is not able to understand the headera fault message with the faultcode MustUnderstand is re-turned.

    4 Client The request message was incorrectly formed or containedincorrect information.

    5 Server There was a problem with the server so the message couldnot proceed

    6 DataEncodingUnknown The message couldnt be processed due to encoding prob-lems

    For more information additional tutorials can be found in the appendix or check the internet ad-dress http://www.w3.org/TR/wsdl .

    4.2.2 The Service in C++

    The header le will be set aside since it contains only redundant information. It can be reread in thesource directory that is accompanying the tutorial. In comparsion with Time Web Service, basically threechanges are required. The rst change concerns the constructor and can be found at line 52. Two stringsare extracted of the server conguration le which are later used to envelope the message before it isreturned. Furthermore, a new method makeFault in line 66 has been introduced which is able to create afault messages. Within the method process two new code fragments are now extracting and analyzing theincoming message, to be seen at line 100 and 110. In case something unexpected happens either will createa SOAP fault message.

    Listing 4.2: Implementation of the Echo Web Service.

    1 #include 2 #include

    34 #include 56 #include " echoservice.h"789 /* *

    10 * I n i ti a li z e s t h e e c ho s e rv i ce a nd r e tu r ns i t .11 */ 12 sta t ic Arc: :Plugin* get_service(Arc: :PluginArgument* arg)13 {14 Arc: :ServicePluginArgument* mccarg = dynamic_cast (arg) ;15 i f ( !mccarg) re turn NULL;16 re turn new ArcService: :EchoService((Arc: :Config*)(*mccarg)) ;17 }1819 /* * 20 * T h is P L U GI N S _TA B LE _ N AM E i s d e fi n in g b a si c e n ti t ie s o f t he i m pl e m en t e d .21 * s er vi ce . I t i s u se d t o g et t he c or re ct e nt ry p oi nt t o t he p lu gi n .22 */ 23 Arc: :PluginDescriptor PLUGINS_TABLE_NAME[] = {24 {25 "echo", / * U ni qu e n am e o f p lu gi n i n s co pe of i t s k in d * /

    23

    http://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdl
  • 8/8/2019 Ws Programming Tutorial

    24/53

    4 The Echo Web Service

    26 "HED:SERVICE", /* Type / kind of plugin */ 27 1, /* Ve rs io n of plu gi n (0 if not ap pl ic ab le ) */ 28 &get_service /* Pointer to construc tor funct ion */ 29 },30 { N UL L , N U LL , 0 , N UL L } /* The array is t erminated by element */ 31 /* with all components set to NULL */ 32 };333435 using namespace Arc;3637 namespace ArcService38 {3940 /* * 41 * C o ns t r uc t o r. C a ll s t he s u pe r c o ns t ru c to r , i n i ti a l iz i n g t h e l o gg e r a nd 42 * s e tt i ng t h e n a m e s pa c e o f t he p a yl o ad . F u rt h e rm o r e t h e p r ef i x a n d s u ff i x w i ll43 * e x tr a ct e d o ut o f t h e C o nf i g o b je c t ( E l e m e nt s w e re d e cl a re d i n si d e t he H ED 44 * conf igu ra t ion f i l e ) .45 */ 46 EchoService: :EchoService(Arc: :Config *cfg) : Service(cfg) , logger(Logger: : rootLogger , "

    Echo")47 {48 / / S e tt i ng t he n a m es p ac e o f t h e o u tg o in g p a yl o ad 49 ns_["echo"]="urn:echo";5051 / / E x tr a ct p r ef i x a n d s u ff i x s p ec i fi e d i n t he H ED c o n fi g u ra t i on f i le

    52 pref ix_=(std: :s t r ing)((*cfg)["pref ix"]) ;53 suff ix_=(std: :s t r ing)((*cfg)["suff ix"]) ;54 }5556 /* * 57 * D e c on s t ru c t or. N o th i ng t o b e d o ne h e re .58 */ 59 EchoService: :~EchoService(void)60 {61 }6263 /* * 64 * M e th o d w h ic h c r ea t es a f a ul t p a yl o ad 65 */ 66 Arc: :MCC_Status EchoService: :makeFaul t (Arc: :Message& outmsg, const s td: :s t r ing & reason)67 {68 logger.msg(Arc: :WARNING , "Creat ing faul t ! Reason: \"%s\"" , reason);69 / / T h e b o ol e an t r ue i n di c at e s t h at i n si d e o f P a yl o ad S OA P ,70 / / a n o b je c t S O AP F au l t w i ll b e c r ea t ed i n si d e .71 Arc: :PayloadSOAP* outpayload = new Arc: :PayloadSOAP(ns_, t rue) ;72 Arc: :SOAPFault* faul t = outpayload ->Faul t ( ) ;73 i f ( f au l t ) {74 faul t ->Code(Arc: :SOAPFault : :Sender) ;75 faul t ->Reason(reason);76 };77 outmsg.Payload(outpayload);7879 re turn Arc: :MCC_Status(Arc: :STATUS_OK);80 }8182 /* * 83 * P r oc e ss e s t he i n co m in g m e ss a ge a nd g e ne r at e s a n o u tg o i ng m e ss a ge .84 * R e tu r ns t h e i n c o m in g s t ri n g o r di n ar y o r r e ve r se - d e pe n di n g o n t he o p e ra t io n 85 * r equest ed .86 * @ p ar a m i n ms g i n c om i ng m e ss a ge87 * @ p ar a m i n ms g o u t go i ng m e ss a ge88 * @ r et u rn S t at u s o f t h e r e su l t a c hi e v ed 89 */ 90 Arc: :MCC_Status EchoService: :process(Arc: :Message& inmsg, Arc: :Message& outmsg)91 {92 logger.msg(Arc: :DEBUG, "Echoservice s tar ted. . .") ;9394 / * * B o t h i n p ut a n d o u t pu t a re s u p po s ed t o b e S O AP * / 95 Arc : :Pay loadSOAP* inpayload = NULL;96 Arc: :PayloadSOAP* outpayload = NULL;97 / * * * / 9899 / * * E x t ra c ti n g i n c om i ng p a y l o ad * /

    100 t ry {101 inpayload = dynamic_cast (inmsg.Payload()) ;102 } ca tch ( s td : : excep tion& e ) { } ;103104 i f ( ! inpayload) {105 logger.msg(Arc: :ERROR, "Input is not SOAP");106 r e tu rn makeFaul t (outmsg , "Received message was not a va lid SOAP message . " ) ;107 };

    108 / * * * / 109110 / * * A n al y zi n g a nd e x ec u te r e qu e st * / 111 Arc: :XMLNode requestNode = (*inpayload)["echo:echoRequest"] ;

    24

  • 8/8/2019 Ws Programming Tutorial

    25/53

    4.3 Implementation of the Client

    112 A rc : : XM LN od e s ay No de = r e qu es t No de [ " ec ho : s ay " ];113 std: :s t r ing operat ion = ( s td: :s t r ing) sayNode.Attr ibute("operat ion") ;114 s td :: st ri ng s ay = ( std :: st ri ng ) s ay No de ;115 std :: string hear = "";116 logger.msg(Arc: :DEBUG, "Say: \"%s\" Operat ion: \"%s\"" ,say,operat ion);117118 / / C om p ar e s t ri n gs w i th c o ns t a nt s d e fi n ed i n t he h e ad e r f i le119 i f (operat ion.compare(ECHO_TYPE_ORDINARY) == 0)120 {121 hear = pref ix_+say+suff ix_;122 }123 else i f (operat ion.compare(ECHO_TYPE_REVERSE) == 0)124 {125 i n t l en = say. l ength ( ) ;126 i nt n ;127 s td :: s t r ing r eve r se = say ;128 f or ( n = 0; n < l en ; n + +)129 {130 r ev er se [ l en - n - 1 ] = s ay [ n ];131 }132 hear = p ref ix_+ reve r se +su ffix_ ;133 }134 else135 {136 r e tu rn makeFau l t (outmsg , "Unknown opera t ion . P l ease use \ "o rdinary \ " o r \ "

    reverse\"");137 }

    138 / * * * / 139140 / * * C r ea t e r e sp o ns e * / 141 outpayload = new Arc: :PayloadSOAP(ns_);142 outpayload ->NewChild("echo:echoResponse").NewChild("echo:hear")=hear;143 outmsg.Payload(outpayload);144145 / * * * / 146147 logger.msg(Arc: :DEBUG, "Echoservice done. . .") ;148 re turn Arc: :MCC_Status(Arc: :STATUS_OK);149 }150151 } / /namespace

    Again, the HED is congured by an XML le and launched in the same manner as introduced before. Theserver conguration le is shown in Listing 4.3. The only change concerns the lines 37 and 38 which specifythe prex and suffix . The parameters will be extracted in the constructor of the service and explain nicelyhow settings can be passed from the server conguration le towards the service.

    4.3 Implementation of the Client

    With the interface of the server gaining complexity, so is the code for the client - for two reasons. Firstly,because the additional arguments need to be lled. Secondly, because of the extra effort to interact with the(here human) user to collect the data which needs to be forwarded to the Echo Web Service. The sourcecode of the client is shown Listing 4.4. The parameters are now passed by the command line, to be seenin the lines following line 15. That code is independent from the ARC library. The creation of the SOAPclient is unchanged from the Echo clients implementation and the request to the server is created in thelines subsequent to line 62. It is processed in the code after line 69 in which also the response is received.The checks of the response have expanded by an additional condition which tests for a fault message, seeline 75.

    4.3.1 The Client in C++

    Listing 4.4: Implementation of the client program.

    1 #include 2 #include 3 #include 4 #include 56 #include 7 #include 89 using namespace Arc;

    25

  • 8/8/2019 Ws Programming Tutorial

    26/53

    4 The Echo Web Service

    Listing 4.3: Server conguration le of the Echo Web Service

    1 2 8 9 /var / run/arched.pid

    10 /var/ log/arched. log11 12 13 /tmp/arc/ tutor ia l / l ib/14 /usr / l ib/arc/15 16 mcctcp17 mcct ls18 mcchttp19 mccsoap20 echoservice21 22 23 24 60000

    25 26 27 POST28 29 30 31 32 33 ^/echo $ 34 35 36 37 [ 38 ]39 40 41

    1011 i n t ma in ( in t a rgc , char** a rgv )12 {1314 / * * G e t a rgu m en t s p a ss e d b y t he c o mm a nd l i ne * / 15 i f ( argc != 4 ){16 printf("Usage: \n") ;17 pr in t f ( " echoc l ien t u r l t ype message \n" ) ;18 printf(" \n") ;19 pr in t f ( "The f i rs t a rgumen t de fines the URL o f the se rv i ce . \n" );20 pr in t f ( "The second a rgumen t the type o f echo wh ich shal l be pe rfo rmed (o rd ina ry o r

    reverse).\n");21 pr in t f ( "The th ird ag rumen t ho lds the message to be t r ansmit t ed .\n" ) ;22 printf(" \n") ;23 printf("Example: \n") ;

    24 printf(" . /echocl ient ht tp: / / localhost :60000/echo ordinary text_to_be_transmit ted\n") ;25 re turn -1;26 }2728 std: :s t r ing ur ls t r ing(argv[1]) ;29 std: :s t r ing type(argv[2]) ;30 std: :s t r ing message(argv[3]) ;31 / * * * / 3233 / / I n i t i at e t he L o gg e r a n d s et i t t o t he s t an d ar d e r ro r s t re a m 34 Arc: :Logger: : rootLogger.setThreshold(Arc: :WARNING);35 Arc: :Logger logger(Arc: :Logger: :getRootLogger() , "echo") ;36 Arc: :LogStream logcerr(s td: :cerr) ;37 Arc: :Logger: :getRootLogger() .addDest inat ion(logcerr) ;38 Arc: :Logger: : rootLogger.setThreshold(Arc: :WARNING);3940 / / S e t t h e A RC i n st a l la t i on d i r ec t or y41 Arc: :ArcLocat ion: : Ini t (" /usr / l ib/arc") ;42 set locale(LC_ALL , "") ;4344 / / Load use r conf igu ra t ion (de fau l t ~ / . a r c / c l i en t .xml )45 std: :s t r ing conff ile ;

    26

  • 8/8/2019 Ws Programming Tutorial

    27/53

  • 8/8/2019 Ws Programming Tutorial

    28/53

  • 8/8/2019 Ws Programming Tutorial

    29/53

    5 The TLS Echo Web Service

    The Web Services of the previous chapters have one major drawback: the communication between the twoendpoints is insecure. For that reason the current and the next chapters will discuss how to create a secureWeb Service. In general, security in a network can be subdivided into the following categories: [ 3]

    Condentiality Protection of the data against passive attacks (such as publicise message content) Authentication Verication of the identity of the communication partners. Integrity Protection against interception and manipulation, replay, insertion, etc. of a message. Non-repudiation Preventing the sender to repudiate the message transmitted by him. Access control Restrict the access to ressources. Availability Ensure a system is always usable which is challenged by various attacks.

    Ideally, all six categories should have been achieved by such an application (though the last category,availability, is difficult to realise). In the present chapter, the security will be put into practice by extendingthe protocol stack with an additional security layer called TLS (Transport Layer Security). Due to thelocation between the TCP and the HTTP layer, the layer is only capable to limit the access of the gridto a certain set of users. Once the user has passed the layer sucessfully, all resources provided by theHED are available. This kind of behaviouor can be seen as to be very coarse grained. Nevertheless, itprovides the security categories: condentiality, authentication, integrity, non-repudiation and access control.

    The next section gives a basic understanding of the working principle of the TLS. In order to enable new-comers an entry to this area, emphasis is put on the security concept and not on an exact description of the

    technical realisation.

    5.1 Transport Layer Security

    The TLS is a protocol which provides a secure connection between two endpoints. It is based directly onthe TCP/IP layers and uses typically an asymmetric encryption to establish the connection (alternatively asymmetric pre-shared key may be used). After the communication has been successfully established, bothparticipants are switching to another encryption method which is based on a new negotiated symmetric key.

    Symmetric and asymmetric encryption are the two main classes of cryptographic algorithms. In case of symmetric encryption, both participants are holding the same secret key to encrypt and decrypt a plain text.The principle is to reverse the process of encryption in order to decrypt the text. Symmetric encryptioncan be ranked as being very secure but its downside is that the key distribution is very difficult in practice.The key has to be shared previously, ideally over a secure channel which may either be a complete differentmedium (i.e. a letter or speech) or a channel which has been encrypted with another secret key. Asymmetricencryption follows a different functional principle. While the symmetric encryption utilise one key, theasymmetric ecryption is based on two keys: a private key and public key. As the names imply, the privatekey is kept secret and is never revealed to others while the public key is available for everyone. Messagesencrypted with the public key can only be decrypted with the private key and conversely, messages encryptedwith the private key can only be decrypted with the public key. The Figure ?? illustrates the circumstancesof the case.

    At startup of a communication process, A (Alice) who desires a secure connection transmits her publickey to B (Bob). Bob is now able to encrypt his messages such that only Alice is able to decrypt them.As one can see, this rst approach already provides condentiality and integrity of messages. But neithernon-repudiation, authentication and consequently nor access control are established because the identity

    29

  • 8/8/2019 Ws Programming Tutorial

    30/53

  • 8/8/2019 Ws Programming Tutorial

    31/53

    5.1 Transport Layer Security

    rst step, a private and a public key will be generated by the requester. The public key together with atextual description of the identity depict the request which will be transmitted to a CA. After the CAsuccessfully veried the validity of the request, the identity of the CA and the name of the used encryptionalgorithms are added. The collected data will represent the plain text of the certicate. In order to ensurethe integrity of the text, a hash value will be created. This is a xed-sized short string which is generatedby an algorithm based on an arbitrary long given text. The algorithm is designed such that a small changein the text will cause the hash value to change almost like a random function. Thus, the hash value canbe used a ngerprint of the text. The CA signs the plain certicate by encrypting its hash value with itsprivate key. Finally the signed certifcate will be returned to the requester. If an outside person wants toverify the certicate owner, the encrypted hash value has to be decrypted by the public key of the CA anda hash value has to be created with the same algorithm in order to compare them.

    Figure 5.3 shows a usecase in which Alice wants to resolve the identity of Bob. Alice submits her request toBob along with a challange consisting of a random number n . Bob encrypts the number with his private keyand returns it together with his certicate. The random number ensures that it is not possible to repeat amessage (integrity) and to prove that the communication partner holds the private key. Alice uses the publickey of Bob to decrypt the challenge. If the decrypted number is equal to the transmitted number, Alice canreason that the identity of Bob is to be trusted in case she is trusting the CA which has signed Bobs certicate.

    In the given example, Alice only trusts the CA 2 but not CA 1. To resolve the identity of CA 1, Aliceestablishes a connection to CA 1 and submits another random number n as a challenge. The CA 1 encryptsthe challenge with its private key and sends the result along with its certicate back to Alice. Alicesuccessfully compares the returned number. Additionally she validates the certicate of CA 1 with thepre-congured certicate of CA 2.. Since the certicate was signed by CA 2 which is pre-congured to betrusted, she also trusts CA 1 and in conclusion the identity of B. In summary, Alice knows she is talking toBob. If Bob also wants to be sure who hes talking to, then the same procedure has to be done to conrmthe identity of Alice. The TLS mode in which both endpoints are ensuring themselves to whom they aretalking to is called bilateral connection mode .

    When the client is aware of the servers authentity, the condential treatment of its data is guaranteedsuch that one can be sure the data wont be revealed to a third party (server-sided condentiality). Onthe other side, if the server is aware of the client authentity, the access to services and resources can becontrolled (access control). Thus, in case of services, the results will only be passed back to the right person(client-sided condentiality). As one can see condentiality, authentication, integrity and non-repudiationare now established.

    Certicates have several advantages. They are scaling very good with the amount of users because CAscan create new sub-CAs such that the load is balanced (certicates of a CA may be cached). Furthermore,no critical information is exchanged for the establishment of a connection (in particular: no secret key isshared which may get intercepted). Instead, a set of pre-congured CAs which will be in general providedby the operation system is needed. In respect of ARC it is obvious that the access to the grid shall beunder the control of its administrator. To do so, the administrators have to create their own CAs whichare in charge of creating certicates for new users. The identity of the created CA has to be added to thedirectory of pre-congured CAs. Many universities have prepared local certicate authorities. And everyuser can establish his own. Certicates in general, however, have found entry to regular computer users, forinstance with the FernUniversity Hagen (https://ca.fernuni-hagen.de/) who use that technology for theirremote students to hand in exercises.

    A CA which controls access to a grid can be considered as a virtual organsiation (VO). It may involveorganisations close to the leading organisation as well as structure which are not formally associated withit. In most cases the basic idea is to share ressources.

    31

  • 8/8/2019 Ws Programming Tutorial

    32/53

  • 8/8/2019 Ws Programming Tutorial

    33/53

    5.2 Service

    5.2 Service

    In order to create a secure connection we hence need two certicates: a client certicate and a servicecerticate. The CA of the certicate has to be pre-congured on the counterpart and furthermore, theowner of the certicate has to hold the tting private key. For the given example X.509-certicates in thePEM format will be used which are standardised by the ITU-T. Altogether six les are needed:

    clientCA The CA which guarantees for the identity of the clientclientCERT The certicate of the client.clientKEY The private key of the client (should be kept in safe custody).

    serverCA The CA which guarantees for the identity of the serverserverCERT The certicate of the server.serverKEY The private key of the server (should be kept in safe custody).

    To get this service running, the six les have to be distributed. The server should hold the les:

    serverCERT.pem, serverKEY.pem and clientCA.pem. The client on the other side should own the les:clientCERT.pem, clientKEY.pem and serverCA.pem. Within the source code directory that accompaniesthis document certicates with corresponding names are prepared. Due to certicates have a limited periodof validity, these certicates may no longer be accepted by the communication parter. One has to createnew certicates to ensure the proper work of the TLS Web Service.

    Several tools are available which allow the handling for more advanced UNIX users. In order to createa rst basic set of certicates signed by a self created CA, the shell scripts createMasterCA.sh and cre-ateSlaveCert.sh can be found within the directory src/services/tlsechoservice/certFactory may be used. Thescript createMasterCA.sh will create a new CA and will overwrite older ones. The script createSlaveCert.sh creates several certicates signed by the CA.

    The TLS Echo Web Service implementation is almost the same as the one presented in the previous chapter.Merely the Class name and the namespace of the service have been changed. The only modication is donewithin the server conguration le which is displayed in Listing 5.1. The rst change is in line 19. As tobe seen, another plugin called mcctls will be loaded by the ModuleManager . The second change is the newelement which has been placed between the TCP and the HTTP component, see line 28. Within the TLSelement the certicates can be declared using the elements KeyPath , CerticatePath , CACerticatePath andCACerticatesDir .

    33

  • 8/8/2019 Ws Programming Tutorial

    34/53

    5 The TLS Echo Web Service

    Listing 5.1: HED conguration le for the Arc intern echo service. Filename: arcecho no ssl.xml hmf

    1 2

    10 11 /var / run/arched.pid12 /var/ log/arched. log13 14 15 /tmp/arc/ tutor ia l / l ib/16 /usr / l ib/arc/17 18 mcctcp19 mcct ls20 mcchttp21 mccsoap22 tlsechoservice23 24 25 26 60000

    27 28 29 30 . /serviceKey.pem31 . /serviceCert .pem32 . /c l ientCA.pem33 34 35 POST36 37 38 39 40 41 ^/ t lsecho $ 42 43 44 45 [ 46 ]47 48 49

    34

  • 8/8/2019 Ws Programming Tutorial

    35/53

    5.3 Client

    5.3 Client

    In this section a new way to implement the client will be introduced. As already mentioned in section 2.2,the protocol stack of the client is built up in almost the same way as the one of the service. Indeed, theclass ClientSOAP composes the stack with the same MCCs used for the service. Once this is known, it isself-evident to create the client in a simlar manner like the service with an own conguration le. Listing 5.2shows the source code of the client program. The main difference to the simple Echo Client presented inthe previous chapter is that now the information about the client protocol stack is encapsulated within aconguration le.

    Listing 5.2: Client programm which is capable to load a conguration le

    1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 78 #include 9 #include

    10 #include 1112 using namespace Arc;1314 i nt ma in ( in t a rgc , char** a rgv ) {1516 / * * G e t a rgu m e nt s p a ss e d b y t he c o mm a nd l i ne * / 17 i f ( argc != 4 ){18 printf("Usage: \n") ;19 pr in t f ( " t l s echocl i ent configu ra t ion type message \n" ) ;20 printf(" \n") ;21 pr in t f ( "The f i rs t a rgument spec i fi e s t he HED configu ra t ion f i le t o be loaded \n" ) ;22 pr in t f ( "The second a rgumen t the type o f echo wh ich shal l be pe rfo rmed (o rd ina ry o r

    reverse) . \n") ;23 pr in t f ( "The th ird ag rument ho lds the message to be t r ansmi tt ed . \n" ) ;24 printf(" \n") ;25 printf("Example: \n") ;26 printf(" . / t lsechoclient c l ientHED.xml ordinary text_to_be_transmit ted\n") ;

    27re turn -1;

    28 }2930 std: :s t r ing type(argv[2]) ;31 std: :s t r ing message(argv[3]) ;32 / * * * / 3334 / * * L o a d t he c l ie n t c o n fi g ur a t io n f i le i n to a s t ri n g * / 35 std: :s t r ing xmlstring;36 std: : i fs t ream f i le(argv[1]) ;37 i f ( f i le .good())38 {39 printf("Reading XML schema from %s\n",argv[1]) ;40 f i le .seekg(0,s td: : ios: :end);41 std: : i fs t ream::pos_type s ize = f i le . te l lg() ;42 f i le .seekg(0,s td: : ios: :beg);43 std: : i fs t ream::char_type *buf = new std: : i fs t ream::char_type[size] ;44 f i le . read(buf ,s ize) ;45 xmls t r ing = bu f ;

    46 delete [ ]buf;47 f i le .c lose() ;48 }49 else50 {51 s td :: cout

  • 8/8/2019 Ws Programming Tutorial

    36/53

    5 The TLS Echo Web Service

    69 i f ( !c l ientConfig) {70 logger.msg(Arc: :ERROR, "Fai led to load cl ient configurat ion") ;71 re turn -1;72 };7374 Arc: :MCCLoader loader(cl ientConfig) ;75 logger.msg(Arc: : INFO, "Client s ide MCCs are loaded") ;76 Arc: :MCC* cl ientEntry = loader["soap"] ;77 i f ( !c l ientEntry) {78 l ogge r.msg(Arc : :ERROR, "Cl ien t chain does no t have en try po in t " ) ;79 re turn -1;80 };81 / * * * / 828384 / * * C r e a te a nd p r oc e ss m e ss a ge * / 85 Arc: :NS ns("t lsecho", "urn: t lsecho") ;86 Arc ::Pay loadSOAP request (ns ) ;87 Arc ::Pay loadSOAP* re sponse = NULL;8889 / / D u e t o t h e f a c t t h at t he c l as s C l ie n tS O A P i s n t u s ed a n ym o re ,90 / / o n e h a s t o p r ep a re t h e m e s s a ge s w h ic h e n ve l op e t he p a yl o ad t h em s e lv e s .91 Arc: :Message reqmsg;92 Arc: :Message repmsg;93 Arc: :MessageAttr ibutes a t t r ibutes_req;94 Arc: :MessageAttr ibutes a t t r ibutes_rep;95 Arc: :MessageContext context ;

    96 repmsg.Attr ibutes(&attr ibutes_rep);97 reqmsg.Attr ibutes(&attr ibutes_req);98 reqmsg.Context(&context) ;99 repmsg.Context(&context) ;

    100101 XMLNode sayNode = request .NewChild("t lsecho: t lsechoRequest") .NewChild("t lsecho:say") =

    message;102 sayNode.NewAttr ibute("operation") = type;103 reqmsg.Payload(&request) ;104105 Arc: :MCC_Status s ta tus = cl ientEntry ->process(reqmsg , repmsg);106 response = dynamic_cast (repmsg.Payload()) ;107 / * * * / 108109 i f ( ! r esponse ) {110 printf("No SOAP response") ;111 re turn 1;112 }else i f ( response ->IsFaul t ( ) ){113 printf("A SOAP faul t occured: \n") ;114 std: :s t r ing hoff = (s td: :s t r ing) response ->Faul t ( ) ->Reason() ;115 pr in t f ( " Faul t code : %d\n", ( r esponse ->Faul t ( ) ->Code() ) ) ;116 printf(" Faul t s t r ing: \"%s\"\n" , ( response ->Faul t ( ) ->Reason()) .c_str()) ;117 /* * 0 undefined , 4 Sender , // Cl ient in SOAP 1.0 118 1 unknown , 5 Receiver , // Server in SOAP 1.0 119 2 Ver si on Mi sm at ch , 6 D at aE nc od in gU nk no wn 120 3 MustUnderstand , **/ 121122 std: :s t r ing xmlFaul t ; response ->GetXML(xmlFaul t , t rue) ; pr intf(" \%s\n\n", xmlFault .

    c_str()) ;123 re turn 1;124 }125126 / / Te st f or p o ss i b le e r ro r s127 i f ( ! s t a tus ) {128 printf("Error %s",((s td: :s t r ing)status) .c_str()) ;129 i f ( response)130 delete response;131 re turn 1;132 }133134135 std: :s t r ing answer = (s td: :s t r ing)((*response)[" t lsecho: t lsechoResponse"][" t lsecho:hear"

    ]) ;136 std: :cout

  • 8/8/2019 Ws Programming Tutorial

    37/53

    5.3 Client

    MessageAttribute object and a MessageContext object. After the payload has been wrapped within themessage it gets transmitted in almost the same way like before, see lines following by line 84. The remainderof the source code is identical to the Echo Client.

    37

  • 8/8/2019 Ws Programming Tutorial

    38/53

  • 8/8/2019 Ws Programming Tutorial

    39/53

    6 Secure Echo Web Service

    The TLS Echo Web Service, which was presented in the previous chapter, was able to control the access tothe HED on a very low layer. For the administration of a large VO the kind of security may be too general.Thus, it is recommended to have a more ne-grained security. This chapter discusses how to install a morecomplex security such that it is possible to limit the access of certain resources to particular users and toconstrain their rights on the workstation.

    The security framework of ARC is based on the same concept of modularity as HED. To extend the securityof a MCC or a service one only needs to modify the server conguration le. That is done by including aSecHandler element into the component or service which contains a PDP element. A small example of achain component containing a SecHandler is shown in Listing 6.1. Within the element Component , whichrealises a HTTP layer, an element SecHandler is located. It contains three attributes. The attribute nameis arc.authz , the event attribute is incoming and the id attribute which is auth . While id is only an optionalparameter, the attribute name causes a certain SecHandler to be loaded. In case the attribute name isassigned to arc.authz , the SecHandler provides the functionality of authentication and is able to permit orto deny the access to the next layer. Each MCC or Service usually implements two queues of SecHandlers one for incoming messages and one for outgoing messages. The attribute event attaches the present oneto the incoming queue. SecHandlers are able to intervene the message ow by: manipulating the messagecontent, manipulating the message attributes or to disrupt messages. Within one component, SecHandlersare executed sequentially in the order in which they were attached to the queue. If any of them fails,message processing fails as well [4].

    In order to decide how the SecHandler shall modify the message, so called PDP (Policy Decision Point)are used. Within the example a PDP named simplelist.pdp is inserted within the SecHandler element. Themechanism of this PDP uses a le which contains a list of identities. If the current identity is on the list,the PDP returns a positive result to the SecHandler . In general more than one PDP can be dened withinone SecHandler . The default behaviour in that case is to execute all PDPs sequentially until one fails suchthat a negativ result will be returned or all return a negativ result such that also a positive result will bepassed to the SecHandler .

    Listing 6.1: Example of a SecHandler within the component http.service

    1 2 POST

    3 4 5 6

    Due to the fact, that presenting all SecHandlers and PDPs would go beyond the scope of an introducingtutorial, only a small set of them will be introduced here in detail. Nevertheless, the Tables 6.1 and 6.2 shallgive a rst overview about existing SecHandlers and PDPs . For further reading it is recommended to consultthe document Security framework of ARC1 written by Weizhong Qiang and Alexandr Konstantinov. Thepresent chapter is closly related to it.

    The Secure Echo Web Service which will be presented in this chapter, is using the SecHandlers : inden-tity.map and arc.authz , and the PDPs : allow.pdp, simplelist.pdp and arc.pdp .

    39

  • 8/8/2019 Ws Programming Tutorial

    40/53

    6 Secure Echo Web Service

    Table 6.1: List of built-in SecHandlers

    identity.map Maps the identity of the user to an identity of the workstation.arc.authz Grants access to the next layer.delegation.collector Processes a request for another service located on a different HED. A

    certicate, which has a delegation policy embedded, is transfered to theservice running that SecHandler . Once the has been extracted and ver-ied it will be transfered to the requested service. The policy is nowavailable within the HED of the service such that the client is enabledto access the service.

    usernametoken.handler Generates the WS-Security username-token and adds it into the SOAPheader of outgoing messages. In case of incoming messages the SecHan-dler extracts the WS-Security username-token out of it. The WS-Security standard extends SOAP and describes i.e. how to attach signa-tures and encryption header to SOAP messages.

    Table 6.2: List of built-in PDPs

    allow.pdp Always returns a positive result.deny.pdp Always returns a negative result.simplelist.pdp Renders a positive result in case the identity corresponds to the listed

    ones and additionally maps the identity to an user of the workstation.arc.pdp Evaluates the result based on a policy XML le.delegate.pdp Similar to arc.pdp a policy le will be evaluated. But here, the policy

    document is extracted and transfered by delegation.collector.pdpservice.invoker Establishes a connection to special service in order to get a policy deci-

    sion. The PDP service implements the same functionality as ARC PDP,

    except that the evaluation request and response is carried by SOAP mes-sages. The benet of the PDP Service and the PDP Service Invoker isthat the policy evaluation engine can be accessed remotely and main-tained centrally.

    6.1 Service

    Listing 6.2 contains the source code of the Secure Echo Web Service. As one can see, the only difference,compared to the source code of the previous section, is the additional code to process the SecHandler startingat line 92. Obviously only the incoming queue is processed and in case the SecHandler fails, the SOAP servicereturns a fault message. The le, which is revealing a lot more information, is the server conguration le

    which is shown in Listing ?? . To enable SecHandlers to work with identities, it is almost essential toutilise the TLS layer. The TLS layer extracts the identity such that it later can be used to process theSecHandler . In line 23 and line 24 two additional plugins are named to be loaded which are implementing of the SecHandlers and PDPs . The rst SecHandler is declared at line 39. The PDP allow.pdp always returnsa positive result, such that everyone who passes the SecHandler is mapped to the user nobody . The secondSecHandler limits the access to the SOAP services using the arc.authz SecHandler and the simplelist policy,see line 45. A similar example was already shown in Listing 6.1. The simplelist policy returns a positiveresult if the identity of the certicate corresponds to an identity within the le clientlist.txt . A small exampleof such a le is displayed in Listing 6.3.

    Listing 6.2: Source code of the Secure Echo Service.

    1 #include 2 #include 34 #include 56 #include " secechoservice.h"

    40

  • 8/8/2019 Ws Programming Tutorial

    41/53

    6.1 Service

    78 /* * 9 * M e th o d w h ic h i s c a pa b le t o p r oc e ss t he a rgu m en t P l u gi n A rg u m en t .

    10 * I n i ti a li z e s t h e s e rv i ce a n d r e t u r ns i t .11 * I t i s n ee de d t o l o a d t h e c la ss a s a p lu gi n .12 */ 13 sta t ic Arc: :Plugin* get_service(Arc: :PluginArgument* arg)14 {15 Arc: :ServicePluginArgument* mccarg = dynamic_cast (arg) ;16 i f ( !mccarg) re turn NULL;17 re turn new ArcService: :SecEchoService((Arc: :Config*)(*mccarg)) ;18 }1920 /* * 21 * T h is v a ri a bl e i s d e fi n in g b a si c e n ti t ie s o f t h e i m pl e m en t e d s e rv i ce .22 * I t i s n ee de d t o g et t he c or re ct e nt ry p oi nt i nt o t he p lu gi n .23 * @see P lug in#ge t_ ins t ance ( )24 */ 25 Arc: :PluginDescriptor PLUGINS_TABLE_NAME[] = {26 {27 "sececho", / * U ni qu e n am e o f p lu gi n i n s co pe of i t s k in d * / 28 "HED:SERVICE", /* Type / kind of plugin */ 29 1, /* Ve rs io n of pl ugi n (0 if not ap pl ic ab le ) */ 30 &get_service /* Pointer to constructor funct ion */ 31 },32 { N UL L , N U LL , 0 , N U L L } /* The array is terminated by element */ 33 }; /* with all components set to NULL */

    34353637 using namespace Arc;3839 namespace ArcService40 {4142 /* * 43 * C o n st r uc t o r. C a ll s t h e s u pe r c o ns t ru c to r , i n i ti a li z i ng t he l o gg e r a n d 44 * s e tt i ng t he n a me s p ac e o f t h e p a yl o ad . F u r th e rm o r e t h e p r ef i x a nd s u ff i x w i ll45 * e x tr a c te d o ut o f t he C o nf i g o b je c t ( E l em e nt s w e re d e cl a re d i n si d e t h e H ED 46 * conf igu ra t ion f i l e ) .47 */ 48 SecEchoService: :SecEchoService(Arc: :Config *cfg) : Service(cfg) , logger(Logger: :

    rootLogger , "Echo")49 {50 ns_["sececho"]="urn:sececho";51 pref ix_=(std: :s t r ing)((*cfg)["pref ix"]) ;52 suff ix_=(std: :s t r ing)((*cfg)["suff ix"]) ;53 }5455 /* * 56 * D e c on s t ru c t or. N o th i ng t o b e d o ne h e re .57 */ 58 SecEchoService: :~SecEchoService(void)59 {60 }6162 /* * 63 * M e th o d w h ic h c r ea t es a f a ul t p a yl o ad 64 */ 65 Arc: :MCC_Status SecEchoService: :makeFault (Arc: :Message& outmsg , const s td: :s t r ing &

    reason)66 {67 logger.msg(Arc: :WARNING , "Creat ing faul t ! Reason: \"%s\"" , reason);68 Arc: :PayloadSOAP* outpayload = new Arc: :PayloadSOAP(ns_, t rue) ;69 Arc: :SOAPFault* faul t = outpayload ->Faul t ( ) ;70 i f ( fau lt ) {71 faul t ->Code(Arc: :SOAPFault : :Sender) ;72 faul t ->Reason(reason);73 };74 outmsg.Payload(outpayload);75 re turn Arc: :MCC_Status(Arc: :STATUS_OK);76 }7778 /* * 79 * P r oc e s se s t he i n co m in g m e ss a ge a n d g e ne r at e s a n o u tg o in g m e ss a ge .80 * R e tu r ns t he i n co m in g s t ri n g o r di n ar y o r r e ve r se - d e pe n d in g o n t h e o p er a ti o n 81 * r e qu e s te d .82 * @ p ar a m i n ms g i n co m in g m e ss a ge83 * @ p ar a m i n ms g o u tg o in g m e ss a ge84 * @ r et u rn S t at u s o f t h e r e s u lt a c hi e ve d 85 */ 86 Arc: :MCC_Status SecEchoService: :process(Arc: :Message& inmsg, Arc: :Message& outmsg)87 {

    88 l ogge r.msg(Arc : :DEBUG, "Secure Echo Web Se rv ice has been s t ar t ed . . . " );899091

    41

  • 8/8/2019 Ws Programming Tutorial

    42/53

    6 Secure Echo Web Service

    92 / * * P r o c e ss e s t he S e c Ha n d le r s o f t he s e rv i ce * / 93 l ogge r.msg(Arc : :DEBUG, "Secure Echo Web Se rv ice : Current C l ien t has the DN: \ "%s \ "" ,

    inmsg.Attr ibutes()->get("TLS:PEERDN")) ;9495 i f ( !ProcessSecHandlers( inmsg,"incoming")) {96 logger.msg(Arc: :DEBUG, "Secure Echo Web Service: Didnt passes SecHandler!") ;97 r e tu rn makeFaul t (outmsg , "Access to th is s e rv i ce i s no t pe rmi tt ed ! " );98 }else{99 logger.msg(Arc: :DEBUG, "Secure Echo Web Service: Passed SecHandler!") ;

    100 }101 / * * * / 102103104105106 / * * B o t h i n p ut a n d o u t pu t a re s u p po s ed t o b e S O AP * / 107 Arc : :Pay loadSOAP* inpayload = NULL;108 Arc: :PayloadSOAP* outpayload = NULL;109 / * * * / 110111 / * * E x t ra c ti n g i n c om i ng p a y l o ad * / 112 t ry {113 inpayload = dynamic_cast (inmsg.Payload()) ;114 } ca tch ( s td : : excep tion& e ) { } ;115 i f ( ! inpayload) {116 logger.msg(Arc: :ERROR, "Input is not SOAP");117 r e tu rn makeFaul t (outmsg , "Received message was not a va lid SOAP message . " ) ;

    118 };119 / * * * / 120121 / * * A n al y zi n g a nd e x ec u te r e qu e st * / 122 Arc: :XMLNode requestNode = (*inpayload)["sececho:secechoRequest"] ;123 A rc : : XM LN od e s ay No de = r eq u es tN o de [ " s ec ec ho : s ay " ];124 std: :s t r ing operat ion = (s td: :s t r ing) sayNode.Attr ibute("operation") ;125 s td :: s tr in g s ay = ( st d :: s tr in g) s ay No de ;126 std :: string hear = "";127 logger.msg(Arc: :DEBUG, "Say: \"%s\" Operat ion: \"%s\"" ,say,operat ion);128129 / / C om p ar e s t ri n gs w i th c o ns t an t s d e fi n ed i n t h e h e ad e r f i le130 i f (operat ion.compare(ECHO_TYPE_ORDINARY) == 0)131 {132 hear = pref ix_+say+suff ix_;133 }134 else i f (operat ion.compare(ECHO_TYPE_REVERSE) == 0)135 {136 i nt l en = say. length ( ) ;137 i nt n ;138 s td : : s t ring r eve r se = say ;139 f or ( n = 0 ;n < l en ; n ++ )140 {141 r ev er se [ l en - n - 1 ] = s ay [ n ];142 }143 hear = p ref ix_+ reve r se +su ff ix_ ;144 }145 else146 {147 r e tu rn makeFaul t (outmsg , "Unknown opera tion . P l ease use \ "o rdinary \ " o r \ "

    reverse\"") ;148 }149 / * * * / 150151 outpayload = new Arc: :PayloadSOAP(ns_);152 outpayload ->NewChild("sececho:secechoResponse") .NewChild("sececho:hear")=hear;153154 outmsg.Payload(outpayload);155 {156 std: :s t r ing s t r ;157 outpayload ->GetDoc(str, t rue) ;158 logger.msg(Arc: :DEBUG, "process: response=%s",s t r ) ;159 };160161 l ogge r.msg(Arc : :DEBUG, "Secure Echo Web Se rv ice done . . . " );162 re turn Arc: :MCC_Status(Arc: :STATUS_OK);163 }164165166 } / /namespace

    The rst part of an entry needs to be the distinguished name (DN) of the current client. A DN is a stringwhich represents a user uniquely and is created using the identity of the certicate. To get the correct DN of a client one can use the TLS Echo Web Service and check the log-le. The second part of an entry speciesthe user the identity shall be mapped to. In the present case, the identity will be mapped to griduser . Incase the policy is unable to match the identity, the PDP returns a negativ result. The SecHandler within the

    42

  • 8/8/2019 Ws Programming Tutorial

    43/53

  • 8/8/2019 Ws Programming Tutorial

    44/53

    6 Secure Echo Web Service

    1 2

    10 11 /var / run/arched.pid12 /var/ log/arched. log13 14 15 /tmp/arc/ tutor ia l / l ib/16 /usr / l ib/arc/17 18 mcctcp19 mcct ls

    20 mcchttp21 mccsoap22 23 arcshc24 ident i tymap25 secechoservice26 27 28 29 6000030 31 32 33 . /serviceKey.pem34 . /serviceCert .pem35 . /c l ientCA.pem36 37 38 POST39 40 nobody41 42 43 44 45 46 47 48 49 50 ^/sececho $ 51 52 53 54 [ 55 ]56

  • 8/8/2019 Ws Programming Tutorial

    45/53

    6.2 Client

    Listing 6.3: Appearence of the le used by simplelist.pdp .

    $ cat c l ient lis t . txt" /C=US/S=Maine/OU=Literary character /O=Ka-Tet Corp. /CN=Roland Deschain" gr iduser"/C=US/S=Maine/OU=Literary character /O=Ka-Tet Corp. /CN=Susannah Dean" gr iduser$

    in a manner such that the state INDETERMINATE will be induced. Two things are checked within it: theidentity based on authentication method Shibboleth and the path of the requested HTTP URL. Due to thefact, that the HTTP path is tting to the requested one, but the authentication was not done by Shibboleth,the rule is not able to decide for a DENY or a PERMIT state the rule produces an INDETERMINATEstate. The last rule is dened in line 46. It is constructed such that is permits the access to the HTTPmethod GET. One can see, that within the server conguration le the Web Service uses the method POST.If a client wants to access the Service and reaches the PDP, a couple of requests are generated which aredescribing the manner the client wants to access the serivice. Some of these request will concern the HTTPmethod GET. In these cases, the rule returns NOT APPLICABLE. In the cases where the requests for aHTTP method is missing (i.e. in the request which only concerns the SOAP access) the state of the rule

    will be INDETERMINATE.

    To get an impression in how the requests look like, one can check the log-le (the log level needs to be setto VERBOSE).

    6.2 Client

    The security introduced to the server has no effect on the client, such that the source code is completelyidentical. Even the client conguration le doesnt need to be changed.

    Shibboleth is an open-source implementation for authentication and authorization based on the XML standard SAML (Se-curity Assertion Markup Language).

    45

  • 8/8/2019 Ws Programming Tutorial

    46/53