Linda Ariani Gunawan
email: gunawan@item.ntnu.no

Frank Alexander Kraemer
email: kraemer@item.ntnu.no

Peter Herrmann
email: herrmann@item.ntnu.no

Behavioral Singletons to Consistently Handle Global States of Security Patterns

Secure systems are usually complex since stateful security mechanisms like authentication and authorization have to be integrated into the functional behavior at various places. The security operations are, in general, interdependent such that events at one place may influence the behavior at other places. Thus, the composed specification of a system is neither easy to understand nor to analyze, and a faulty integration of the security mechanisms is often overseen. In this paper, we introduce the concept of singletons into our model-based engineering technique SPACE which facilitates a straightforward integration of security aspects. The behavior of a security protocol is encapsulated in a building block using a two-view interface contract. One view of the contract is quite simple and suffices for the correct integration of the block into a system specification. The other view is more complex but has to be considered only by the block designers to verify that the behavioral model in the block fulfills its interface contract. We exemplify the singletons by means of an authorization mechanism and discuss how to prove that the two views of its interface contract are consistent.

Introduction

Developing secure applications is a difficult and error prone task. One of the reasons for this is that many security mechanisms are hard to understand and realizing them requires in-depth knowledge [START_REF] Mouratidis | Integrating Security and Software Engineering: Advances and Future Vision[END_REF]. Moreover, although developers with sufficient security expertise manage to provide implementations of those mechanisms, their integration in application designs poses yet another challenge due to the crosscutting nature of the security aspects [START_REF] Viega | Applying Aspect-Oriented Programming to Security[END_REF][START_REF] Georg | An Aspect-Oriented Methodology for Designing Secure Applications[END_REF][START_REF] Mouheb | Aspect-Oriented Modeling for Representing and Integrating Security Concerns in UML[END_REF]. Security functions are usually accessed by several parts of an application, such that a change in the security functionality has an impact on the rest of the application. This holds particularly for the integration of stateful security mechanisms into a system design which increases the complexity of the model dependencies further, since events at one place of a system may influence the behavior at other places.

Reusing proven, well-tested solutions is one way to address the problem of lack of expertise in some specific domains. It has also been recognized as an important key to build high-quality software systems in an efficient and costeffective manner [START_REF] Heineman | Component-Based Software Engineering: Putting the Pieces Together[END_REF]. Solutions are more easily reusable when they are modular, highly cohesive, and loosely coupled with external components [START_REF] Stevens | Structured Design[END_REF]. Software libraries in the form of APIs are available for reuse also for security protocols. Nevertheless, the need to integrate these APIs into various places of an application aggravates understanding the composed system. Therefore, we require an approach that not only promotes reuse but also modularizes crosscutting concerns like security aspects and facilitates seamless integration with applications.

Previously, we developed the model-based approach SPACE [START_REF] Kraemer | Engineering Reactive Systems: A Compositional and Model-Driven Method Based on Collaborative Building Blocks[END_REF] in which a system specification is modularized with self-contained building blocks describing the behavior of several functionalities in UML activities. In turn, these blocks can contain any number of inner activities referenced by call behavior actions. On average, more than 70% of an application specification can be composed from reusable blocks taken from various domain-specific libraries [START_REF] Kraemer | Automated Encapsulation of UML Activities for Incremental Development and Verification[END_REF]. To integrate a block correctly into its environment, it is augmented with a contract in the form of a UML state machine which describes the behavior visible at the interface between the block and its environment. Moreover, the formal semantics of the activities [START_REF] Kraemer | Reactive Semantics for Distributed UML Activities[END_REF] makes it possible to verify block compositions using the model checker included in Arctis [START_REF] Kraemer | Tool Support for the Rapid Composition, Analysis and Implementation of Reactive Services[END_REF], the tool-set for SPACE.

To deal with stateful, crosscutting concerns while also minimizing dependencies, we introduce the concept of behavior singletons which is inspired by the corresponding design pattern for programming described by Gamma et al. [START_REF] Gamma | Design Patterns: Elements of Reusable Object-Oriented Software[END_REF]. In particular, we discuss a new kind of block that may be represented by various call behavior actions in different parts of a system model which, however, all refer to a single behavior instance. Thus, a security aspect can be specified in this so-called singleton block independently from the application-specific functionality of a system. In contrast to Gamma et al.'s singleton, we also consider the behavior at the interface of singleton blocks by supplementing it with a behavior contract. The interface behavior is specified in such a way that inconsistencies due to the usage of the singleton at many parts of the application are ruled out if both the singleton and its environment obey the interface. Singleton blocks containing relevant security features can be easily reused since the automatic model checker included in Arctis is sufficient to prove that a singleton block instance is correctly integrated into its environment. The proof that a security mechanism guarantees the interface contracts of all singleton block instances, however, is a little more complex, but usually manageable as pointed out in Sect. 4.

A Social Application Example Modeled in SPACE

An Arctis building block may contain any number of inner activities referenced by call behavior actions that are connected through some "glue logic". Therefore, a system specification consists of building blocks forming a tree structure with a system activity (i.e., the outermost block) as the root and simple activities (i.e., blocks that do not contain any other call behavior action) as the leaves. Figure 1 shows the system specification of the example. It is an Android application which enables users to obtain their friends' geographical locations, manage their friend lists, and record their own current locations. This system consists of ten call behavior actions which are further decomposed into other call behavior actions as depicted partially in Fig. 2. The Petri net-like semantics of the activities models behavior as control respective data flows of tokens between the nodes of an activity via its edges. Block c: Communication is initialized when the application starts as delineated by the arrow from the initial node (•) in Fig. 1. This call behavior action refers to an activity that handles messages with the application's peers. Subsequently, the main user interface (UI), whose behavior is encapsulated in block mui: Main UI, is started. Thereafter, the user may choose to use any of the following features:1 toggling the location update service (f 1 ), managing a list of friends (f 2 ), or retrieving friends' locations (f 3 ). Feature f 1 is managed by an event emitted from the UI block through the pins startReportLoc or stopReportLoc. It is supported by block u: Periodic Location Update which, when started, periodically reads the location of the device it is running on. To achieve this, the block utilizes corresponding Android APIs and stores the location on a remote server until the block is stopped. The other features which include retrieval of the user's contact list (f 2 ) and location data (f 3 ) from the server are modeled in a similar way with the remaining building blocks.

The example application employs Google services that can store information like locations, photos or contacts, while also providing RESTful APIs for third-party applications to access them. Here we utilize two APIs, namely Latitude [START_REF]Google Latitude API[END_REF] to handle the location data and Contacts [13] to retrieve the contact list. Since all requests to these services must be authorized, the application uses the authorization protocol OAuth 2.0 [START_REF] Hammer-Lahav | The OAuth 2.0 Authorization Protocol[END_REF]. This protocol is developed to enable a third-party application to obtain a limited access to protected resources hosted in an HTTP service with an access token instead of using the resource owner's (i.e., the user's) credentials directly. Before obtaining an access token, the application needs authorization from the user. This is achieved by redirecting the user to an authorization server via a web browser. After a positive authentication and authorization, the user is redirected back to the application with an authorization grant. Thereafter, the grant is used by the application to obtain an access token and a refresh token from the authorization server. By means of the access token, the application finally can access restricted resources for a limited duration. A refresh token is used to obtain a new access token when the current one expires.

The activity encapsulating the behavior of the OAuth protocol is not shown in this paper due to lack of space, but it is referenced by the block o: OAuth 2.0, that is depicted in Fig. 3. In the following, we sketch the external behavior of this block that handles one request to a protected resource at a time. The first request initiates a user's authentication and authorization process through pin getAuthGrant. This step is not managed by the block because it needs to invoke a web client which is treated differently on different platforms. Thereafter, the following requests can be run without the authorization step. The incoming pin cancel of the OAuth block is used to indicate that the user denies the application's request to access his or her resources. The other two outgoing pins are used to report two types of errors: Pin error indicates an error related to the corresponding request, for example, if the requested resource is not found. Pin authError shows an authorization error, for instance, if the authorization code is incorrect or the user has revoked the access grant.

Singleton Building Blocks

In general, the behavior of authentication and authorization protocols is stateful. For instance, in OAuth the user verification and user's consent for access rights are executed once, i.e., upon receiving the first request, while subsequent requests directly use the stored token. Moreover, a new token may need to be obtained when the curent one expires. Such stateful behavior is also common in other protocols, e.g., TLS [START_REF] Dierks | The Transport Layer Security (TLS) Protocol Version 1.2[END_REF], the SASL framework [START_REF] Melnikov | Simple Authentication and Security Layer (SASL)[END_REF], and single sign-on solutions such as SAML [START_REF] Cantor | Assertions and Protocols for the OASIS Security Assertion Markup Language[END_REF].

As mentioned, authorized access to a restricted resource is used at several features of a system. For instance, in our example we use authorization in all the features f 1 (current location update), f 2 (management of user's friend list), and f 3 (last location retrieval) which are not executed in any strict sequence since they can be independently triggered from each other. Therefore, a solution in which authentication is always done by one certain feature is not possible. Furthermore, in a large project, features are likely developed by different engineers, so that global constraints like demanding a "first requestor" would require undesirable additional coordination making the engineering process more complex.

Consequently, we have to consider a certain stateful behavior that uses shared data (e.g., the access token) and a shared state (e.g., when authorization is ongoing) at various places of an application. In object-oriented programming, the access of shared data from various points can be handled using a singleton pattern [START_REF] Gamma | Design Patterns: Elements of Reusable Object-Oriented Software[END_REF]. This pattern ensures that a class has one shared instance only, and provides a single, global access point to this instance. We adapt this concept in the form of singleton blocks. Instead of referring to different instances of a behavior description, using a singleton pattern means that different call behavior actions of the same type refer to a single behavior instance. Hence, in Fig. 2 the three call behaviors oa, so, and s point to the same block, namely, Singleton OAuth 2.0.

The singleton pattern, however, does not solve the problem mentioned in the introduction that events at one feature may influence the behavior of the others which makes the understanding of the overall system behavior more difficult and is a common source of errors. Therefore, we provide the singleton blocks with interface behavior contracts (Sect. 3.2) that guarantee the absence of these inconsistencies.

Interactions with a Singleton

In SPACE and Arctis, a system consisting of various building blocks is implemented by an automatic two-step process: First, a component-based description modeled by state machines is derived from the building blocks using a special model transformation [START_REF] Kraemer | Transforming Collaborative Service Specifications into Efficiently Executable State Machines[END_REF]. Second, code is generated from the state machines [START_REF] Kraemer | Aligning UML 2.0 State Machines and Temporal Logic for the Efficient Execution of Services[END_REF]. In the first step, a singleton is treated differently since it is implemented as a separate state machine. Thus, on the code level it communicates with the state machines of its environment asynchronously using message passing. Sending towards a singleton is easy: When a client feature3 wants to send a message towards a singleton, it just uses the address of the state machine realizing the singleton and passes a message to it.

Sending from a singleton towards the client feature is more complicated since there may be more than one feature, and the singleton needs to determine the actual receiver. In some cases, the singleton only has to process a simple request that can be answered immediately such that no waiting is involved, and a request can be processed completely without being interrupted by other requests. In this case, the singleton simply has to send the response to the originating client feature of the request. However, this is not the general case. In most situations, the request needs to be buffered since other stateful behavior has to be executed to compute a response. Sometimes, the singleton may also require to store all known client features and dispatch certain events only to some of them. For this reason, the singleton must be able to handle addresses of the client features explicitly using variables. To realize this technically, we require that all incoming and outgoing parameters are of the special data type SingletonData. An object of this type contains the address of the originator that is used to determine to which client feature a signal has to be passed. Other data can be carried by this kind of object as well since it is a wrapper for object flows. Moreover, as several call behavior actions utilizing the same singleton may be synthesized into the same target state machine, we also need to keep track of which call behavior instance sent a certain request. This is also reflected by the address component of SingletonData.

The state machine implementing the singleton is created by the runtime support system when one of the other state machines realizing the system sends its first signal towards the singleton. For the client feature calling the singleton, this is transparent since sending the signal is buffered regardless. The singleton state machine is stopped once the main component terminates.

Behavioral Contract of a Singleton

As discussed in the introduction, an ordinary building block is protected by one behavioral contract specifying in which sequence its parameters may be used. Likewise, the interaction between a singleton and its environment is restricted which, however, is expressed by means of two different contracts:

Single-session: Here, the interaction between the singleton and a single client feature is described. Multi-session: This contract models the overall interaction between the singleton and all client features that are linked to it.

The single-session contract is usually relatively simple and therefore suited to guide an integration of the singleton to a particular client feature. In contrast, the multi-session contract is more complex, since it handles several client features. Fortunately, however, this contract has to be considered only by the author of the singleton, who has to deal with the challenge to coordinate multiple invocations of a single stateful behavior anyhow. A single-session contract is expressed in the form of a so-called External State Machine (ESM, [START_REF] Kraemer | Automated Encapsulation of UML Activities for Incremental Development and Verification[END_REF]). This is a special UML state machine depicting the possible ordering of externally visible events on the activity parameter nodes. It specifies properties to be kept by both the activity itself and its environment; and thus shows how to compose the activity correctly with others. The semantics of activities is defined in [START_REF] Kraemer | Reactive Semantics for Distributed UML Activities[END_REF], and the automatic verification that block compositions are correct is supported by the model checker included in Arctis [START_REF] Kraemer | Tool Support for the Rapid Composition, Analysis and Implementation of Reactive Services[END_REF]. The ESM depicting the single-session contract of our singleton OAuth example is presented in Fig. 4. In the begining, the initial transition to state idle is executed. Thereafter, only the transition labeled with request/ to state active can be taken. It indicates that the singleton receives an incoming flow via parameter node request (see Fig 3). Afterwards, the singleton can output either one of the events response, error, authError, or getAuthGrant. The first three events trigger a transition to state idle modeling that the singleton is ready to receive another request. getAuthGrant triggers a transition to state authorizing which requires the environment to provide an incoming flow through node cancel A multi-session contract is specified with an Extended ESM or EESM [START_REF] Slåtten | Contracts for multi-instance UML activities[END_REF]. This extends the ESM with variables, transition guards, operations, arithmetic and predicate logic, such that event constraints related to the state of multiple invocations can be specified. The EESM of activity Singleton OAuth 2.0 is shown in Fig. 5. We assume that the singleton is linked with n client features. The identifiers of those features that have sent a request but not yet received the corresponding result (i.e., the active features) are stored in the set variable act which, in consequence, uses the powerset P (1..n) as its data type. The variable authno of type 1..n indicates at which client feature an authorization step is taken place.

The initial transition sets act to the empty set. 4 When a request is received at the client feature i, the subsequent transition is taken. Here, the transition guard i / ∈ act must be fulfilled to comply with the restriction that each feature can only send one request at a time. The operation act = act ∪ {i} specifies that feature i is an element of act after executing the transition. The operation authno = i states that i is the feature via which the authorization procedure will be handled. The invocation of the authorization is indicated by the transition from state unauthorized to authorizing. When authorization code is received via pin authCode, the singleton enters state authorized. If the authorization is canceled, the singleton enters state idle provided that authno is the only feature that is currently active, or state unauthorized when there is at least one other active feature i. In the latter case, a new authorization starts at feature i. In the event of successful authorization, a request from one feature is answered by a response, an error message or an authorization error message as specified by the four corresponding transitions from state authorized. Since any inactive feature may send one request at any time, we use a self transition labeled with request(i) in states unauthorized, authorizing, and authorized of the EESM. Of course, the two contracts have to be consistent, and we discuss in the next section how that can be guaranteed.

∃i, j ∈ 1..n : i ∈ act ∧ j ∈ act ∧ i = j ∃i ∈ 1..n : i ∈ act ∧ i = authno act = act \ {i} authno = j ∃i ∈ 1..n : act == {i}

Consistency of Singleton Contracts

To guarantee consistency of the two singleton contracts, we have to prove formally that the multi-session contract is a correct refinement of the single-session one. As an example, we sketch in the following parts of the proof that the Singleton OAuth 2.0 EESM in Fig. 5 fulfills the ESM in Fig. 4 for each client feature in a specification. Intuitively, it shows that the first transition of the EESM is mapped to the initial transitions of the ESMs for all client features. Each of the other EESM transitions corresponds to one ESM transition of a client feature while all other features do not execute any transition. We mark the EESM as Φ while Ψ [k] refers to the ESM for the client feature k. In [START_REF] Abadi | The Existence of Refinement Mappings[END_REF], Abadi and Lamport verify that so-called refinement mappings (RM) can be used for refinement proofs, i.e., that ∀k ∈ 1..n : Φ ⇒ Ψ [k] holds. An RM is a function from Φ to Ψ [k] that fulfills the following two properties: 51. An initial state of Φ is mapped to an initial state of Ψ [k]. 2. A transition of Φ is mapped to a transition of Ψ [k] or to a stuttering step in which the variables of Ψ [k] do not change. In the former case, the labels of the transitions have to be identical.

For the verification that our EESM Φ in Fig. 5 implements the ESM Ψ of every client feature k depicted in Fig. 4, we use the following mapping:

Ψ [k].state IF Φ.state = initial THEN initial ELSE IF k / ∈ Φ.act THEN idle ELSE IF Φ.state = authorizing ∧ Φ.authno = k THEN authorizing

ELSE active

It reflects that the initial state of the EESM is mapped to the one of the ESM. The ESM of client feature k is in the state idle if in the EESM k is not an element of the variable act. If Φ is in state authorizing and k is the value of variable authno, then the authorization process at feature k was invoked and, in consequence, its ESM is in state authorizing. In all other cases, the ESM is in state active.

We have to verify that the mapping implements the two properties listed above. The first property is trivially fulfilled by the first IF-statement of the mapping. To prove the second property, we have to verify for every transition of the EESM that it is mapped to a transition or a stuttering step of the ESM. As a full proof sketch would exceed the space limit, we exemplify that by verifying the EESM transition request(i) from state idle to state unauthorized. Here, we distinguish the cases i = k and i = k. In the former case, k is not an element of act due to the transition guard and, according to the mapping, the ESM is in the state idle before the execution. Thereafter, k is an element of act. Since the EESM reaches the state unauthorized, the ESM will be in state active afterwards. In consequence, the EESM transition is mapped to the ESM transition from idle to active which, moreover, uses the same label request.

The case i = k is also straightforward. If k is in the variable act prior to the execution of the transition, the ESM is in state active while it is otherwise in idle. Since we assume i = k, k is neither added to nor removed from act by executing the transition such that the ESM does not change its state. Thus, in this case the EESM transition is mapped to a stuttering step.

While the proof steps are similarly simple for most of the other EESM transitions, in three of them we need additional invariants about the EESM which have to hold in the initial state and are not falsified by any transition. Due to the simple structure of the EESM with only two variables, however, it was very easy to find suitable invariants.

To assure that the singleton activity in Fig. 3 fulfills the EESM and, as proven above, also the ESMs, we have to carry out another refinement proof. Due to the space limit, this verification cannot be pointed out here but similar proofs are discussed in [START_REF] Slåtten | Contracts for multi-instance UML activities[END_REF].

Integrators who create applications that use a singleton do not have to be experts in a specific domain like, for instance, security. Moreover, when developing a client feature, they do not need to take into account whether other features in a system use the same singleton. Only the single-session contract attached to the singleton block must be respected. This includes alternative behaviors as exemplified by the OAuth example for which the result of a request can be "delayed" by an authorization step or given out immediately since the authorization has been executed in another client feature. The ESM in Fig. 4 shows these alternatives as separate transitions starting from state active. A client feature must be ready to handle all alternatives since failing to fulfill one may result in a deadlock. In summary, the client feature must obey the ESM contract which can be guaranteed without having to coordinate certain global constraints. In addition to the contract, the integrators have to ensure that every flow into a singleton block carries an object of type SingletonData that is provided with data if required. Since the flows from the block are also of type SingletonData, data that is sent from the singleton has to be extracted from the corresponding object in the received token.

A client feature i may notice the existence of other client features (e.g., by not needing to authorize a user). However, since the interferences by these client features do not change the state of the single-session contract of i, the already proven consistency between the two contract views effectively rules out that the other features may harm i. Thus, the singletons fulfill also the demand stated in Sect. 3 that different developers should be able to build in blocks without having to coordinate global constraints with other engineers.

The "price" to offer singletons enabling independent integration, however, is that their development is more complex. This mainly results from the fact that due to the single instance and global access principles, multiple incoming flows can occur anytime, in any order, and from many different features. These flows may access a shared resource that needs to be kept consistent. Therefore, the authors are often required to design a singleton which maintains mutual exclusion among those events. One way to make multiple incoming flows mutually exclusive is to buffer them and handle them one by one according to, for example, their arrival sequence. Applying this strategy to the OAuth 2.0 protocol results in the Singleton OAuth 2.0 activity depicted in Fig. 3. Block b: Reactive Buffer, which is taken from one of our libraries, is used to buffer requests. If a request is received when the buffer is empty, the request is given out immediately, otherwise it is buffered. The pin next is used to get a subsequent request, if available, after the inner block o: OAuth 2.0 completes the execution of the current request.

In order to send messages to correct client features, the singleton must handle their addresses explicitly in the singleton block design. The singleton author, therefore, needs to ensure that every output of a singleton block contains such an address. This address can be obtained from a SingletonData object which is carried by every incoming flow and set automatically by the Arctis runtime support system. If the singleton needs to execute other stateful behavior, the address of an incoming flow can be stored temporarily in a variable, e.g., temp in the singleton OAuth example.

Furthermore, the author of a singleton block needs to create the single-session and multi-session contracts and to verify that they are consistent as sketched in Sect. 4. Since a block is created once and, in general, reused many times (see [START_REF] Kraemer | Automated Encapsulation of UML Activities for Incremental Development and Verification[END_REF]), however, the higher cost of constructing such a block will be rewarded. For instance, the singleton block OAuth 2.0 is sufficiently versatile to be applied in merely all systems using this authorization protocol [START_REF] Hammer-Lahav | The OAuth 2.0 Authorization Protocol[END_REF].

Related Work

To the best of our knowledge, this is the first article on singleton patterns that also include behavior descriptions with interface contracts and are above programming language level. In [START_REF] Gamma | Design Patterns: Elements of Reusable Object-Oriented Software[END_REF], Gamma et al. introduce singletons as a creational pattern, but do not handle elaborate behavior.

Related to the crosscutting nature of security concerns, many approaches that use aspect-oriented concepts, such as AOP, AOM, AOD, and AOSD, have been proposed (see, e.g., [START_REF] Viega | Applying Aspect-Oriented Programming to Security[END_REF][START_REF] Georg | An Aspect-Oriented Methodology for Designing Secure Applications[END_REF][START_REF] Mouheb | Aspect-Oriented Modeling for Representing and Integrating Security Concerns in UML[END_REF][START_REF] Jürjens | Dynamic Secure Aspect Modeling with UML: From Models to Code[END_REF][START_REF] Pavlich-Mariscal | Enchancing UML to Model Custom Security Aspects[END_REF][START_REF] Jézéquel | Model Driven Design and Aspect Weaving[END_REF]). Security mechanisms are modeled as aspects which are automatically weaved in at joint points of a primary specification based on rules defined as pointcuts. This approach, like ours, modularize security aspects so that they can be analyzed in isolation. However, our singleton-based integration of security aspects into a system specification is facilitated by explicit behavior contracts. In the aspect-oriented approaches, the binding between security and primary models is tightly coupled [START_REF] Alexander | Challenges of Aspect-oriented Technology[END_REF], hidden and dispersed in the joint points, pointcuts, and weaving algorithm.

With regards to model-based secure system development, various approaches have been published [START_REF] Jürjens | Secure System Development with UML[END_REF][START_REF] Basin | Model Driven Security: From UML Models to Access Control Infrastructures[END_REF][START_REF] Doan | MAC and UML for Secure Software Design[END_REF]. UMLsec [START_REF] Jürjens | Secure System Development with UML[END_REF] is a UML profile that is used to incorporate security-related information such as fair exchange and secure communication links in various UML diagrams and hence facilitating the development of security-critical systems. SecureUML [START_REF] Basin | Model Driven Security: From UML Models to Access Control Infrastructures[END_REF] is a modeling language designed to integrate information relevant to Role-Based Access Control policies into application models defined with the UML. Similarly, integration of Mandatory Access Control with UML is proposed in [START_REF] Doan | MAC and UML for Secure Software Design[END_REF]. However, in these approaches, security aspects are tightly coupled with the functional models and therefore designing a secure application requires in-depth security knowledge or a close cooperation with security experts. With our approach, domain-specific specialists can work separately with their own building blocks and due to the behavioral contracts of blocks their models can be integrated seamlessly.

Conclusion

We have applied the singleton pattern known from object-oriented programming to a component-driven (resp. collaborative) approach using model-based engineering. The novelty lies in the consideration of the behavioral aspect by means of contracts, i.e., in which sequence data may be sent between the singleton and the feature(s) using it. With these contracts, we can determine that the singleton is used in a correct way. Further, the need to support single-session contracts compels the author to guarantee that the client features are treated independently from each other by the singleton. The approach is theoretically sound (see Sect. 4) and also appealing from a practical viewpoint. The presented example application is a prototype of a realistic application and was fully implemented with our tool-support.

With respect to the expertise required to use the approach, there is an inherent advantage: Using the singleton blocks is rather simple, since here only the simplified version of the contract has to be considered. Creating a singleton is more subtle, since one has to take the handling of multiple invocations of a stateful behavior from client features into account. Nevertheless, this is part of the intricacies of, e.g., a security protocol that have to be understood by the author of a singleton anyhow. We are also investigating the applicability of behavioral singletons for other problem domains such as communication and dependability.

In the future, we plan to extend the behavioral contracts of building blocks to include security properties, e.g., confidentiality, integrity, and authenticity, in such a way that the security evaluation of an application specification using those blocks is largely based on the security properties of each block. Our goal is to support modular reasoning of a system not only for functional aspects but also for security issues.

Fig. 1 .

 1 Fig. 1. Friends Locator Example

2 Fig. 3 .

 23 Fig. 3. Singleton OAuth 2.0 Activity

Fig. 4 .

 4 Fig. 4. Single-session Contract of The Singleton OAuth 2.0

Fig. 5 .

 5 Fig. 5. Multi-session Contract of The Singleton OAuth 2.0

XMPP Client p: Get Last Location l: Get Contact List ul: Update Location t: Timer g: Get Curr Location u: Periodic Location Update Fig

  . 2. Hierarchy of Blocks from The Friends Locator Example

				«system» Friends Locator
			mui: MainUI			fui: Friends UI	lui: Location UI
		a1: Get AuthCode	a2: Get AuthCode	a3: Get AuthCode
	c: Communication	p: Get Last Location	l: Get Contact List	u: Periodic Location Update
	c: Communication
	x: XMPP Client	h: Message Handler	oa: Singleton OAuth 2.0		so: Singleton OAuth 2.0	ul: Update Location	t: Timer
	x:	h: Message
		Handler
							s: Singleton	g: Get Curr
							OAuth 2.0	Location
			Singleton OAuth 2.0
			b: Reactive Buffer	o: OAuth 2.0
			b: Reactive			o: OAuth 2.0
			Buffer
						...	...

By feature, we refer to a part of an application that performs a certain function.

In our example in Fig.1, this is handled by three call behavior actions of type Get AuthCode. The referred activity utilizes WebView, a webpage viewer for Android.

With the term client feature we refer to a feature that interacts with a singleton.

In the programming-like syntax of the EESMs an assignment is described by = while the equal operator is noted as ==.

In[START_REF] Abadi | The Existence of Refinement Mappings[END_REF], two other properties are mentioned that, yet, are not relevant in our case.

code get cancelled getAuthCode authCode cancel a1: Get AuthCode code get cancelled get AuthCode auth Code cancel ready a2: Get AuthCode code get cancelled getAuthCode authCode cancel


Graham Thomson
email: graham.r.thomson@gmail.com

Sotirios Terzis
email: sotirios.terzis@strath.ac.uk

A Middleware for Pervasive Situation-Awareness

Situation-awareness is the ability of applications to adapt to the current situation of their users. For situation-awareness to be truly pervasive it should support the individual needs of every user, everywhere. We present a middleware for pervasive situation-awareness based on the idea of separating the features of a situation from the specification of how it should be recognised. The features of a situation can be seen as an interface that can be easily customised to satisfy individual user needs, while alternative specifications can be used to recognise a situation in different environments. The middleware views situations as collections of roles that individuals and devices play. Its implementation follows an agent-based architecture where collaborating agents acquire and reason over context data. We also show that the middleware can recognise a variety of highly customised situations using alternative specifications with performance that is acceptable for interactive situation-aware applications in realistic deployment sizes.

Introduction

Situation-awareness is considered a defining characteristic of pervasive computing systems [START_REF] Cook | Pervasive computing at scale: Transforming the state of the art[END_REF]. It refers to the ability of applications to adapt their operation to the current situation of their users through the collection and interpretation of sensor data. More specifically, a situation is an interpretation of sensor data into a higher, domain relevant concept, understandable to users and applications [START_REF] Ye | Situation identification techniques in pervasive computing: A review[END_REF]. Situations can be considered as semantic interpretations of sequences of contexts that describe particular aspects of the overall situation.

The main challenge for situation-awareness is how to recognise high-level concepts from the low-level sensor data. The challenge is confounded by the need for good appreciation of both the characteristics of the underlying sensing infrastructure, and the needs of user applications. To date there has been a lot of work to address this challenge, see [START_REF] Ye | Situation identification techniques in pervasive computing: A review[END_REF] for a recent survey. Approaches take one of two approaches. They either utilise expert knowledge to explicitly specify situations (e.g. [START_REF] Coutaz | Context is key[END_REF][START_REF] Ranganathan | Reasoning about uncertain contexts in pervasive computing environments[END_REF][START_REF] Henricksen | Developing context-aware pervasive computing applications: Models and approach[END_REF]), or learning algorithms to implicitly recognise situations (e.g. [START_REF] Patterson | Inferring high-level behavior from low-level sensors[END_REF][START_REF] Roy | Context-Aware Resource Management in Multi-Inhabitant Smart Homes: A Nash H-Learning based Approach[END_REF][START_REF] Albinali | Structural learning of activities from sparse datasets[END_REF][START_REF] Ye | Using situation lattices in sensor analysis[END_REF]). However, due to the engineering effort required either to specify or learn a wide range of situations, both approaches are typically limited to quite generic situations. For example, they only recognise a generic meeting situation, instead of specific types of meetings that users may be interested in. They also target specific sensing infrastructures, and are typically limited to a small number of environments. As a result, they fail to support the needs of every user, everywhere. They do not support pervasive situation awareness.

We believe that supporting the needs of every user across a wide range of environments can be best achieved by separating the description of situations and their features from the specification of how they are recognised. Our belief is based on the observation that in most domains users are interested in a wide range of specific variants of generic situations. In this context, variants of generic situations can be supported through customisation of the features of situations, while a situation could be specified in multiple ways to allow its recognition across different environments.

We have developed a middleware to support pervasive situation-awareness. The middleware provides a query-based interface that allows situation-aware applications to retrieve notifications about the occurrence of situations. To better deal with the volatility inherent in pervasive computing environments, our middleware follows a loosely-coupled agent-based architecture, with agents collaborating over a publish/subscribe substrate. Each agent is responsible for a particular aspect of the situation recognition process with reasoning over context data supported by a rule engine based on the Rete algorithm.

To demonstrate the expressive power of the middleware, we show that it is able to support recognition of a number of situations in a university environment through a range of specifications that can be easily customised to produce a large number of variants. To demonstrate that its performance is practical for interactive situation-aware applications we focus on the round-trip time of a situation recognition request, basically a summary of the overall performance of the system, and we show that by appropriately distributing the recognition load between agents the performance scales reasonably as the number of entities involved in the situation, and the number of situations to be recognised increases.

In the next section we look at previous work on situation-awareness. We then present our model for the description and specification of situations, followed by a description of our middleware architecture and implementation. This is followed by the evaluation of our middleware. Finally, we draw some conclusions and present some directions for future work.

Related work on situation-awareness

A key requirement for pervasive situation-awareness is the ability to support a large number of situations with limited engineering effort. In this respect, learning-based approaches are typically considered more appropriate as they are better suited for settings where there is a wide range of fairly inaccurate sensors to recognise a variety of situations [START_REF] Ye | Situation identification techniques in pervasive computing: A review[END_REF]. In practice, both specification and learning-based approaches require significant engineering effort.

Specification-based approaches require domain experts to provide the logicbased or ontological specifications for each situation of interest. Learning-based approaches are mostly based on supervised learning techniques. These require the annotation of the examples needed for the learning to take place. In recent years, there has been some work to try and minimize the number of examples, like [START_REF] Albinali | Structural learning of activities from sparse datasets[END_REF][START_REF] Ye | Using situation lattices in sensor analysis[END_REF], by exploiting additional structure and knowledge to simplify the learning task. However, these approaches just trade the effort required for the annotation of the examples, with work by domain experts for the specification of the necessary structure and knowledge. In this context unsupervised learning techniques like [START_REF] Patterson | Inferring high-level behavior from low-level sensors[END_REF][START_REF] Roy | Context-Aware Resource Management in Multi-Inhabitant Smart Homes: A Nash H-Learning based Approach[END_REF] would offer a significant advantage. However, they tend to be limited in scope and restricted to a small set of situations using a specific sensing infrastructure. Of particular note are techniques like [START_REF] Tapia | Activity recognition in the home using simple and ubiquitous sensors[END_REF] that have shown some promise in the identification of user activities such as walking, or sitting down. Such techniques could be utilised as part of the recognition of higher-level user activities.

It would seem that both specification and learning-based approaches are not really appropriate for pervasive situation-awareness. However, as often, most of the situations that need to be recognised are just variants of a small number of generic situations, the key point in keeping the overall engineering effort manageable is to make it easy to produce variants. In this respect, specification-based approaches have an advantage as they are more transparent to applications and users [START_REF] Ye | Situation identification techniques in pervasive computing: A review[END_REF]. This makes the individual situation elements visible, making them easier to vary. This is particularly the case in approaches such as [START_REF] Coutaz | Context is key[END_REF], which provide a well-defined structure for situations.

Another key requirement for pervasive situation-awareness is operation across various environments, i.e. recognition of the same situation in different ways, each aimed for a particular environment. Some specification-based approaches already support this [START_REF] Ranganathan | Reasoning about uncertain contexts in pervasive computing environments[END_REF][START_REF] Henricksen | Developing context-aware pervasive computing applications: Models and approach[END_REF]. However, as they place limited structure over specifications, they make it quite difficult to produce variants of the specified situations, because one needs to fully understand the whole specification. At the same time, ontologies have been used to provide a common vocabulary for and facilitate sharing of situations, e.g. CobraOnt1 . However, they also make it difficult to produce variants of the specified situations, as this requires good appreciation of ontological reasoning.

In conclusion, pervasive situation-awareness requires a specification-based approach that provides a well-defined structure for the specifications, is flexible enough to accommodate promising learning-based approaches, and supports multiple specifications for the same situation.

A model for pervasive situation-awareness

We define situations as semantic interpretations of context information (adopted from [START_REF] Ye | Situation identification techniques in pervasive computing: A review[END_REF]) that represent the high-level activity of an individual or a group of people and the devices they use. The recognition of a situation involves information at the following levels of abstraction: sensor data, context information and situations. Sensor data represent the raw output from sensors. Context information is a structured representation of sensor data. This is a typed relation that represents some property of an entity derived from sensor data and/or other context information. Pieces of context information are combined and interpreted to deduce the situation that users or devices are currently involved in. This classification of the information is similar to that followed by [START_REF] Ye | Using situation lattices in sensor analysis[END_REF], and allows us to accommodate learning-based techniques for the recognition of user activities like [START_REF] Tapia | Activity recognition in the home using simple and ubiquitous sensors[END_REF] within a specification-based approach.

A situation model comprises of three parts. First is the description of the situation itself, which identifies the features it contains. Features are externally observable properties that characterise some aspect of the situation. They could refer either to an individual entity or a collection of entities taking part in the situation. They describe what is recognised without any reference to how, providing a common interface to situation-aware applications and the other parts of the model.

Second, there are customisations, which place simple constraints on the features of the situation. The constraints are Boolean expressions that refer to either a single feature or a set of features. As they are specified with respect to the features of a situation, they can be applied to any situation with the necessary features allowing it to be easily tailored to address the particular needs of users. We can view the relationship between a situation and its customisations as a form of restriction inheritance [START_REF] Meyer | The many faces of inheritance: A taxonomy of taxonomy[END_REF].

Third, there are one or more specifications for the situation. These are complex documents describing the entities, properties, locations and constraints that are used to determine whether the situation is occurring. It is the specification that maps the context information, derived from low-level sensor data to the high-level features of the situation through a set of feature bindings. We adopt a specification-based approach as the transparency it provides facilitates these mappings. Taking inspiration from [START_REF] Coutaz | Context is key[END_REF] we introduce structure into specifications through the specification of a set of roles played by individual entities involved in the situation. An entity (user, device, or location) is involved in a situation if it plays one or more of its roles, when it is occurring. An expression describes a series of constraints and relationships that need to apply on the roles. Each role in turn includes a similar expression that places constraints on any entity playing it. A situation is considered to be occurring when all of the relations and constraints included in its specification hold. Following a similar approach to [START_REF] Ranganathan | Reasoning about uncertain contexts in pervasive computing environments[END_REF], both roles and situations have a specific type that is defined with respect to a domain-specific ontology, providing a common vocabulary across environments.

The model also incorporates three types of inheritance between model parts that enable certain abstract reasoning over recognised situations. The first is situation inheritance, a form of extension inheritance [START_REF] Meyer | The many faces of inheritance: A taxonomy of taxonomy[END_REF], that allows a situation to introduce additional features to the inherited ones in its description. The second is feature inheritance, a form of subtype inheritance [START_REF] Meyer | The many faces of inheritance: A taxonomy of taxonomy[END_REF], that allows the introduction of subclasses of particular inherited features. The third is customisation inheritance, a form of restriction inheritance [START_REF] Meyer | The many faces of inheritance: A taxonomy of taxonomy[END_REF], that allows a customisation to be further customised with the introduction of additional constraints. Figure 1 shows an example of two situation descriptions a 'Meeting' and a more specific 'Group Meeting' represented by dark blue rectangles. Each description includes a number of features, represented by light blue ovals. So, a meeting is characterised by the time and place it occurs and its attendees, while a group meeting in addition to these is also characterised by the group, and two types of attendees, group members and others. The solid arrow connecting the two situation descriptions indicates an instance of situation inheritance, while the dotted arrows indicate an instance of feature inheritance. Customisations are shown as yellow ovals. For example, the 'SmartLabGroup-Meeting' customisation constrains the group of a 'GroupMeeting' situation to the SmartLab group, with the dotted line connecting them indicating this relationship. More specific customisations can be created by placing additional constraints. For example, the 'SmartLab Reading Group Meeting' and 'Smart-Lab Group Progress Meeting' customisations constrain the 'Time' and 'Place' of the 'Group Meeting' in addition to its 'Group'. The dotted arrows indicate that these are instances of customisation inheritance.

Specifications are shown with green ovals and a solid line relates them to the situation they specify. A situation may be specified in a number of ways, each requiring different context information to recognise it. For example, a 'Group Meeting' can be recognised based on the time and the location of the attendees, 'Basic spec', or on calendar information and the location of the attendees, 'Calendar-based spec', or on the group membership of the attendees, 'Advanced spec'. Multiple specifications allow recognition to adapt to the currently available context information. Different specifications can be also created to suit different deployments. For example, light weight ones can be used when deployed on resource-constrained mobile devices and more sophisticated ones when dedicated infrastructure is available. In addition, different specifications can be fused to increase confidence in the results.

A middleware for pervasive situation-awareness

The middleware needs to be open, as it must incorporate a variety of users and heterogeneous devices, whose number and identity are not known in advance and will change over time. The data describing the properties of users and devices, and new and customised situation specifications, are inherently distributed. Recognition of situations is a responsive process that must continually monitor changes in the environment and report the situations occurring. Situation-aware applications are adaptive, tailoring their behaviour to the current situation. Both recognition of situations and adaptation of application behaviour must be performed autonomously. Agent-based architectures with agents responsive to changes in their environment, that proactively act, and collaborate with other agents, support the flexible autonomous action necessary to satisfy these requirements [START_REF] Jennings | Applications of intelligent agents[END_REF], a fact that has already been recognised by others [START_REF] Kumar | Pico: A middleware framework for pervasive computing[END_REF][START_REF] Ranganathan | Reasoning about uncertain contexts in pervasive computing environments[END_REF].

The situation determination agent (SDA) is the agent that actually recognises situations. It continually attempts to match situation specifications and report instances of situations when they occur. There could be a number of SDAs deployed in an environment. To collect the context information necessary for the SDA to perform its function, a number of context entity agents are used (CEAs). The idea is that a number of different SDAs may be interested in the same kind of context information, so by having collections of agents that are managed by the middleware perform the context processing tasks, we can optimise the use of available resources. There are two flavours of CEAs -data (DCEAs) that detect and report individual properties of entities, and compute (CCEAs) that perform calculations over the properties and detect patterns of their values over time. The exchange of context information between CEAs and SDAs as well as between DCEAs and CCEAs is done over a publish/subscribe substrate. The CEA manager (CEAM) selects the most appropriate set of CEAs to provide the required context information taking into consideration the quality of the produced context information and the available resources.

Specification repository agents (SRAs) store collections of specifications and customisations. SRAs can either be hosted in the environment or on users' personal devices in order to ensure that the particular needs of users are satisfied everywhere. Situation-aware application agents (SAA) provide the interface to the middleware for situation-aware applications. They manage the applications' situation recognition requests and report to them occurrences of the requested situations. They are typically hosted on the device that hosts the situationaware application. An SDA manager (SDAM) coordinates the interaction between SDAs and SRAs and selects the most appropriate SDA for each situation recognition request based on the resource requirements of the situation specification and the available resources at the device hosting the SDA.

In order to simplify the situation recognition process, each situation is considered to include an index. This is the entity from whose perspective the situation is viewed. Situation recognition requests are expressed with respect to a particular situation index. This turns situation discovery into an entity discovery process. To facilitate this process every entity in the system is represented by an index server agent (ISA) that keeps track of the SAAs that have requested situations involving this entity, and can additionally filter the information provided about an entity depending on the agent requesting it. An index locator agent (ILA) is responsible for the discovery of ISAs and is typically deployed alongside each SAA. Figure 2 illustrates the situation recognition process. The SAA presents a simple situation query interface to situation-aware applications with three operations. The first is getSituations that allows situationaware applications to discover which situations, customisations and specifications are supported in the local environment, particularly useful for runtime situation discovery. It can be parameterised to discover situations, customisations, specifications or any combination of these. The second is requestSituations that allows applications to request notifications for occurring situations. Its parameters include: the situation index, the target situation/customisation to be recognised, the required confidence by which the target situation must be recognised, the level of detail to be reported ranging from short (just the situation and its index), to features (the situations and all each features), to full (the situation, all its features, and all available details of the recognition process, including the specification used, the agents that were involved, etc), the lease period (i.e. the amount of time for which the query should remain active). The third is unregister that allows applications to deactivate a situation recognition request before its lease expires.

Middleware implementation

Situation descriptions, customisations and specifications are defined in a semantically rich manner with reference to relevant domain ontologies by using OWL documents 2 . OWL enables interoperability across different environments and is supported by a rich set of tools that can check the validity of documents, graphically edit and manipulate documents, and even reason about the relationships of concepts across different ontologies.

The agent-based architecture is implemented using the Java Agent DEvelopment Framework (JADE) 3 . It supports suitable abstractions for the development of agents and agent behaviours. It provides support for agent discovery, and communication over both wired and wireless networks. It is able to handle networking volatility through store and forward techniques, and supports multiple device platforms, from server-class machines to mobile phones.

The situation determination agent (SDA) implementation is based on the Jess Rule Engine realisation of the Rete network algorithm4 . The SDA is also responsible for transforming situation specifications into Jess code and determining the required entity properties. There are three main steps to the translation. The first is to identify all the properties that are referenced in the specification's expression and feature bindings. The set of properties determines which DCEAs and CCEAs are required to recognise the specification. The second step is to identify the roles that appear in the specification, and extract any cardinality constraints that are placed upon them as these require special processing. The third step is to generate Jess code for the specification. Each Jess rule comprises of an 'if' part that lists all of the patterns that must match for the rule to fire, and a 'then' part that lists all of the actions that are executed when the rule is fired. In this case the focus is on the 'if' part that concatenates (a) expressions that match against each of the roles present in the specification, (b) a list of the tuples and expansions required to access the necessary properties, and (c) the expressions of the specification. A very similar process is used for the transformation of role specifications. The full details of the process including an example transformation can be found in [START_REF] Thomson | A Model and Architecture for Pervasive Situation Determination[END_REF].

The middleware implementation also includes a number of optimisations to better utilise available resources. First, it distinguishes between generic situation and role specifications, and grounded ones, i.e. those that rely on entities properties whose value is produced by agents residing on the same device. For the latter it is wasteful to assign their recognition to a remote SDA, so an SDA is preferably deployed on the same device in order to reduce network communication. Second, SDAs classify specifications of interest as either active or inactive. The former are those for which all required entity attributes are currently available through corresponding CEAs, and can thus be identified. As entities appear and disappear from the environment so do their associated CEAs resulting in the activation and de-activation of the corresponding specifications.

Middleware evaluation

Our evaluation first focuses on showing that the middleware is expressive enough to easily support multiple specifications and a wide range of customisations for a set of situations, and thus is able to support the needs of individual users across potentially different environments. Then we focus on showing that the middleware performs well. In this respect, the quality of the recognition process is not really relevant as it depends on the specific situation specification used and the quality of the underlying sensing infrastructure, both of which are not determined by the middleware itself. Instead, we focus on its ability to support interactive situation-aware applications as the number of entities involved in the situation, and the number of situations to be recognised increases. The roudtrip time of a situation recognition request provides a summary of the overall performance of the system.

Expressive power

To demonstrate the expressive power of our middleware we focus on meeting, presentation and lecture situations in a university setting. The blue ovals represent situations, the yellow ovals customisations, the green ovals specifications, and the solid arrows indicate situation inheritance relationships. The capital letters in the specification ovals indicate the types of CEAs used to implement the specification (see [START_REF] Thomson | A Model and Architecture for Pervasive Situation Determination[END_REF] for more details).

Figure 3 shows a generic 'Meeting' situation extended by a 'Group meeting' that recognises meetings of particular research groups, a 'PhD meeting' that detects a meeting between a PhD student and his/her supervisors, and a 'Demonstrator meeting' that recognises a meeting held between the lecturers and demonstrators of a particular class. Each extended meeting situation has at least three alternative specifications. The first two are the ones we saw in figure 1. The third is tailored to the particular type of meeting, for example part of this specification for the group meeting required that more than 75% of the attendees are members of the same group, while for the PhD meeting, part of this specification detects PhD supervisor and student relations between the attendees.

Figure 4 shows a presentation situation with five different specifications, two specifications similar to those described above, one based on a fixed time, place and attendees' locations, and another based on attendees' locations and a calendar entry. There is also a coarse-grained specification that can only recognise presentation attendees, and two fine-grained specifications that could differentiate between speakers and audience members of a presentation, one based on fine-grained location information (i.e. based on the area of the room a person is located), and the other based on detecting whether a person is speaking or not. A lecture situation is also identified by five specifications similar to the presentation ones, with the different attendees now being the lecturer and the students of a class. Further customisation to the particular organisational setting is carried out through several customisations for each of the meeting, presentation and lecture situations. For example, customisations of the group meeting situation are created for each of the research and administrative groups within a particular university department, as well as customisations for each of the lectures, labs and tutorials for each course run by the department. This offers a large degree of flexibility in tailoring situations to the particular needs of the department's staff and students.

Performance

The performance measurements are based on a deployment of the middleware in a university environment. Three different classes of computers were used: (a) desktop PCs with a 3.4 GHz Intel Pentium 4 processor and 1 GB of RAM, running Debian GNU/Linux 3.1, (b) a Dell Inspiron 6000 laptop, with a 1.5 GHz Intel Pentium M processor and 1 GB of RAM, running Windows XP, and (c) a collection of HP Pocket PC h5500 handheld computers with a 400 MHz Intel XScale processor and 128 MB RAM, running Windows CE 4.2. The desktop PCs were connected to a 100 Mbps-BaseT Ethernet network, while the laptop and Pocket PCs were connected via a WEP-encrypted 802.11b wireless network.

The performance study focuses on the round trip time of a situation recognition request (RTT). It incorporates the time consumed by sending the situation recognition request out, the system gathering the necessary information required to recognise the situation, the cost of performing the recognition itself, and the delivery of the results back to the application. Each RTT measurement represents the mean value of 300 samples, which reflect a single situation recognition session where an application first joins the network, issues a situation recognition request, receives 10 situation reports, and reacts to the situation information. A total of 30 sessions were collected.

We first focus on the middleware performance for a set of situations as the number of entities involved in them increases from typical to larger sizes. The measurements were collected using a situation-aware application that could record the times that events such as sending situation recognition requests and receiving situation reports occur. One SDA was run on a desktop PC and another desktop PC hosted the other infrastructure agents. Pocket PCs were used to represent users, and hosted the CEAs that reported the user's location and personal profile information, as well as their ISA. The measurement application was also run on a Pocket PC.

The RTT measurements for each situation are shown in figure 5. The size values represent the number of users involved in the situation. For larger sizes a single Pocket PC represented more than one person. Overall, each of the situations shows an acceptable round trip time. Even at the largest situation size, all response times are under nineteen milliseconds. For each doubling in situation size, the round trip time increases by only 10% on average. This means the middleware is able to support interactive situation-aware applications. We now focus on the performance of the middleware as the number of situations simultaneously recognised increases from light to heavy loads. The change in RTT is measured for a particular situation, while the number of instances of other situations being recognised in the environment increases. The 'Presentation' situation is chosen as it showed the steepest RTT scaling in figure 5 above. This is due to the fact that it has the greatest number of distinct roles. For these measurements, a slightly different set up was used. For the cases where the number of users involved exceeded the available Pocket PCs, we simulated additional users on desktop PCs. However, no simulation is involved in the 'Presentation' situation itself as the number of participants is limited to eight. Otherwise, the set-up is the same as above.

The RTT measurements are shown in figure 6. At scale 1, there was a single instance of a number of group situations that included a 'Lunch', 'Meeting', 'Group Meeting', 'Demonstrator Meeting', 'Lecture', 'Lab' and 'Tutorial' situations. Each instance included eight people, matching the size of the 'Presentation' instance. Each scale number reflects a multiple of this set of situations. At each scale, the single, realistic instance of the 'Presentation' situation was measured.

Figure 6 shows that RTTs increase more steeply as the number of simultaneously recognised situations increases, than when the size of the situation increased. For each doubling in the number of situations simultaneously recognised, the RTT more than doubles on average. However the level of performance is still acceptable. At the heaviest load, while recognising forty situations simultaneously with a single SDA, the average RTT was just 387 milliseconds. These times can be reduced by sharing the recognition load across multiple SDAs. Note that load distribution is automatically managed by the middleware. To demonstrate this, the largest scale set up was redeployed, with the number of available SDAs increased, and the reduction in the RTTs was measured. Each SDA processes an equal share of the total number of situations. For 2 SDAs the mean RTT was 231.829 milliseconds, while for 4 SDAs the mean RTT was 144.112. These represent a decrease of the RTT by more than half, 61%, on average for each doubling of the available SDAs. So, employing multiple SDAs can help to maintain a low RTT in periods of heavy load.

Conclusions and future work

In this paper we presented a middleware for pervasive situation-awareness. The middleware is able to recognise the same situations across different environments by supporting multiple specifications, each targeting a particular sensing infrastructure. It is also able to accommodate the particular needs of individual users by supporting easy customisation of situations. As customisations are expressed in terms of the features of a situation, they can be applied across a variety of situation specifications and the resulting situations can be identified across different environments. We also showed through a number of situations that our middleware is expressive enough to easily support the definition of a wide range of situations, customisations and specifications. Moreover, we demonstrated that its performance scales reasonably to support practical deployment scenarios.

In the future we plan to extend our middleware along two dimensions. First, we plan to enhance our model by exploring more sophisticated forms of situation customisation beyond restriction inheritance. In this respect, we are looking into the specification of sophisticated interpreters to apply more expressive customisations. Second, we plan to enhance the performance of our middleware implementation by exploring cloud-based deployment scenarios. In this front, we can off-load large parts of the rule matching involved in the situation identification process in a cloud platform like the Google App Engine, however this would require careful consideration of the performance trade-offs involved.

Fig. 1 .

 1 Fig.1. The 'Meeting' and 'Group Meeting' situations, their specifications and customisations.

Fig. 2 .

 2 Fig. 2. An illustration of how the different types of agents cooperate to carry out the situation recognition process.

Fig. 3 .Fig. 4 .

 34 Fig. 3. University meeting situations.

Fig. 5 .

 5 Fig. 5. Mean RTT for a selection of situations as the size of the situations increases.

Fig. 6 .

 6 Fig.6. Mean RTT for the 'Presentation' situation as the number of simultaneously recognised situations increases.

http://cobra.umbc.edu/ontologies.html

http://www.w3.org/ TR/2004/REC-owl-features-20040210

http://jade.tilab.com

http://herzberg.ca.sandia.gov/jess


Ivan Voras
email: ivan.voras@fer.hr

Marin Orlić
email: marin.orlic@fer.hr

Mario Žagar
email: mario.zagar@fer.hr

Something old is new again: reimagining the oldest social networking platform

Keywords: social network, protocol, e-mail, SMTP, IMAP, Internet, Web

The phenomenon of social networking has entered the lives of mil lions of people via the ubiquitous Web-based platforms such as Facebook and Google+ which are centralized platforms completely controlled by single enti ties. However, a complete parallel message-passing infrastructure already exists and has the benefit of 30 years experience and investments: the SMTP e-mail network, which together with the latest technologies can be utilized to provide a completely decentralized, convenient, private and even fault-tolerant social net working platform. This work in progress aims to design and implement a proof of concept of such idea.

Introduction

Internet-facilitated social networking platforms are a natural extension of the human desire for communication and keeping in touch with people we care about (including to some extent people we want do business with). In the year 2012 it is already con sidered "normal" for people to participate in and communicate by using large webbased social network services and both "Facebook" and "Twitter" are well on their way of becoming generic words. However, the popular social Web sites today are not communicating and exchanging information in a way even approaching seamless. They are also highly centralized and often highly invasive in their data privacy poli tics, but due to their huge popularity, even knowledgeable users who would otherwise not participate are drawn into using them by peer pressure. Every introduction of a new social network services (like Google+) contends for the users with every other existing service, and the competition is fierce. This paper aims to suggest an idea for the implementation of a new social network platform on top of existing infrastructure, leveraging an existing large user base with minimal investments. The core idea is to adapt the service which already has a huge backing, in a way which is mostly seamless with its existing usage; this service is the venerable electronic mail (e-mail).

We discuss the capabilities of e-mail for content delivery in §2, the expected fea tures of such a social network service, with a proposal for such a service implemented over existing e-mail infrastructure (specifically, SMTP and IMAP) in §3.

1.1

The role of e-mail and social networks in modern communication

The electronic mail service is one of the oldest services on the Internet -present in its codified form as Simple Mail Transfer Protocol (SMTP) since 1982 [START_REF] Postel | RFC 821: Simple Mail Tranfer Protocol[END_REF]. Though it was originally created to support several transport schemes (TCP, NCP, NITS, X.25) and with addressing mechanisms which do not completely rely on the Domain Name Service (DNS) for e-mail routing, the dominant modern implementations of the SMTP have practically removed all older transport and addressing schemes and sup port only the TCP/IP variant with simple addressing which is well known to all Inter net users today.

The volume of e-mail messages exchanged over the Internet can only be esti mated, but it is in any case simply impressive. Estimations for year 2010 [START_REF] Pingdom | Internet 2010 in numbers[END_REF] set the total number of e-mail messages exchanged daily at 294 billion, of which a staggering 89% (approximately 262 billion) are "spam mail". The yearly total of messages ex changed is somewhere in the range of 90 trillion. Not only are these numbers impres sive in themselves but they convey how much e-mail has become a part of the Internet infrastructure on which people rely in their daily lives. They also indicate how robust this simple message passing service is (or must be) to allow such high volume of mes sages to be globally routed. We can contrast this to the recently prominent "social net work" services. The published statistics of Facebook [3][11] speak of around 845 mil lion monthly active users and 1 billion pieces of content (Web links, news stories, blog posts, notes, photo albums, etc.) shared daily, which is around 2% of daily world-wide non-spam e-mail traffic. Of course, while e-mail is strongly used for busi ness communication, Facebook is still used almost exclusively for private social inter action, and Facebook does not have to deal with so many spam messages.

E-mail as a Distributed Content Distribution Service

Like many of the early described Internet protocols, SMTP in a large part shares a no tion of equality between nodes connected to the network. Each node can receive all messages and route them to other nodes, but SMTP does not specify how the users of those hosts can access these messages. This need is addressed by separate protocols like POP3 [START_REF] Myers | RFC 1939: Post Office Protocol -Version 3[END_REF] and IMAP4 [START_REF] Crispin | RFC 3501: Internet Message Access Protocol -Version 4rev1[END_REF], and recently, HTTP via "webmail" services. SMTP servers without additional internal rules (e.g. access lists, firewalls) can accept e-mail messages from any user and route it to any other user on the Internet, users being identified by their e-mail addresses. Today's SMTP implementations basically utilizes the DNS as a routing table, looking up mail exchanger entries (the "MX records") or host name entries ("A records") to get to the IP addresses of destination hosts.

In the modern SMTP sessions, servers do not respond to message reception to the sender until the message is safely written to a permanent storage. This "store-and-for ward" scheme helps to achieve robustness. Two types of error messages are provided (for permanent and transient errors), which allow an implementation of a "wait-andretry" protocol for transient errors, which goes a long way toward ensuring that errors like server overload and storage space exhaustion don't affect message delivery if re solved reasonably quickly. However, the SMTP does not itself actually guarantee message delivery, just that there should be reasonable effort on the side of the SMTP server to do so. In this, it is similar to e.g. the IP. At best, in case of a permanent error during message delivery, the user indicated as the sender of the message in the mes sage headers will receive a notification about this error.

2.1

Comparison to modern peer-to-peer sharing networks

Most of the similarity between the SMTP-based e-mail message delivery service and peer-to-peer content sharing networks is in how they are formed as overlay networks over existing infrastructure and in the way messages are routed between distant nodes. The e-mail service uses the ever-changing, almost ad-hoc information from the DNS for message routing. The e-mail service is distributed and peer-to-peer because of the protocol-level equivalence of all the SMTP hosts on the Internet. Barring internal rules and firewalls, each SMTP host can route a message to any other. An important concept in overlays networks is the separation of addressing be tween the layer. In e-mail, the user addresses are from a completely separate address ing scheme from the one used to route TCP/IP network packets. In fact, e-mail ad dresses can reference users and hosts for which there is no 1:1 mapping to the TCP/IP network. One important consequence of this scheme is its independence in the case the transport technology changes (e.g. the switch from IPv4 to IPv6).

Modern e-mail messages contain rich content (images, multimedia, rich text for matting) by making use of the multi-part message format -"MIME" [START_REF] Freed | RFC 2045: Multipurpose Internet Mail Extensions[END_REF].

Merging e-mail and social networking services

There is a large volume of papers and best practices on the backend architectures that power large Web sites such as the social networking behemoths, which is very inter esting from an engineering point of view but the users are generally attracted to only two features: the ease of use and the size of the community [START_REF] Lampe | A face(book) in the crowd: social Searching vs. social browsing[END_REF]. Among the basic functions offered by social networking services, we will concentrate on these:

• Inviting friends / building a social network • Exchanging private messages (asynchronous / non-real-time messages)

• Exchanging personal information • Publishing messages (status texts) and content objects This basic set of functions seems to support the majority of the social interaction on Facebook and Google+, but many other forms of interaction can be implemented us ing this basic set. With the provision that "messages" in this case can be complex, carrying multimedia and other complex content, functions such as "events", "fan pages" and even social applications can be implemented using only message passing. We expect the following useful properties from the implementation of a social net working platform over e-mail:

• The easy, unambiguous mapping of persons (or at least their user accounts) to their network addresses by using e-mail addresses, which are well defined, ubiqui tous and in inexhaustible supply. • The ability for Internet Service Providers, other companies and all other entities on the Internet to easily augment their own infrastructure to support the new ser vice and offer it to their users on as-needed basis, while still being independent en tities with the ability to offer locally valuable additions to the service. In effect, the proposal will enable the creation of "mini-Facebooks" with well-defined interop erability, while simultaneously mostly solving the biggest obstacle: the huge infra structure needed for such endevours. • The robustness which comes from its decentralized nature and years of experience with e-mail infrastructure. • The increased privacy which comes from moving some of the social interaction features to the user agent, from not having any single Internet entity capable of processing or storing global messages and from a standard which allows users to migrate between different service providers. • The increased competition between service providers and between user agents in the quality of service, features and presentation, which arises from having a decen tralized system.

Within the framework for this new service, the role of the SMTP will be in the trans port of specially formatted (but completely valid and interoperable) e-mail messages between hosts on the Internet. The user agents (Mail User Agents -MUA), which may be implemented in any of the currently popular technologies (e.g. as desktop or as Web applications), would distinguish these messages from regular e-mail traffic, parse them and present them in with an augmented user interface which supports ad vanced features normally not available in e-mail. Practical implementations may or may not use the auxiliary protocols like POP3 and IMAP to retrieve the messages from users' mailboxes (i.e. just as they are currently implemented). We envision to build the additional features into e-mail messages by making use of the standard MIME specification for multipart messages, formatting added data as XML documents, which has the additional benefit of allowing for simplified presenta tions of the content so that user agents without the support for the new features can display a basic, simplified e-mail message.

We imagine that the popular practical implementation of this new service will pro vide user interfaces similar to those found today in popular social networking Web sites and will completely hide the underlying e-mail based nature of the service. That said, the intention behind this idea is not to replace the current e-mail service and clients with something new, but to expect that the regular and "social" e-mail mes sages will coexist but be slightly separately treated by the user agents. One possible implementation of this coexistence we can propose may be in the form of separate user agents observing the same mailbox, with the augmented agent recognizing and, after fetching and parsing the message, hiding it or moving the message from the mailbox. An extension of this idea may be to do this on the server side, with user agents using an advanced protocol like IMAP to monitor [START_REF] Leiba | RFC 2177: IMAP4 IDLE command[END_REF] separate folders within the mailbox (this ability is already present in most e-mail servers deployed today in the form of message filters or even spam filters).

An important difference between social networking services and e-mail services is in their privacy assumptions. As opposed to the "free-for-all" nature of the e-mail, so cial networking services deliberately limit the interaction to that between persons which are inside the network (i.e. "added as friends"). We address this issue by in cluding simple, well-known and standardized public key cryptography technologies as an unavoidable part of the service. Currently, the best candidate for this type of technology is PGP (described in RFC 2440 [START_REF] Callas | RFC 4880: OpenPGP Message Format[END_REF][9]).

3.1

The basic features of social networking services implemented with message passing

We start by requiring each person using the service to have at least one cryptographic public-private key pair per e-mail address usable for the service. This key pair will in many cases be used to support the privacy and confidentiality within the social net work. All content-carrying messages are required to contain at least one valid digital signature. In this scheme, the user's public key is a stronger identifier of the person's identity than the person's e-mail address. Joining two users in the commutative "friend" relation can basically be reduced to the two users exchanging their public keys. This is effectively the only point where it is possible for users to receive unso licited e-mail messages (i.e. spam, junk mail), and an effective set of rules can be used to filter out unwanted message (e.g. by setting the limit on the number of characters in the message, requiring only plain-text introductory messages, etc.). Once a "friend re quest" is accepted, all further communication between the users will be either signed or signed and encrypted using public key cryptography technologies. Messages re ceived by user agents without valid signatures must be discarded. Private message exchange is conceptually the simplest case for both the sender and the client. Properly formatted messages are digitally signed by the sender and en crypted so only the receiver can read them.

Personal information is voluntarily entered by users of social networking services and all of it (except for basic information such as the e-mail address and the user's "name") is optional. Exchange of such information can be implemented by broadcast ing a message to their "friends," which can be implemented incrementally to increase communication efficiency. Such arrangement also allows tight control of personal in formation sent to specific users.

The most widely used feature of social networking sites (at least as observed by these authors) is the message publishing feature by which users exchange messages and content within their social network (either the entire network or a subset of it -"circles" or "groups", depending on specific privacy settings). By taking advantage of the MIME message format to contain multiple embedded objects, the messages can contain arbitrary objects in arbitrary numbers, referenced and optionally described in the main message (e.g. a snapshot of a photo album with all the album's photo's thumbnails). Large multimedia objects (e.g. YouTube videos) can be linked to.

We suggest that the user agents' user interfaces follow similar design for function alities and have overall look and feel similar to current implementations of social net work Web sites. In case the user agent is implemented as a Web application, it can also implement "apps" in a way analogous to today's popular products. Other features such as real-time instant messaging can be implemented with protocols such as Jabber (XMPP) [START_REF] St Andre | RFC 6120: Extensible Messaging and Presence Protocol (XMPP): Core[END_REF].

Future work

As this paper proposes only an idea of a service for which this authors believe it will be useful to a global audience, future works must design and describe specific details usable for its implementation. An effort is under way to create such a specification in parallel with an experimental implementation. There are many fields left unaddressed in this paper, among which are the possibilities offer state management services to other applications, and the opportunity for data mining. These will get addressed in our future work.

The authors wish to encourage communication and discussion which would help develop this idea and solve its edge cases. We invite input from all interested parties.