Index: source/ariba/AribaModule.cpp
===================================================================
--- source/ariba/AribaModule.cpp	(revision 11885)
+++ 	(revision )
@@ -1,291 +1,0 @@
-// [License]
-// The Ariba-Underlay Copyright
-//
-// Copyright (c) 2008-2009, Institute of Telematics, UniversitÃ€t Karlsruhe (TH)
-//
-// Institute of Telematics
-// UniversitÃ€t Karlsruhe (TH)
-// Zirkel 2, 76128 Karlsruhe
-// Germany
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// 1. Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
-// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ARIBA PROJECT OR
-// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// The views and conclusions contained in the software and documentation
-// are those of the authors and should not be interpreted as representing
-// official policies, either expressed or implied, of the Institute of
-// Telematics.
-// [License]
-
-#include "AribaModule.h"
-
-// boost/std includes
-#include <assert.h>
-#include <boost/regex.hpp>
-#include <boost/foreach.hpp>
-#include <boost/algorithm/string.hpp>
-
-// ariba includes
-#include "ariba/SideportListener.h"
-#include "ariba/utility/misc/Helper.h"
-#include "ariba/utility/misc/StringFormat.h"
-#include "ariba/communication/BaseCommunication.h"
-#include "ariba/communication/EndpointDescriptor.h"
-
-using namespace ariba::utility::Helper;
-using ariba::communication::BaseCommunication;
-using ariba::communication::EndpointDescriptor;
-
-namespace ariba {
-
-use_logging_cpp(AribaModule);
-const string AribaModule::BootstrapMechanismNames[5]
-         = {"invalid", "static", "broadcast", "mdns", "sdp"};
-
-AribaModule::AribaModule()
-	: started(false), base_comm(NULL), sideport_sniffer(NULL) {
-	endpoints = "tcp{41322};rfcomm{10};";
-}
-
-AribaModule::~AribaModule() {
-}
-
-string AribaModule::getBootstrapHints(const Name& spoVNetName) const {
-	std::ostringstream o;
-	int i=0;
-	BOOST_FOREACH( const BootstrapInfo& info, bootstrapNodes ) {
-		o << info.spovnetName.toString() << "{";
-		if (i!=0) o << ",";
-
-		BOOST_FOREACH( const BootstrapNode& node, info.nodes ) {
-			if( node.desc != NULL )
-				o << node.desc->toString();
-			else if(node.mechanism == BootstrapMechanismBroadcast
-					|| node.mechanism == BootstrapMechanismMulticastDNS
-					|| node.mechanism == BootstrapMechanismSDP){
-				o << BootstrapMechanismNames[node.mechanism];
-				if( !node.info.empty() ) o << "{" << node.info << "}";
-				o << ";";
-			}
-		}
-		o << "}";
-		i++;
-	}
-	return o.str();
-}
-
-void AribaModule::addBootstrapHints(string boot_info) {
-	using namespace boost::xpressive;
-	using namespace ariba::utility::string_format;
-	using namespace ariba::utility::Helper;
-	using namespace std;
-
-	boost::erase_all(boot_info, " ");
-	boost::erase_all(boot_info, "\t");
-	boost::erase_all(boot_info, "\n");
-	boost::erase_all(boot_info, "\r");
-
-	smatch match;
-	if (regex_search(boot_info, match, robjects)) {
-		regex_nav nav = match;
-		for (int i = 0; i < nav.size(); i++) {
-			string type = nav[i][robject_id].str();
-			string data = nav[i][robject_data].str();
-			data = data.substr(1, data.size() - 2);
-			Name name(type);
-
-			// find static bootstrap info --> BootstrapMechanismStatic
-			EndpointDescriptor* desc = EndpointDescriptor::fromString(data);
-			addBootstrapNode(name, desc, "", BootstrapMechanismStatic);
-
-			// find automatic bootstrap info --> {BootstrapMechanismBroadcast,
-			// 					BootstrapMechanismMulticastDNS,BootstrapMechanismSDP}
-			typedef vector< string > split_vector_type;
-			split_vector_type splitvec;
-			boost::split( splitvec, data, boost::is_any_of(";") );
-			for(unsigned int i=0; i<splitvec.size(); i++){
-				string x = splitvec[i];
-				split_vector_type innervec;
-
-				boost::split( innervec, x, boost::is_any_of("{}") );
-				BootstrapNode node;
-				if(innervec.size() < 1) continue;
-
-				if(innervec[0] == BootstrapMechanismNames[BootstrapMechanismBroadcast])
-					node.mechanism = BootstrapMechanismBroadcast;
-				else if(innervec[0] == BootstrapMechanismNames[BootstrapMechanismMulticastDNS])
-					node.mechanism = BootstrapMechanismMulticastDNS;
-				else if(innervec[0] == BootstrapMechanismNames[BootstrapMechanismSDP])
-					node.mechanism = BootstrapMechanismSDP;
-				else
-					continue;
-
-				if(innervec.size() > 1)
-					node.info = innervec[1];
-
-				this->addBootstrapNode(name, node);
-			}
-		}
-	}
-
-	logging_info( "Added bootstrap hints: " << getBootstrapHints() );
-}
-
-void AribaModule::addBootstrapNode(const Name& spovnet,
-		communication::EndpointDescriptor* desc, const string& info,
-		const BootstrapMechanism& mechanism) {
-	BootstrapNode node(0, desc, mechanism, info);
-	addBootstrapNode(spovnet, node);
-}
-
-void AribaModule::addBootstrapNode(const Name& spovnet, const BootstrapNode& node){
-	bool added = false;
-
-	// add node to existing bootstrap list
-	BOOST_FOREACH( BootstrapInfo& info, bootstrapNodes ){
-		if (info.spovnetName == spovnet) {
-			info.nodes.push_back(node);
-			added = true;
-			break;
-		}
-	}
-
-	// create new entry
-	if (!added) {
-		BootstrapInfo info;
-		info.spovnetName = spovnet;
-		info.nodes.push_back(node);
-		bootstrapNodes.push_back(info);
-	}
-}
-
-const communication::EndpointDescriptor* AribaModule::getBootstrapNode(
-		const Name& spovnet, const BootstrapMechanism mechanism) const {
-	BOOST_FOREACH( const BootstrapInfo& info, bootstrapNodes ) {
-		if( info.spovnetName == spovnet ) {
-			BOOST_FOREACH( const BootstrapNode& node, info.nodes ) {
-				if( node.mechanism == mechanism && node.desc != NULL )
-					return node.desc;
-			}
-		}
-	}
-	return NULL;
-}
-
-string AribaModule::getBootstrapInfo(
-		const Name& spovnet, const BootstrapMechanism mechanism) const {
-	BOOST_FOREACH( const BootstrapInfo& info, bootstrapNodes ) {
-		if( info.spovnetName == spovnet ) {
-			BOOST_FOREACH( const BootstrapNode& node, info.nodes ) {
-				if( node.mechanism == mechanism && node.desc != NULL )
-					return node.info;
-			}
-		}
-	}
-
-	return string();
-}
-
-vector<AribaModule::BootstrapMechanism> AribaModule::getBootstrapMechanisms(
-		const Name& spovnet) const {
-	vector<AribaModule::BootstrapMechanism> ret;
-	BOOST_FOREACH( const BootstrapInfo& info, bootstrapNodes ) {
-		if( info.spovnetName == spovnet ) {
-			BOOST_FOREACH( const BootstrapNode& node, info.nodes ) {
-				if(std::find(ret.begin(), ret.end(), node.mechanism) == ret.end())
-					ret.push_back(node.mechanism);
-			}
-		}
-	}
-	return ret;
-}
-
-void AribaModule::registerSideportListener(SideportListener* sideport){
-	sideport_sniffer = sideport;
-}
-
-// @see Module.h
-void AribaModule::initialize() {
-
-	// preconditions
-	assert(!started);
-
-	// init variables
-	base_comm = NULL;
-}
-
-// @see Module.h
-void AribaModule::start() {
-
-	// preconditions
-	assert(base_comm == NULL);
-	assert(!started);
-
-	// create the base communication component
-	started = true;
-	base_comm = new BaseCommunication();
-	base_comm->setEndpoints(endpoints);
-}
-
-// @see Module.h
-void AribaModule::stop() {
-
-	// preconditions
-	assert(base_comm != NULL);
-	assert(started);
-
-	// delete base communication component
-	started = false;
-	delete base_comm;
-}
-
-// @see Module.h
-string AribaModule::getName() const {
-	return "ariba";
-}
-
-// @see Module.h
-void AribaModule::setProperty(string key, string value) {
-	if (key == "endpoints") endpoints = value;
-	else if (key == "bootstrap.hints") addBootstrapHints(value);
-}
-
-// @see Module.h
-const string AribaModule::getProperty(string key) const {
-	if (key == "endpoints") return endpoints; // TODO: return local endpoints
-	else if (key == "bootstrap.hints") return getBootstrapHints();
-	return "";
-}
-
-// @see Module.h
-const vector<string> AribaModule::getProperties() const {
-	vector<string> properties;
-	properties.push_back("endpoints");
-	properties.push_back("bootstrap.hints");
-	return properties;
-}
-
-const string AribaModule::getLocalEndpoints() {
-	return base_comm->getEndpointDescriptor().toString();
-}
-
-} // namespace ariba
Index: source/ariba/AribaModule.h
===================================================================
--- source/ariba/AribaModule.h	(revision 11885)
+++ 	(revision )
@@ -1,277 +1,0 @@
-// [License]
-// The Ariba-Underlay Copyright
-//
-// Copyright (c) 2008-2009, Institute of Telematics, UniversitÃ€t Karlsruhe (TH)
-//
-// Institute of Telematics
-// UniversitÃ€t Karlsruhe (TH)
-// Zirkel 2, 76128 Karlsruhe
-// Germany
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// 1. Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
-// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ARIBA PROJECT OR
-// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// The views and conclusions contained in the software and documentation
-// are those of the authors and should not be interpreted as representing
-// official policies, either expressed or implied, of the Institute of
-// Telematics.
-// [License]
-
-#ifndef ARIBAMODULE_H_
-#define ARIBAMODULE_H_
-
-#include <string>
-#include <vector>
-#include <ctime>
-#include <cstdlib>
-#include <algorithm>
-
-using std::vector;
-using std::string;
-
-// forward declaration
-namespace ariba {
-	class AribaModule;
-	class SideportListener;
-}
-
-// local includes
-#include "Name.h"
-#include "Module.h"
-
-namespace ariba {
-
-// forward declaration
-namespace communication {
-	class EndpointDescriptor;
-	class BaseCommunication;
-}
-
-/** \addtogroup public
- * @{
- * This class implements a container class for ariba base services. Each node
- * is a running using this base-module. It also manages Bootstrap information
- * in a abstract simple way.
- *
- *        +---+   +---+
- *        |N1 |   |N2 |
- *     +--|   |---|   |--+
- *     |  +---+   +---+  |
- *     |                 |
- *     |     AribaModule |
- *     +-----------------+
- *
- * N1, N2 are nodes.
- *
- * @author Sebastian Mies <mies@tm.uka.de>
- * @author Christoph Mayer <mayer@tm.uka.de>
- */
-class AribaModule: public Module {
-	friend class Node;
-	use_logging_h(AribaModule);
-public:
-	/**
-	 * Constructor of the ariba underlay module
-	 */
-	AribaModule();
-
-	/**
-	 * Destructor of the ariba underlay module
-	 */
-	virtual ~AribaModule();
-
-	/**
-	 * Returns all known bootstrap endpoints to this ariba module in
-	 * a human-readable string. This information can be used by other
-	 * nodes for bootstraping. It may also be used to publish this info
-	 * to other nodes via the web, for example.
-	 *
-	 * @param The name of the spovnet
-	 * @return A human-readable string containing all known bootstrap
-	 *   information known to this module.
-	 */
-	string getBootstrapHints(const Name& spoVNetName = Name::UNSPECIFIED) const;
-
-	/**
-	 * Adds bootstrap hints to the local database. The format of the string
-	 * must is the same as returned by <code>getBootstrapInfo</code>.
-	 *
-	 * @param bootinfo A string containing bootstrap information.
-	 */
-	void addBootstrapHints(string bootinfo);
-
-	/**
-	 * Register a sideport for sniffing on communication events
-	 * and get advanced information. The sniffer is attached to
-	 * every node that is created on the module. Only one such
-	 * sniffer can be active system-wide, a new call to this
-	 * register function will only attach the sniffer to nodes
-	 * created after the registration call.
-	 *
-	 * @param sideport The SideportListener to integrate
-	 */
-	void registerSideportListener(SideportListener* sideport);
-
-	// --- module implementation ---
-
-	/**
-	 * Module Property information:
-	 *
-	 * ip.addr  = preferred ip address (otherwise bind to all)
-	 * tcp.port = preferred tcp port (or use default value)
-	 * udp.port = preferred udp port (or use default value)
-	 * bootstrap.hints = used bootstrap hints
-	 * bootstrap.file  = used file for bootstrap information
-	 */
-	void initialize();                          ///< @see Module.h
-	void start();                               ///< @see Module.h
-	void stop();                                ///< @see Module.h
-	string getName() const;                     ///< @see Module.h
-	void setProperty(string key, string value); ///< @see Module.h
-	const string getProperty(string key) const; ///< @see Module.h
-	const vector<string> getProperties() const; ///< @see Module.h
-
-	/**
-	 * Get the local endpoint information
-	 */
-	const string getLocalEndpoints();
-
-private:
-
-	/**
-	 * Available bootstrap mechanisms
-	 */
-	enum BootstrapMechanism {
-		BootstrapMechanismInvalid = 0,
-		BootstrapMechanismStatic = 1,
-		BootstrapMechanismBroadcast = 2,
-		BootstrapMechanismMulticastDNS = 3,
-		BootstrapMechanismSDP = 4,
-	};
-	static const string BootstrapMechanismNames[5];
-
-	/**
-	 * bootstrap node information
-	 */
-	class BootstrapNode {
-	public:
-		inline BootstrapNode() :
-			timestamp(0), desc(NULL), mechanism(BootstrapMechanismInvalid), info("") {
-
-		}
-		inline BootstrapNode(const BootstrapNode& copy) :
-			timestamp(copy.timestamp), desc(copy.desc), mechanism(copy.mechanism), info(copy.info) {
-		}
-		inline BootstrapNode(
-				uint32_t timestamp,
-				communication::EndpointDescriptor* desc,
-				BootstrapMechanism mechanism, string info) :
-			timestamp(timestamp), desc(desc), mechanism(mechanism), info(info) {
-		}
-		uint32_t timestamp;
-		communication::EndpointDescriptor* desc;
-		BootstrapMechanism mechanism;
-		string info;
-	};
-
-	/*
-	 * bootstrap info, all bootstrap nodes
-	 * for a specific spovnet
-	 */
-	class BootstrapInfo {
-	public:
-		BootstrapInfo() :
-			spovnetName(), nodes() {
-		}
-
-		BootstrapInfo(const BootstrapInfo& copy) :
-			spovnetName(copy.spovnetName), nodes(copy.nodes) {
-		}
-
-		Name spovnetName;
-		vector<BootstrapNode> nodes;
-	};
-
-	vector<BootstrapInfo> bootstrapNodes; //< all available bootstrap information
-
-protected:
-	// members
-	string endpoints; //< local endpoints the ariba module is bound to
-	bool started; //< flag, if module has been started
-
-	/**
-	 * bootstrap node management
-	 * add a bootstrap node
-	 */
-	void addBootstrapNode(
-			const Name& spovnet,
-			communication::EndpointDescriptor* desc,
-			const string& info,
-			const BootstrapMechanism& mechanism
-			);
-
-	/**
-	 * bootstrap node management
-	 * add a bootstrap node
-	 */
-	void addBootstrapNode(
-			const Name& spovnet,
-			const BootstrapNode& node
-			);
-
-	/**
-	 * bootstrap node management
-	 * get all available bootstrap mechanisms
-	 * where bootstrap nodes are available for
-	 */
-	vector<AribaModule::BootstrapMechanism> getBootstrapMechanisms(
-			const Name& spovnet
-			) const;
-
-	/**
-	 * get a endpoint descriptor for a spovnet
-	 * using a specific bootstrap mechanisms.
-	 * will currently only work with static
-	 */
-	const communication::EndpointDescriptor* getBootstrapNode(
-			const Name& spovnet,
-			const BootstrapMechanism mechanism
-			) const;
-
-	/**
-	 * get the info field associated for a given
-	 * spovnet through a given mechanism
-	 */
-	string getBootstrapInfo(
-			const Name& spovnet,
-			const BootstrapMechanism mechanism
-			) const;
-
-	communication::BaseCommunication* base_comm; //< the base communication
-	SideportListener* sideport_sniffer; //< the sideport listener
-};
-
-} // namespace ariba
-
-/** @} */
-
-#endif /* ENVIRONMENT_H_ */
Index: source/ariba/CMakeLists.txt
===================================================================
--- source/ariba/CMakeLists.txt	(revision 11885)
+++ source/ariba/CMakeLists.txt	(revision 12060)
@@ -46,5 +46,5 @@
 ### Increment this whenever the interface changes! ###
 ######################################################
-set(ariba_SOVERSION 1)
+set(ariba_SOVERSION 2)
 ######################################################
 
@@ -184,5 +184,5 @@
 add_headers(
     ariba.h
-    AribaModule.h
+#    AribaModule.h
     CommunicationListener.h
     DataMessage.h
@@ -199,5 +199,5 @@
 
 add_sources(
-    AribaModule.cpp
+#    AribaModule.cpp
     CommunicationListener.cpp
     DataMessage.cpp
Index: source/ariba/CommunicationListener.cpp
===================================================================
--- source/ariba/CommunicationListener.cpp	(revision 11885)
+++ source/ariba/CommunicationListener.cpp	(revision 12060)
@@ -59,4 +59,5 @@
 
 void CommunicationListener::onLinkFail(const LinkID& l, const NodeID& r) {
+    onLinkDown(l, r);
 }
 
@@ -69,6 +70,41 @@
 }
 
+// this implementation provides backward compatibility
+// overwrite it to use the new interface
+void CommunicationListener::onMessage(reboost::shared_buffer_t message,
+        const NodeID& remote,
+        const LinkID& lnk,
+        const SequenceNumber& seqnum,
+        const ariba::overlay::OverlayMsg* overlay_msg)
+{
+    // copy data
+    Data data;
+    data.setLength(message.size() * 8);
+    memcpy(data.getBuffer(), message.data(), message.size());
+    
+    // and prepare old-style overlay message
+    Message legacy_msg;
+    legacy_msg.setPayload(data);
+    
+    
+    // * call legacy handler *
+    this->onMessage(legacy_msg, remote, lnk);
+}
+
 void CommunicationListener::onKeyValue( const Data& key, const vector<Data>& value ) {
 }
 
+bool CommunicationListener::onPing(const NodeID& remote)
+{
+    return true;
+}
+
+void CommunicationListener::onPingLost(const NodeID& remote)
+{
+}
+
+void CommunicationListener::onPong(const NodeID& remote)
+{
+}
+
 } // namespace ariba
Index: source/ariba/CommunicationListener.h
===================================================================
--- source/ariba/CommunicationListener.h	(revision 11885)
+++ source/ariba/CommunicationListener.h	(revision 12060)
@@ -44,10 +44,14 @@
 #include "LinkProperties.h"
 #include "DataMessage.h"
+#include "ariba/overlay/SequenceNumber.h"
 
 namespace ariba {
+
+typedef ariba::overlay::SequenceNumber SequenceNumber;
 
 // forward decl
 namespace overlay {
 	class BaseOverlay;
+	class OverlayMsg;
 }
 
@@ -116,4 +120,6 @@
 
 	/**
+	 * @DEPRECATED
+	 * 
 	 * Called when a message is incoming
 	 * @param msg The data message that is received
@@ -123,4 +129,21 @@
 	virtual void onMessage(const DataMessage& msg, const NodeID& remote,
 			const LinkID& lnk = LinkID::UNSPECIFIED);
+
+
+    /**
+     * NOTE: This interface is still unstable and may change in future releases.
+     *   ---> Especially the parameter Â«overlay_msgÂ» may be replaced or removed.
+     *   
+     * Called when a message is incoming
+     * @param msg A shared buffer with the (serialized) payload
+     * @param remote The remote node that sent the message
+     * @param lnk The link id of the link where the message is received
+     * @param overlay_msg A pointer to the ariba internal Overlay Message
+     */
+    virtual void onMessage(reboost::shared_buffer_t message,
+            const NodeID& remote,
+            const LinkID& lnk,
+            const SequenceNumber& seqnum,
+            const ariba::overlay::OverlayMsg* overlay_msg);
 
 	// --- dht functionality ---
@@ -133,4 +156,28 @@
 	virtual void onKeyValue( const Data& key, const vector<Data>& value );
 
+    // --- ping pong (routed) ---
+    /**
+     * Called when a ping message was received.
+     * 
+     * @param remote Node which sent the ping message
+     * @return bool Allows to send a pong message (default: true)
+     */
+    virtual bool onPing(const NodeID& remote);
+
+    /**
+     * Called when a ping message is lost.
+     * 
+     * NOTE: A ping message could also get lost without notice.
+     * 
+     * @param remote Node to which the ping message was sent
+     */
+    virtual void onPingLost(const NodeID& remote);
+    
+    /**
+     * Called when a pong message was received.
+     * 
+     * @param remote Node which sent the pong message
+     */
+    virtual void onPong(const NodeID& remote);
 };
 
Index: source/ariba/DataMessage.h
===================================================================
--- source/ariba/DataMessage.h	(revision 11885)
+++ source/ariba/DataMessage.h	(revision 12060)
@@ -9,5 +9,6 @@
 // use message utility
 #ifdef USE_MESSAGE_UTILITY
-  #include "ariba/utility/messages.h"
+//  #include "ariba/utility/messages.h"
+  #include "ariba/utility/messages/Message.h"
   namespace ariba {
     typedef utility::Message Message;
Index: source/ariba/Message.h
===================================================================
--- source/ariba/Message.h	(revision 11885)
+++ source/ariba/Message.h	(revision 12060)
@@ -41,5 +41,9 @@
 
 #include <inttypes.h>
-#include "ariba/utility/messages.h"
+
+// legacy messages
+#include "ariba/utility/messages/Message.h"
+// reboost messages
+#include "ariba/utility/transport/messages/message.hpp"
 
 /** \addtogroup public
Index: source/ariba/Node.cpp
===================================================================
--- source/ariba/Node.cpp	(revision 11885)
+++ source/ariba/Node.cpp	(revision 12060)
@@ -39,15 +39,32 @@
 #include "Node.h"
 
+#include <boost/foreach.hpp>
+
 #include "ariba/overlay/BaseOverlay.h"
+#include "ariba/communication/BaseCommunication.h"
+
 #include "ariba/utility/types/OverlayParameterSet.h"
 #include "ariba/communication/EndpointDescriptor.h"
 
+#include <boost/property_tree/exceptions.hpp>
+
+using namespace std;
 using ariba::communication::EndpointDescriptor;
+using boost::property_tree::ptree;
 
 namespace ariba {
 
-Node::Node(AribaModule& ariba_mod, const Name& node_name) :
-	name(node_name), ariba_mod(ariba_mod) {
-	base_overlay = new BaseOverlay();
+//Node::Node(AribaModule& ariba_mod, const Name& node_name) :
+//	name(node_name), ariba_mod(ariba_mod) {
+//	base_overlay = new BaseOverlay();
+//}
+
+Node::Node()  :
+        name(Name::UNSPECIFIED),
+        base_communication(NULL),
+        base_overlay(NULL)
+{
+    base_communication = new BaseCommunication();
+    base_overlay = new BaseOverlay();
 }
 
@@ -55,88 +72,204 @@
 	delete base_overlay;
 	base_overlay = NULL;
-}
-
-void Node::join(const Name& vnetname) {
-	spovnetId = vnetname.toSpoVNetId();
-	nodeId = generateNodeId(name);
-
-	// start base comm if not started
-	if( !ariba_mod.base_comm->isStarted() )
-		ariba_mod.base_comm->start();
-
-	// start base overlay if not started
-	// join against ourselfs
-	if( !base_overlay->isStarted() )
-		base_overlay->start( *ariba_mod.base_comm, nodeId );
-	base_overlay->joinSpoVNet( spovnetId );
-
-	// join against static bootstrap points and
-	// start automatic bootstrapping modules
-	vector<AribaModule::BootstrapMechanism> mechanisms
-		= ariba_mod.getBootstrapMechanisms(vnetname);
-
-	vector<pair<BootstrapManager::BootstrapType,string> > internalmodules;
-
-	BOOST_FOREACH(AribaModule::BootstrapMechanism m, mechanisms){
-		switch(m){
-			case AribaModule::BootstrapMechanismStatic:
-			{
-				const communication::EndpointDescriptor* ep =
-							ariba_mod.getBootstrapNode(vnetname, m);
-					if( ep != NULL && ep->isUnspecified() == false )
-						base_overlay->joinSpoVNet( spovnetId, *ep);
-				break;
-			}
-			case AribaModule::BootstrapMechanismBroadcast:
-				internalmodules.push_back(make_pair(
-						BootstrapManager::BootstrapTypePeriodicBroadcast,
-						ariba_mod.getBootstrapInfo(vnetname, m)));
-				break;
-			case AribaModule::BootstrapMechanismMulticastDNS:
-				internalmodules.push_back(make_pair(
-						BootstrapManager::BootstrapTypeMulticastDns,
-						ariba_mod.getBootstrapInfo(vnetname, m)));
-				break;
-			case AribaModule::BootstrapMechanismSDP:
-				internalmodules.push_back(make_pair(
-						BootstrapManager::BootstrapTypeBluetoothSdp,
-						ariba_mod.getBootstrapInfo(vnetname, m)));
-				break;
-			default:
-				break;
-		}
-	}
-
-	// start automatic overlay bootstrapping modules
-	base_overlay->startBootstrapModules(internalmodules);
-
-	// done
-}
-
-void Node::initiate(const Name& vnetname, const SpoVNetProperties& parm) {
-	utility::OverlayParameterSet ovrpset;
-	ovrpset.setOverlayStructure(
-			(utility::OverlayParameterSet::_OverlayStructure)
-			parm.getBaseOverlayType()
-			);
-
-	spovnetId = vnetname.toSpoVNetId();
-	nodeId = generateNodeId(name);
-
-	// start base comm if not started
-	if( !ariba_mod.base_comm->isStarted() )
-		ariba_mod.base_comm->start();
-
-	// start base overlay if not started
-	if( !base_overlay->isStarted() )
-		base_overlay->start( *ariba_mod.base_comm, nodeId );
-
-	base_overlay->createSpoVNet( spovnetId, ovrpset );
-}
+	
+	delete base_communication;
+	base_communication = NULL;
+}
+
+void Node::connect(const ptree& config)
+{
+    using namespace boost::property_tree;
+    using namespace addressing2;
+    
+    assert( ! base_communication->isStarted() );
+    assert( ! base_overlay->isStarted() );
+
+    // XXX needed since Â»empty_ptree<ptree>()Â« is not working
+    //   ---> see: http://stackoverflow.com/questions/5003549/where-is-boost-property-treeempty-ptree
+    static const ptree empty_pt;
+    
+    // SpovNet ID
+    Name spovnet_name(config.get<string>("spovnet_name"));
+    spovnetId = spovnet_name.toSpoVNetId();
+    
+    // Node ID
+    try
+    {
+        name = config.get<string>("node_name");
+    }
+    catch ( ptree_bad_path& e )
+    {
+        name = Name::UNSPECIFIED;
+    }
+    nodeId = generateNodeId(name);
+
+    
+    
+    /* Base Communication */
+    EndpointSetPtr listen_on;
+    try
+    {
+        listen_on = endpoint_set::create_EndpointSet(
+            config.get_child("listen_on"));
+    }
+    catch ( ptree_bad_path& e )
+    {
+        /* no endpoints specified, using default: Â»[::]:41322+Â« */
+        
+        ptree default_listen_on;
+        default_listen_on.put("endp.category", "TCPIP");
+        default_listen_on.put("endp.addr", "::");
+        default_listen_on.put("endp.port", 0);  // defaults to 41322 (or higher)
+        
+        listen_on = endpoint_set::create_EndpointSet(default_listen_on);
+//        logging_warn("No endpoints specified in config. ---> Using default.");
+        cout << "No endpoints specified in config. ---> Using default." << endl;
+    }
+    base_communication->start(listen_on);
+    
+    // TODO maybe notify the upper layer whether we have any active endpoints
+    
+
+    /* Base Overlay */
+    base_overlay->start( base_communication, nodeId );
+
+    base_overlay->createSpoVNet( spovnetId );
+    base_overlay->joinSpoVNet( spovnetId );
+    
+    
+    
+    /* Bootstrap */
+    const ptree& bootstrap_pt = config.get_child("bootstrap", empty_pt);
+    
+    // Static Bootstrap
+    try
+    {
+        // read endpoint_set from config
+        EndpointSetPtr ep_set = endpoint_set::create_EndpointSet(
+                bootstrap_pt.get_child("direct"));
+        
+        EndpointDescriptor ep = EndpointDescriptor::UNSPECIFIED();
+        ep.replace_endpoint_set(ep_set);
+        
+        // try to connect
+        base_overlay->joinSpoVNet( spovnetId, ep);
+    }
+    catch ( ptree_bad_path& e )
+    {
+//        logging_info("No direct bootstrap info in config.");
+        cout << "No direct bootstrap info in config." << endl;
+    }
+
+    
+    /* Bootstrap modules */
+    vector<pair<BootstrapManager::BootstrapType,string> > internalmodules;
+    
+    // Bootstrap: Broadcast
+    if ( bootstrap_pt.get("broadcast", false) )
+    {
+        internalmodules.push_back(make_pair(
+                BootstrapManager::BootstrapTypePeriodicBroadcast,""));
+    }
+    
+    // Bootstrap: MDNS
+    if ( bootstrap_pt.get("mdns", false) )
+    {
+        internalmodules.push_back(make_pair(
+                BootstrapManager::BootstrapTypeMulticastDns,""));
+    }
+
+    // Bootstrap: SDP
+    if ( bootstrap_pt.get("sdp", false) )
+    {
+        internalmodules.push_back(make_pair(
+                BootstrapManager::BootstrapTypeBluetoothSdp,""));
+    }
+
+    // start automatic overlay bootstrapping modules
+    base_overlay->startBootstrapModules(internalmodules);
+}
+
+//void Node::join(const Name& vnetname) {
+//	spovnetId = vnetname.toSpoVNetId();
+//	nodeId = generateNodeId(name);
+//
+//	// start base comm if not started
+//	if( !ariba_mod.base_comm->isStarted() )
+//		ariba_mod.base_comm->start();
+//
+//	// start base overlay if not started
+//	// join against ourselfs
+//	if( !base_overlay->isStarted() )
+//		base_overlay->start( *ariba_mod.base_comm, nodeId );
+//	base_overlay->joinSpoVNet( spovnetId );
+//
+//	// join against static bootstrap points and
+//	// start automatic bootstrapping modules
+//	vector<AribaModule::BootstrapMechanism> mechanisms
+//		= ariba_mod.getBootstrapMechanisms(vnetname);
+//
+//	vector<pair<BootstrapManager::BootstrapType,string> > internalmodules;
+//
+//	BOOST_FOREACH(AribaModule::BootstrapMechanism m, mechanisms){
+//		switch(m){
+//			case AribaModule::BootstrapMechanismStatic:
+//			{
+//				const communication::EndpointDescriptor* ep =
+//							ariba_mod.getBootstrapNode(vnetname, m);
+//					if( ep != NULL && ep->isUnspecified() == false )
+//						base_overlay->joinSpoVNet( spovnetId, *ep);
+//				break;
+//			}
+//			case AribaModule::BootstrapMechanismBroadcast:
+//				internalmodules.push_back(make_pair(
+//						BootstrapManager::BootstrapTypePeriodicBroadcast,
+//						ariba_mod.getBootstrapInfo(vnetname, m)));
+//				break;
+//			case AribaModule::BootstrapMechanismMulticastDNS:
+//				internalmodules.push_back(make_pair(
+//						BootstrapManager::BootstrapTypeMulticastDns,
+//						ariba_mod.getBootstrapInfo(vnetname, m)));
+//				break;
+//			case AribaModule::BootstrapMechanismSDP:
+//				internalmodules.push_back(make_pair(
+//						BootstrapManager::BootstrapTypeBluetoothSdp,
+//						ariba_mod.getBootstrapInfo(vnetname, m)));
+//				break;
+//			default:
+//				break;
+//		}
+//	}
+//
+//	// start automatic overlay bootstrapping modules
+//	base_overlay->startBootstrapModules(internalmodules);
+//
+//	// done
+//}
+//
+//void Node::initiate(const Name& vnetname, const SpoVNetProperties& parm) {
+//	utility::OverlayParameterSet ovrpset;
+//	ovrpset.setOverlayStructure(
+//			(utility::OverlayParameterSet::_OverlayStructure)
+//			parm.getBaseOverlayType()
+//			);
+//
+//	spovnetId = vnetname.toSpoVNetId();
+//	nodeId = generateNodeId(name);
+//
+//	// start base comm if not started
+//	if( !ariba_mod.base_comm->isStarted() )
+//		ariba_mod.base_comm->start();
+//
+//	// start base overlay if not started
+//	if( !base_overlay->isStarted() )
+//		base_overlay->start( *ariba_mod.base_comm, nodeId );
+//
+//	base_overlay->createSpoVNet( spovnetId, ovrpset );
+//}
 
 void Node::leave() {
 	base_overlay->stopBootstrapModules();
 	base_overlay->leaveSpoVNet();
-	ariba_mod.base_comm->stop();
+	base_communication->stop();  // XXX before Â»base_overlay->stop()Â« ??
 	base_overlay->stop();
 }
@@ -172,23 +305,128 @@
 }
 
+bool Node::isLinkDirect(const ariba::LinkID& lnk) const
+{
+    return base_overlay->isLinkDirect(lnk);
+}
+
+int Node::getHopCount(const ariba::LinkID& lnk) const
+{
+    return base_overlay->getHopCount(lnk);
+}
+
+
+
+
+/* +++++ Message sending +++++ */
+void Node::check_send_priority(uint8_t priority)
+{
+    if ( priority < send_priority::HIGHEST || priority > send_priority::LOWEST )
+        throw std::invalid_argument("Illegal priority");     
+}
+
+
+// +++ new interface +++
+const SequenceNumber& Node::sendMessage(reboost::message_t msg, const LinkID& lnk, uint8_t priority)
+{
+    // check priority
+    check_send_priority(priority);
+        
+    // * call base overlay *
+    return base_overlay->sendMessage(msg, lnk, priority);
+}
+
+// +++ legacy interface +++
+seqnum_t Node::sendMessage(const DataMessage& msg, const LinkID& lnk)
+{
+    reboost::message_t message = ((Message*) msg)->wrap_up_for_sending();
+    
+    try
+    {
+        base_overlay->sendMessage(message, lnk, send_priority::NORMAL);
+        return 0;
+    }
+    catch ( ariba::overlay::message_not_sent& e )
+    {
+        logging_warn("Message could not be sent. Dropped.");
+        return -1;
+    }
+}
+
+
+// +++ new interface +++
+const SequenceNumber& Node::sendMessage(reboost::message_t msg, const NodeID& nid,
+        const ServiceID& sid, uint8_t priority, const LinkProperties& req) {
+
+    // check priority
+    check_send_priority(priority);
+        
+    // * call base overlay *
+    return base_overlay->sendMessage(msg, nid, priority, sid);
+}
+
+// +++ legacy interface +++
 seqnum_t Node::sendMessage(const DataMessage& msg, const NodeID& nid,
 		const ServiceID& sid, const LinkProperties& req) {
-	return base_overlay->sendMessage((Message*) msg, nid, sid);
-}
-
+    
+//    reboost::message_t message = ((Message*) msg)->wrap_up_for_sending();
+    reboost::message_t message;
+    message.push_back( ((Message*) msg)->serialize_into_shared_buffer() );
+    
+    try
+    {
+        sendMessage(message, nid, sid, send_priority::NORMAL, req);
+        return 0;
+    }
+    catch ( ariba::overlay::message_not_sent& e )
+    {
+        logging_warn("Message could not be sent. Dropped.");
+        return -1;
+    }
+}
+
+
+// +++ new interface +++
+NodeID Node::sendMessageCloserToNodeID(reboost::message_t msg, const NodeID& nid, const ServiceID& sid,
+        uint8_t priority, const LinkProperties& req) {
+
+    // check priority
+    check_send_priority(priority);
+        
+    // * call base overlay *
+    return base_overlay->sendMessageCloserToNodeID(msg, nid, priority, sid);
+}
+
+// +++ legacy interface +++
 NodeID Node::sendMessageCloserToNodeID(const DataMessage& msg, const NodeID& nid, const ServiceID& sid,
         const LinkProperties& req) {
     
-    return base_overlay->sendMessageCloserToNodeID((Message*) msg, nid, sid);
-}
-
-
-seqnum_t Node::sendMessage(const DataMessage& msg, const LinkID& lnk) {
-	return base_overlay->sendMessage((Message*) msg, lnk);
-}
-
+    reboost::message_t message = ((Message*) msg)->wrap_up_for_sending();
+    
+    return sendMessageCloserToNodeID(message, nid, sid, send_priority::NORMAL, req);
+}
+
+
+// +++ new interface +++
+void Node::sendBroadcastMessage(reboost::message_t msg, const ServiceID& sid, uint8_t priority) {
+
+    // check priority
+    check_send_priority(priority);
+        
+    // * call base overlay *
+    return base_overlay->broadcastMessage(msg, sid, priority);
+}
+
+// +++ legacy interface +++
 void Node::sendBroadcastMessage(const DataMessage& msg, const ServiceID& sid) {
-	return base_overlay->broadcastMessage((Message*)msg, sid);
-}
+    reboost::message_t message = ((Message*) msg)->wrap_up_for_sending();
+
+	return sendBroadcastMessage(message, sid);
+}
+
+
+/* +++++ [Message sending] +++++ */
+
+
+
 
 bool Node::bind(NodeListener* listener) {
@@ -204,8 +442,8 @@
 	bool ret = base_overlay->bind(listener, sid);
 
-	// now that we have a listener, we can ask if sniffing is ok
-	if( ariba_mod.sideport_sniffer != NULL ){
-		base_overlay->registerSidePort(ariba_mod.sideport_sniffer);
-	}
+//	// now that we have a listener, we can ask if sniffing is ok
+//	if( ariba_mod.sideport_sniffer != NULL ){
+//		base_overlay->registerSidePort(ariba_mod.sideport_sniffer);
+//	}
 
 	return ret;
Index: source/ariba/Node.h
===================================================================
--- source/ariba/Node.h	(revision 11885)
+++ source/ariba/Node.h	(revision 12060)
@@ -43,12 +43,16 @@
 namespace ariba {
 	class Node;
-	namespace overlay {
-		class BaseOverlay;
-	}
+    namespace communication {
+        class BaseCommunication;
+    }
+    namespace overlay {
+        class BaseOverlay;
+    }
 }
 
 #include <vector>
 #include <iostream>
-#include <boost/foreach.hpp>
+#include <exception>
+
 #include "Module.h"
 #include "Identifiers.h"
@@ -56,8 +60,14 @@
 #include "NodeListener.h"
 #include "Name.h"
-#include "AribaModule.h"
+//#include "AribaModule.h"
 #include "CommunicationListener.h"
 #include "DataMessage.h"
 #include "SideportListener.h"
+#include "ariba/overlay/SequenceNumber.h"
+
+// reboost messages
+#include "ariba/utility/transport/messages/message.hpp"
+
+#include <boost/property_tree/ptree.hpp>
 
 using std::vector;
@@ -65,4 +75,23 @@
 
 namespace ariba {
+
+// typedef ariba::overlay::SequenceNumber SequenceNumber; // XXX see CommunicationListener
+
+using boost::property_tree::ptree;
+
+// sendMessage-Priorities
+struct send_priority
+{
+    enum SEND_PRIORITY
+    {
+        HIGHEST = 2,
+        HIGHER = 3,
+        NORMAL = 4,
+        LOWER = 5,
+        LOWEST = 6
+    };
+};
+
+
 
 /**
@@ -75,6 +104,8 @@
  * @author Christoph Mayer <mayer@tm.uka.de>
  */
+// TODO do we really want to inherit from Module.. ?
 class Node: public Module {
 public:
+    
 	/**
 	 * Constructs a new node using a given ariba module
@@ -86,5 +117,8 @@
 	 *   is a zero-terminated char-string.
 	 */
-	Node(AribaModule& ariba_mod, const Name& node_name = Name::UNSPECIFIED);
+//	Node(AribaModule& ariba_mod, const Name& node_name = Name::UNSPECIFIED);
+	
+	// XXX EXPERIMENTAL
+	Node();
 
 	/**
@@ -100,4 +134,12 @@
 	//--- node control ---
 
+    /**
+     * XXX EXPERIMENTAL
+     * 
+     * Replaces initialte & join
+     */
+    void connect(const ptree& config);
+
+    // XXX DEPRECATED
 	/**
 	 * This method instructs the node to join a particular spovnet.
@@ -107,5 +149,5 @@
 	 * @param vnetId The SpoVNet name
 	 */
-	void join(const Name& name);
+//	void join(const Name& name);
 
 	/**
@@ -116,6 +158,6 @@
 	 * @param param The SpoVNet properties
 	 */
-	void initiate(const Name& name, const SpoVNetProperties& parm =
-			SpoVNetProperties::DEFAULT);
+//	void initiate(const Name& name, const SpoVNetProperties& parm =
+//			SpoVNetProperties::DEFAULT);
 
 	/**
@@ -221,51 +263,108 @@
 	void dropLink(const LinkID& lnk);
 
-	// message sending
-
-	/**
-	 * Sends a one-shot message to a service. If link properties are specified,
-	 * the node tries to fulfill those requirements. This may cause the node
-	 * to first establish a temporary link, second sending the message and last
-	 * dropping the link. This would result in a small amount of extra latency
-	 * until the message is delivered. If reliable transport was selected,
-	 * the method returns a sequence number and a communication event is
-	 * triggered on message delivery or loss.
-	 *
-	 * @param msg The message to be sent
-	 * @param nid The remote node identifier
-	 * @param sid The remote service identifier
-	 * @param req The requirements associated with the message
-	 * @return A sequence number
-	 */
+	/**
+	 * Returns whether a link is direct or relayed over other nodes
+	 * @param lnk LinkID of the link
+	 * @return true if link is direct; false otherwise
+	 */
+	bool isLinkDirect(const ariba::LinkID& lnk) const;
+	
+	/**
+	 * Returns the latest measured hop count on this link.
+	 * NOTE: This is not guaranteed to be up to date.
+	 * 
+	 * @param lnk LinkID of the link
+	 * @return overlay hop count on this link 
+	 */
+	int getHopCount(const ariba::LinkID& lnk) const;
+	
+	
+	/* +++++ Message sending +++++ */
+
+	
+    /**
+     * Sends a message via an established link. If reliable transport was
+     * selected, the method returns a sequence number and a communication event
+     * is triggered on message delivery or loss.
+     * 
+     * +++ New interface, using efficient zero-copy reboost messages. +++
+     *
+     * @param msg The message to be sent
+     * @param lnk The link to be used for sending the message
+     */
+    const SequenceNumber& sendMessage(reboost::message_t msg, const LinkID& lnk, uint8_t priority=send_priority::NORMAL);
+
+    /**
+     * +++ Legacy interface, converts old ariba messages into new reboost messages. +++
+     */    
+    seqnum_t sendMessage(const DataMessage& msg, const LinkID& lnk);
+
+    
+    /**
+     * Sends a one-shot message to a service. If link properties are specified,
+     * the node tries to fulfill those requirements. This may cause the node
+     * to first establish a temporary link, second sending the message and last
+     * dropping the link. This would result in a small amount of extra latency
+     * until the message is delivered. If reliable transport was selected,
+     * the method returns a sequence number and a communication event is
+     * triggered on message delivery or loss.
+     * 
+     * +++ New interface, using efficient zero-copy reboost messages. +++
+     *
+     * @param msg The message to be sent
+     * @param nid The remote node identifier
+     * @param sid The remote service identifier
+     * @param req The requirements associated with the message
+     * @return A sequence number
+     */
+    const SequenceNumber& sendMessage(reboost::message_t msg, const NodeID& nid, const ServiceID& sid,
+            uint8_t priority=send_priority::NORMAL, const LinkProperties& req = LinkProperties::DEFAULT);
+
+    /**
+     * +++ Legacy interface, converts old ariba messages into new reboost messages. +++
+     */
 	seqnum_t sendMessage(const DataMessage& msg, const NodeID& nid, const ServiceID& sid,
 			const LinkProperties& req = LinkProperties::DEFAULT);
 
-	/**
-	 * like the above function, but sends the message to the closest directly known node
-	 * to the specified address
-	 */
+    
+    /**
+     * like the above function, but sends the message to the closest directly known node
+     * to the specified address
+     * 
+     * +++ New interface, using efficient zero-copy reboost messages. +++
+     * 
+     */
+    NodeID sendMessageCloserToNodeID(reboost::message_t msg, const NodeID& nid, const ServiceID& sid,
+            uint8_t priority=send_priority::NORMAL, const LinkProperties& req = LinkProperties::DEFAULT);
+
+    /**
+     * +++ Legacy interface, converts old ariba messages into new reboost messages. +++
+     */
     NodeID sendMessageCloserToNodeID(const DataMessage& msg, const NodeID& nid, const ServiceID& sid,
             const LinkProperties& req = LinkProperties::DEFAULT);
 
-	/**
-	 * Sends a message via an established link. If reliable transport was
-	 * selected, the method returns a sequence number and a communication event
-	 * is triggered on message delivery or loss.
-	 *
-	 * @param msg The message to be sent
-	 * @param lnk The link to be used for sending the message
-	 */
-	seqnum_t sendMessage(const DataMessage& msg, const LinkID& lnk);
-
-	/**
-	 * Sends a message to all known hosts in the overlay structure
-	 * the nodes that are reached here depend on the overlay structure.
-	 *
-	 * @param msg The message to be send
-	 * @param sid The id of the service that should receive the message
-	 * @see getNeighborNodes
-	 */
+	
+    /**
+     * Sends a message to all known hosts in the overlay structure
+     * the nodes that are reached here depend on the overlay structure.
+     *
+     * +++ New interface, using efficient zero-copy reboost messages. +++
+     *
+     * @param msg The message to be send
+     * @param sid The id of the service that should receive the message
+     * @see getNeighborNodes
+     */
+	void sendBroadcastMessage(reboost::message_t msg, const ServiceID& sid, uint8_t priority=send_priority::NORMAL);
+
+    /**
+     * +++ Legacy interface, converts old ariba messages into new reboost messages. +++
+     */
 	void sendBroadcastMessage(const DataMessage& msg, const ServiceID& sid);
 
+	
+	/* +++++ [Message sending] +++++ */
+	
+	
+	
 	// --- communication listeners ---
 
@@ -313,5 +412,10 @@
 	/** @see Module.h */
 	string getName() const;
-
+	
+	
+private:
+	inline void check_send_priority(uint8_t priority);
+
+	
 protected:
 	// friends
@@ -320,7 +424,8 @@
 	// member variables
 	Name name;                             //< node name
-	AribaModule& ariba_mod;	               //< ariba module
+//	AribaModule* ariba_mod;	               //< ariba module
 	SpoVNetID spovnetId; 	               //< current spovnet id
 	NodeID nodeId; 		              	   //< current node id
+	communication::BaseCommunication* base_communication;
 	overlay::BaseOverlay* base_overlay;    //< the base overlay
 
Index: source/ariba/SideportListener.cpp
===================================================================
--- source/ariba/SideportListener.cpp	(revision 11885)
+++ source/ariba/SideportListener.cpp	(revision 12060)
@@ -41,5 +41,5 @@
 #include "ariba/overlay/BaseOverlay.h"
 #include "ariba/overlay/LinkDescriptor.h"
-#include "ariba/utility/addressing/endpoint_set.hpp"
+#include "ariba/utility/addressing2/tcpip_endpoint.hpp"
 
 using ariba::overlay::LinkDescriptor;
@@ -130,6 +130,4 @@
 	if( overlay == NULL ) return (Protocol)ret;
 
-	using namespace ariba::addressing;
-
 	LinkDescriptor* link = NULL;
 	BOOST_FOREACH( LinkDescriptor* lnk, overlay->links ){
@@ -147,16 +145,19 @@
 	if(bclink.isUnspecified() || bclink.remoteLocator == NULL) return (Protocol)ret;
 
-	const address_v* locator = bclink.remoteLocator;
+	addressing2::EndpointPtr locator = bclink.remoteLocator;
 
-	if( locator->instanceof<tcpip_endpoint>() ){
-		tcpip_endpoint tcpip = *locator;
-
-		if( tcpip.address().is_v4() || tcpip.address().is_v4_mapped() ){
+	if( locator->get_category() == addressing2::endpoint_category::TCPIP )
+	{
+        boost::shared_ptr<addressing2::tcpip_endpoint> endp =
+                boost::dynamic_pointer_cast<addressing2::tcpip_endpoint>(locator);
+	    
+		if( endp->to_asio().address().is_v4() )
+		{
 			ret = SideportListener::ipv4;
-		}else if( tcpip.address().is_v6() ){
+		}else {
 			ret = SideportListener::ipv6;
 		}
 
-	}else if( locator->instanceof<rfcomm_endpoint>() ){
+	}else if( locator->get_category() == addressing2::endpoint_category::BLUETOOTH ){
 		ret = SideportListener::rfcomm;
 	}
Index: source/ariba/ariba.h
===================================================================
--- source/ariba/ariba.h	(revision 11885)
+++ source/ariba/ariba.h	(revision 12060)
@@ -44,5 +44,4 @@
  */
 
-#include "AribaModule.h"
 #include "CommunicationListener.h"
 #include "DataMessage.h"
Index: source/ariba/communication/BaseCommunication.cpp
===================================================================
--- source/ariba/communication/BaseCommunication.cpp	(revision 11885)
+++ source/ariba/communication/BaseCommunication.cpp	(revision 12060)
@@ -57,41 +57,10 @@
 namespace communication {
 
+using namespace ariba::addressing2;
+
 using ariba::utility::PeerID;
 using ariba::utility::SystemQueue;
 
 use_logging_cpp(BaseCommunication);
-
-/// adds an endpoint to the list
-void BaseCommunication::add_endpoint( const address_v* endpoint ) {
-	if (endpoint==NULL) return;
-	BOOST_FOREACH( endpoint_reference& ref, remote_endpoints ) {
-		if (ref.endpoint->type_id() == endpoint->type_id() && *ref.endpoint == *endpoint) {
-			ref.count++;
-			return;
-		}
-	}
-	endpoint_reference ref;
-	ref.endpoint = endpoint->clone();
-	ref.count = 1;
-	remote_endpoints.push_back(ref);
-}
-
-/// removes an endpoint from the list
-void BaseCommunication::remove_endpoint( const address_v* endpoint ) {
-	if (endpoint==NULL) return;
-	for (vector<endpoint_reference>::iterator i = remote_endpoints.begin();
-		i != remote_endpoints.end(); i++) {
-		if ((*i->endpoint).type_id() == endpoint->type_id() && (*i->endpoint) == *endpoint) {
-			i->count--;
-			if (i->count==0) {
-				logging_info("No more links to " << i->endpoint->to_string() << ": terminating transports!");
-				transport->terminate(i->endpoint);
-				delete i->endpoint;
-				remote_endpoints.erase(i);
-			}
-			return;
-		}
-	}
-}
 
 
@@ -100,5 +69,6 @@
 	  transport( NULL ),
 	  messageReceiver( NULL ),
-	  started( false )
+	  started( false ),
+	  listenOn_endpoints(new addressing2::endpoint_set())
 {
 }
@@ -109,40 +79,47 @@
 
 
-void BaseCommunication::start() {
+void BaseCommunication::start(EndpointSetPtr listen_on) {
+    assert ( ! started );
+    
+    listenOn_endpoints = listen_on;
+    logging_info("Setting local end-points: " << listenOn_endpoints->to_string());
+    
 	logging_info( "Starting up ..." );
 	currentSeqnum = 0;
 
-	// set local peer id
-	localDescriptor.getPeerId() = PeerID::random();
-	logging_info( "Using PeerID: " << localDescriptor.getPeerId() );
-
 	// creating transports
+	//  ---> transport_peer holds the set of the active endpoints we're listening on
 	logging_info( "Creating transports ..." );
-
-#ifdef UNDERLAY_OMNET
-	AribaOmnetModule* module = StartupWrapper::getCurrentModule();
-	module->setServerPort( listenport );
-
-	transport = module;
-	network = new OmnetNetworkProtocol( module );
-#else
-	transport = new transport_peer( localDescriptor.getEndpoints() );
-#endif
+	transport = new transport_peer();
+	active_listenOn_endpoints = transport->add_listenOn_endpoints(listenOn_endpoints);
+	logging_info( "XXX. Active endpoints = " << active_listenOn_endpoints->to_string() ); // XXX
 
 	logging_info( "Searching for local locators ..." );
-	/**
-	 * DONT DO THAT: if(localDescriptor.getEndpoints().to_string().length() == 0)
-	 * since addresses are used to initialize transport addresses
-	 */
-	AddressDiscovery::discover_endpoints( localDescriptor.getEndpoints() );
-	logging_info( "Done. Local endpoints = " << localDescriptor.toString() );
-
+	local_endpoints = AddressDiscovery::discover_endpoints(active_listenOn_endpoints);
+	if ( local_endpoints->count() > 0 )
+	{
+	    logging_info( "Done. Discovered local endpoints: " << local_endpoints->to_string() );
+	}
+	else
+	{
+	    logging_warn("WARING!! No local endpoints found, NO COMMUNICATION POSSIBLE!!");
+	    
+	    // TODO notify application, so that it may react properly. throw exception..?
+	    assert( false );
+	}
+
+	
+    // create local EndpointDescriptor
+	//  ---> localDescriptor hold the set endpoints that can be used to reach us
+    localDescriptor.getPeerId() = PeerID::random();
+    localDescriptor.replace_endpoint_set(local_endpoints);
+    logging_info( "Using PeerID: " << localDescriptor.getPeerId() );
+
+    // start transport_peer
 	transport->register_listener( this );
 	transport->start();
 
-#ifndef UNDERLAY_OMNET
 	// bind to the network change detection
 	networkMonitor.registerNotification( this );
-#endif
 
 	// base comm startup done
@@ -163,11 +140,4 @@
 bool BaseCommunication::isStarted(){
 	return started;
-}
-
-/// Sets the endpoints
-void BaseCommunication::setEndpoints( string& _endpoints ) {
-	localDescriptor.getEndpoints().assign(_endpoints);
-	logging_info("Setting local end-points: "
-		<< localDescriptor.getEndpoints().to_string());
 }
 
@@ -193,12 +163,31 @@
 	addLink( ld );
 
-	// send a message to request new link to remote
-	logging_debug( "Send messages with request to open link to " << descriptor.toString() );
-	AribaBaseMsg baseMsg( AribaBaseMsg::typeLinkRequest, linkid );
-	baseMsg.getLocalDescriptor() = localDescriptor;
-	baseMsg.getRemoteDescriptor().getPeerId() = descriptor.getPeerId();
-
-	// serialize and send message
-	send( &baseMsg, descriptor );
+
+    /* send a message to request new link to remote */
+    logging_debug( "Send messages with request to open link to " << descriptor.toString() );
+
+    /*
+	 * Create Link-Request Message:
+	 * NOTE: - Their PeerID (in parent message)
+	 * - Our LinkID
+	 * - Our PeerID
+	 * - Our EndpointDescriptor
+	 */
+	reboost::message_t linkmsg;
+	linkmsg.push_back(linkid.serialize());
+	linkmsg.push_back(localDescriptor.getPeerId().serialize());
+	linkmsg.push_back(localDescriptor.endpoints->serialize());
+	
+//	// XXX AKTUELL BUG FINDING...
+//	reboost::shared_buffer_t xxx = localDescriptor.endpoints->serialize();
+//	EndpointSetPtr xxx_set = endpoint_set::create_EndpointSet();
+//	xxx_set->deserialize(xxx);
+//	cout << "/// MARIO VORHER: " << localDescriptor.endpoints->to_string() << endl;
+//	cout << "/// MARIO NACHHER: " << xxx_set->to_string() << endl;
+	
+	// send message
+	// TODO move enum to BaseComm
+	send_to_peer(AribaBaseMsg::typeLinkRequest, descriptor.getPeerId(), linkmsg,
+	        descriptor, system_priority::OVERLAY);
 
 	return linkid;
@@ -217,14 +206,13 @@
 
 	// tell the registered listeners
-	BOOST_FOREACH( CommunicationEvents* i, eventListener ) {
+	foreach( CommunicationEvents* i, eventListener ) {
 		i->onLinkDown( link, ld.localLocator, ld.remoteLocator );
 	}
 
-	// create message to drop the link
+
+	// * send message to drop the link *
 	logging_debug( "Sending out link close request. for us, the link is closed now" );
-	AribaBaseMsg msg( AribaBaseMsg::typeLinkClose, ld.localLink, ld.remoteLink );
-
-	// send message to drop the link
-	send( &msg, ld );
+	reboost::message_t empty_message;
+	send_over_link( AribaBaseMsg::typeLinkClose, empty_message, ld, system_priority::OVERLAY );
 
 	// remove from map
@@ -232,31 +220,48 @@
 }
 
-seqnum_t BaseCommunication::sendMessage( const LinkID lid, const Message* message) {
-
-	logging_debug( "Sending out message to link " << lid.toString() );
-
+
+seqnum_t BaseCommunication::sendMessage( const LinkID& lid,
+        reboost::message_t message,
+        uint8_t priority,
+        bool bypass_overlay) throw(communication_message_not_sent)
+{
+    // message type: direct data or (normal) data 
+    AribaBaseMsg::type_ type;
+    if ( bypass_overlay )
+    {
+        type = AribaBaseMsg::typeDirectData;
+        logging_debug( "Sending out direct-message to link " << lid.toString() );
+    }
+    else
+    {
+        type = AribaBaseMsg::typeData;
+        logging_debug( "Sending out message to link " << lid.toString() );
+    }
+
+    
 	// query local link info
 	LinkDescriptor& ld = queryLocalLink(lid);
-	if( ld.isUnspecified() ){
-		logging_error( "Don't know the link with id " << lid.toString() );
-		return -1;
+	if( ld.isUnspecified() )
+	{
+	    throw communication_message_not_sent("Don't know the link with id "
+	            + lid.toString());
 	}
 
 	// link not up-> error
-	if( !ld.up ) {
-		logging_error("Can not send on link " << lid.toString() << ": link not up");
-		return -1;
-	}
-
-	// create message
-	AribaBaseMsg msg( AribaBaseMsg::typeData, ld.localLink, ld.remoteLink );
-
-	// encapsulate the payload message
-	msg.encapsulate( const_cast<Message*>(message) );
-
-	// send message
-	send( &msg, ld );
-
-	// return sequence number
+	if( !ld.up )
+	{
+	    throw communication_message_not_sent("Can not send on link "
+	            + lid.toString() + ": link not up");
+	}
+
+
+	// * send message *
+	bool okay = send_over_link( type, message, ld, priority );
+
+	if ( ! okay )
+	{
+	    throw communication_message_not_sent("send_over_link failed!");
+	}
+	
 	return ++currentSeqnum;
 }
@@ -268,5 +273,5 @@
 		LinkDescriptor& linkDesc = queryLocalLink(link);
 		if (linkDesc.isUnspecified()) return EndpointDescriptor::UNSPECIFIED();
-		return linkDesc.remoteEndpoint;
+		return linkDesc.remoteDescriptor;
 	}
 }
@@ -283,29 +288,17 @@
 }
 
-SystemEventType TransportEvent("Transport");
-SystemEventType MessageDispatchEvent("MessageDispatchEvent", TransportEvent );
-
-/// called when a system event is emitted by system queue
-void BaseCommunication::handleSystemEvent(const SystemEvent& event) {
-
-	// dispatch received messages
-	if ( event.getType() == MessageDispatchEvent ){
-		logging_debug( "Forwarding message receiver" );
-		boost::function0<void>* handler = event.getData< boost::function0<void> >();
-		(*handler)();
-		delete handler;
-	}
-}
-
-/**
- * called within the ASIO thread
- * when a message is received from underlay transport
- */ 
+
+
+/*------------------------------
+ | ASIO thread --> SystemQueue |
+ ------------------------------*/
+
+/// ASIO thread
 void BaseCommunication::receive_message(transport_connection::sptr connection,
-	reboost::message_t msg) {
+	reboost::shared_buffer_t msg) {
 
 	logging_debug( "Dispatching message" );
 	
-    boost::function0<void>* handler = new boost::function0<void>(
+    SystemQueue::instance().scheduleCall(
             boost::bind(
                     &BaseCommunication::receiveMessage,
@@ -313,71 +306,173 @@
                     connection,
                     msg)
-    );
-    
-    SystemQueue::instance().scheduleEvent(
-        SystemEvent(this, MessageDispatchEvent, handler)
-    );
-}
-
-/**
- * called within the ARIBA thread (System Queue)
- * when a message is received from underlay transport
- */ 
+        );
+}
+
+/// ASIO thread
+void BaseCommunication::connection_terminated(transport_connection::sptr connection)
+{
+    SystemQueue::instance().scheduleCall(
+            boost::bind(
+                    &BaseCommunication::connectionTerminated,
+                    this,
+                    connection)
+        );
+}
+
+/*--------------------------------
+ | [ASIO thread --> SystemQueue] |
+ -------------------------------*/
+
+/// ARIBA thread (System Queue)
+void BaseCommunication::connectionTerminated(transport_connection::sptr connection)
+{
+    vector<LinkID*> links = connection->get_communication_links();
+    
+    logging_debug("[BaseCommunication] Connection terminated: "
+            << connection->getLocalEndpoint()->to_string()
+            << " <--> " << connection->getRemoteEndpoint()->to_string()
+            << " (" << links.size() << " links)");
+    
+    // remove all links that used the terminated connection
+    for ( vector<LinkID*>::iterator it = links.begin(); it != links.end(); ++it )
+    {
+        LinkID& link_id = **it;
+        
+        logging_debug("  ---> Removing link: " << link_id.toString());
+        
+        // searching for link, not found-> warn
+        LinkDescriptor& linkDesc = queryLocalLink( link_id );
+        if (linkDesc.isUnspecified()) {
+            logging_warn("Failed to find local link " << link_id.toString());
+            continue;
+        }
+
+        // inform listeners
+        foreach( CommunicationEvents* i, eventListener ){
+            i->onLinkFail( linkDesc.localLink,
+                    linkDesc.localLocator, linkDesc.remoteLocator );
+        }
+
+        // remove the link descriptor
+        removeLink( link_id );
+    }
+}
+
+/// ARIBA thread (System Queue)
 void BaseCommunication::receiveMessage(transport_connection::sptr connection,
-        reboost::message_t message)
+        reboost::shared_buffer_t message)
 {
-    
-    //// Adapt to old message system ////
-    // Copy data
-    size_t bytes_len = message.size();
-    uint8_t* bytes = new uint8_t[bytes_len];
-    message.read(bytes, 0, bytes_len);
-    
-    Data data(bytes, bytes_len * 8);
-    
-    Message legacy_message;
-    legacy_message.setPayload(data);
-    
-    
-    
-	/// decapsulate message
-	AribaBaseMsg* msg = legacy_message.decapsulate<AribaBaseMsg>();
-	logging_debug( "Receiving message of type " << msg->getTypeString() );
-
+    // XXX
+    logging_debug("/// [receiveMessage] buffersize: " << message.size());
+        
+    // get type
+    uint8_t type = message.data()[0];
+    reboost::shared_buffer_t sub_buff = message(1);
+    
+    // get link id
+    LinkID link_id;
+    if ( type != AribaBaseMsg::typeLinkRequest)
+    {
+        sub_buff = link_id.deserialize(sub_buff);
+    }
+    
 	// handle message
-	switch (msg->getType()) {
-
+	switch ( type )
+	{
 		// ---------------------------------------------------------------------
 		// data message
 		// ---------------------------------------------------------------------
-		case AribaBaseMsg::typeData: {
-			logging_debug( "Received data message, forwarding to overlay" );
-			if( messageReceiver != NULL ) {
+		case AribaBaseMsg::typeData:
+		{
+			logging_debug( "Received data message, forwarding to overlay." );
+			if( messageReceiver != NULL )
+			{
 				messageReceiver->receiveMessage(
-					msg, msg->getRemoteLink(), NodeID::UNSPECIFIED
+					sub_buff, link_id, NodeID::UNSPECIFIED, false
 				);
 			}
+			
 			break;
 		}
 
+        // ---------------------------------------------------------------------
+        // direct data message (bypass overlay-layer)
+        // ---------------------------------------------------------------------
+        case AribaBaseMsg::typeDirectData:
+        {
+            logging_debug( "Received direct data message, forwarding to application." );
+            
+            if( messageReceiver != NULL )
+            {
+                messageReceiver->receiveMessage(
+                    sub_buff, link_id, NodeID::UNSPECIFIED, true
+                );
+            }
+            
+            break;
+        }
+
+
+        
 		// ---------------------------------------------------------------------
 		// handle link request from remote
 		// ---------------------------------------------------------------------
-		case AribaBaseMsg::typeLinkRequest: {
-			logging_debug( "Received link open request" );
-
-			/// not the correct peer id-> skip request
-			if (!msg->getRemoteDescriptor().getPeerId().isUnspecified()
-				&& msg->getRemoteDescriptor().getPeerId() != localDescriptor.getPeerId()) {
-				logging_info("Received link request for "
-					<< msg->getRemoteDescriptor().getPeerId().toString()
-					<< "but i'm "
-					<< localDescriptor.getPeerId()
-					<< ": Ignoring!");
-				break;
-			}
-
+		case AribaBaseMsg::typeLinkRequest:
+		{
+			logging_debug( "Received link open request on "
+			        << connection->getLocalEndpoint()->to_string() );
+			
+			/*
+			 * Deserialize Peer Message
+			 * - Our PeerID 
+			 */
+			PeerID our_peer_id;
+			sub_buff = our_peer_id.deserialize(sub_buff);
+
+            /// not the correct peer id-> skip request
+            if ( our_peer_id != localDescriptor.getPeerId() &&
+                    ! our_peer_id.isUnspecified() /* overlay bootstrap */ )
+            {
+                logging_info("Received link request for "
+                    << our_peer_id.toString()
+                    << "but i'm "
+                    << localDescriptor.getPeerId()
+                    << ": Ignoring!");
+                
+                // TODO terminate connection?
+                
+                break;
+            }
+
+            
+		    /*
+		     * Deserialize Link-Request Message:
+		     * - Their LinkID
+		     * - Their PeerID
+		     * - Their EndpointDescriptor
+		     */
+            LinkID their_link_id;
+            PeerID their_peer_id;
+            EndpointSetPtr their_endpoints = endpoint_set::create_EndpointSet();
+            sub_buff = their_link_id.deserialize(sub_buff);
+            sub_buff = their_peer_id.deserialize(sub_buff);
+            sub_buff = their_endpoints->deserialize(sub_buff);
+            /* [ Deserialize Link-Request Message ] */
+
+            
 			/// only answer the first request
-			if (!queryRemoteLink(msg->getLocalLink()).isUnspecified()) {
+			if (!queryRemoteLink(their_link_id).isUnspecified())
+			{
+			    
+			    // TODO aktuell: When will these connections be closed?
+			    // ---> Close it now (if it services no links) ?
+			    //   (see also ! allowlink below)
+			    
+			    // XXX AKTUELL TESTING !! This will cause race conditions. So this is test-code only!
+			    if ( connection->get_communication_links().size() == 0 )
+			    {
+			        connection->terminate();
+			    }
+			    
 				logging_debug("Link request already received. Ignore!");
 				break;
@@ -386,5 +481,5 @@
 			/// create link ids
 			LinkID localLink  = LinkID::create();
-			LinkID remoteLink = msg->getLocalLink();
+			LinkID remoteLink = their_link_id;  // XXX intermediate variable is unnecessary
 			logging_debug(
 			        "local=" << connection->getLocalEndpoint()->to_string()
@@ -394,5 +489,5 @@
 			// check if link creation is allowed by ALL listeners
 			bool allowlink = true;
-			BOOST_FOREACH( CommunicationEvents* i, eventListener ){
+			foreach( CommunicationEvents* i, eventListener ){
 				allowlink &= i->onLinkRequest( localLink,
 				        connection->getLocalEndpoint(),
@@ -403,5 +498,4 @@
 			if( !allowlink ){
 				logging_warn( "Overlay denied creation of link" );
-				delete msg;
 				return;
 			}
@@ -411,16 +505,13 @@
 			ld->localLink = localLink;
 			ld->remoteLink = remoteLink;
-			ld->localLocator = connection->getLocalEndpoint()->clone();
-			ld->remoteLocator = connection->getRemoteEndpoint()->clone();
-			ld->connection = connection;
-			ld->remoteEndpoint = msg->getLocalDescriptor();
-			add_endpoint(ld->remoteLocator);
-
-			// add layer 1-3 addresses
-			ld->remoteEndpoint.getEndpoints().add(
-				ld->remoteLocator, endpoint_set::Layer1_3 | endpoint_set::NoLoopback);
-			localDescriptor.getEndpoints().add(
-				connection->getLocalEndpoint(),
-				endpoint_set::Layer1_3 | endpoint_set::NoLoopback);
+			ld->localLocator = connection->getLocalEndpoint();
+			ld->remoteLocator = connection->getRemoteEndpoint();
+			ld->remoteDescriptor = EndpointDescriptor(their_peer_id, their_endpoints);
+			ld->set_connection(connection);
+
+            
+			// update endpoints (should only have any effect in case of NAT)
+			ld->remoteDescriptor.endpoints->add_endpoint(connection->getRemoteEndpoint());
+//			localDescriptor.endpoints->add_endpoint(connection->getLocalEndpoint());  // XXX 0.0.0.0:0
 
 			// link is now up-> add it
@@ -428,24 +519,48 @@
 			addLink(ld);
 
-			// link is up!
-			logging_debug( "Link (initiated from remote) is up with "
-				<< "local(id=" << ld->localLink.toString() << ","
-				<< "locator=" << ld->localLocator->to_string() << ") "
-				<< "remote(id=" << ld->remoteLink.toString() << ", "
-				<< "locator=" << ld->remoteLocator->to_string() << ")"
-			);
-
-			// sending link request reply
-			logging_debug( "Sending link request reply with ids "
-				<< "local=" << localLink.toString() << ", "
-				<< "remote=" << remoteLink.toString() );
-			AribaBaseMsg reply( AribaBaseMsg::typeLinkReply, localLink, remoteLink );
-			reply.getLocalDescriptor() = localDescriptor;
-			reply.getRemoteDescriptor() = ld->remoteEndpoint;
-
-			send( &reply, *ld );
+
+			
+            /* sending link reply */
+            logging_debug( "Sending link reply with ids "
+                << "local=" << localLink.toString() << ", "
+                << "remote=" << remoteLink.toString() );
+
+		    /*
+		     * Create Link-Reply Message:
+		     * - Our LinkID
+		     * - Our Endpoint_Set (as update)
+		     * - Their EndpointDescriptor (maybe they learn something about NAT)
+		     */
+		    reboost::message_t linkmsg;
+		    linkmsg.push_back(localLink.serialize());
+		    linkmsg.push_back(localDescriptor.endpoints->serialize());
+		    linkmsg.push_back(ld->remoteDescriptor.endpoints->serialize());
+		    
+		    // XXX
+		    cout << "/// MARIO: " << ld->get_connection()->getRemoteEndpoint()->to_string() << endl;
+		    
+		    // send message
+			bool sent = send_over_link( AribaBaseMsg::typeLinkReply, linkmsg, *ld, system_priority::OVERLAY );
+			
+			if ( ! sent )
+			{
+			    logging_error("ERROR: Could not send LinkReply to: " << ld->remoteLocator->to_string());
+			    
+			    // TODO remove link, close link, ..?
+			    
+			    break;
+			}
+
+
+            // link is up!
+            logging_debug( "Link (initiated from remote) is up with "
+                << "local(id=" << ld->localLink.toString() << ","
+                << "locator=" << ld->localLocator->to_string() << ") "
+                << "remote(id=" << ld->remoteLink.toString() << ", "
+                << "locator=" << ld->remoteLocator->to_string() << ")"
+            );
 
 			// inform listeners about new open link
-			BOOST_FOREACH( CommunicationEvents* i, eventListener ) {
+			foreach( CommunicationEvents* i, eventListener ) {
 				i->onLinkUp( localLink, ld->localLocator, ld->remoteLocator);
 			}
@@ -458,35 +573,63 @@
 		// handle link request reply
 		// ---------------------------------------------------------------------
-		case AribaBaseMsg::typeLinkReply: {
+		case AribaBaseMsg::typeLinkReply:
+		{
 			logging_debug( "Received link open reply for a link we initiated" );
 
+            /*
+             * Deserialize Link-Reply Message:
+             * - Their LinkID
+             * - Their Endpoint_Set (as update)
+             * - Our EndpointDescriptor (maybe we can learn something about NAT)
+             */
+			LinkID their_link_id;
+			EndpointSetPtr their_endpoints = endpoint_set::create_EndpointSet();
+			EndpointSetPtr our_endpoints = endpoint_set::create_EndpointSet();
+			sub_buff = their_link_id.deserialize(sub_buff);
+			sub_buff = their_endpoints->deserialize(sub_buff);
+			sub_buff = our_endpoints->deserialize(sub_buff);
+
+            
 			// this is a reply to a link open request, so we have already
 			// a link mapping and can now set the remote link to valid
-			LinkDescriptor& ld = queryLocalLink( msg->getRemoteLink() );
+			LinkDescriptor& ld = queryLocalLink( link_id );
 
 			// no link found-> warn!
 			if (ld.isUnspecified()) {
-				logging_warn("Failed to find local link " << msg->getRemoteLink().toString());
-				delete msg;
+				logging_warn("Failed to find local link " << link_id.toString());
 				return;
 			}
+			
+			if ( ld.up )
+			{
+                logging_warn("Got link replay for already open link. Ignore. LinkID: " << link_id.toString());
+                
+                // TODO send LinkClose ?
+                return;			    
+			}
 
 			// store the connection
-			ld.connection = connection;
+			ld.set_connection(connection);
 			
 			// set remote locator and link id
-			ld.remoteLink = msg->getLocalLink();
-			ld.remoteLocator = connection->getRemoteEndpoint()->clone();
-			ld.remoteEndpoint.getEndpoints().add(
-							msg->getLocalDescriptor().getEndpoints(),
-							endpoint_set::Layer1_4
-						);
-
-			localDescriptor.getEndpoints().add(
-				msg->getRemoteDescriptor().getEndpoints(),
-				endpoint_set::Layer1_3
-			);
+			ld.remoteLink = their_link_id;
+			ld.remoteLocator = connection->getRemoteEndpoint();
+			
+			
+			/* Update endpoints */
+			// NOTE: we might loose some information here, but it's our only chance to get rid of outdated information.
+			ld.remoteDescriptor.replace_endpoint_set(their_endpoints);
+			
+			// add actual remote endpoint to this set (should only have any effect in case of NAT)
+			ld.remoteDescriptor.endpoints->add_endpoint(connection->getRemoteEndpoint());
+			
+			// TODO In case of NAT, we could learn something about our external IP.
+			//   ---> But we must trust the remote peer about this information!!  
+//			localDescriptor.endpoints->add_endpoints(our_endpoints);
+			
+			
+			
+			
 			ld.up = true;
-			add_endpoint(ld.remoteLocator);
 
 			logging_debug( "Link is now up with local id "
@@ -496,5 +639,5 @@
 
 			// inform lisneters about link up event
-			BOOST_FOREACH( CommunicationEvents* i, eventListener ){
+			foreach( CommunicationEvents* i, eventListener ){
 				i->onLinkUp( ld.localLink, ld.localLocator, ld.remoteLocator );
 			}
@@ -509,17 +652,16 @@
 		case AribaBaseMsg::typeLinkClose: {
 			// get remote link
-			const LinkID& localLink = msg->getRemoteLink();
-			logging_debug( "Received link close request for link " << localLink.toString() );
+//			const LinkID& localLink = msg.getRemoteLink();
+			logging_debug( "Received link close request for link " << link_id.toString() );
 
 			// searching for link, not found-> warn
-			LinkDescriptor& linkDesc = queryLocalLink( localLink );
+			LinkDescriptor& linkDesc = queryLocalLink( link_id );
 			if (linkDesc.isUnspecified()) {
-				logging_warn("Failed to find local link " << localLink.toString());
-				delete msg;
+				logging_warn("Failed to find local link " << link_id.toString());
 				return;
 			}
 
 			// inform listeners
-			BOOST_FOREACH( CommunicationEvents* i, eventListener ){
+			foreach( CommunicationEvents* i, eventListener ){
 				i->onLinkDown( linkDesc.localLink,
 						linkDesc.localLocator, linkDesc.remoteLocator );
@@ -527,5 +669,5 @@
 
 			// remove the link descriptor
-			removeLink( localLink );
+			removeLink( link_id );
 
 			// done
@@ -534,41 +676,47 @@
 
 		// ---------------------------------------------------------------------
-		// handle link locator changes
+		// handle link locator changes  -- TODO is this ever called..?
 		// ---------------------------------------------------------------------
-		case AribaBaseMsg::typeLinkUpdate: {
-			const LinkID& localLink = msg->getRemoteLink();
-			logging_debug( "Received link update for link "
-				<< localLink.toString() );
-
-			// find the link description
-			LinkDescriptor& linkDesc = queryLocalLink( localLink );
-			if (linkDesc.isUnspecified()) {
-				logging_warn("Failed to update local link "
-					<< localLink.toString());
-				delete msg;
-				return;
-			}
-
-			// update the remote locator
-			const address_v* oldremote = linkDesc.remoteLocator;
-			linkDesc.remoteLocator = connection->getRemoteEndpoint()->clone();
-
-			// inform the listeners (local link has _not_ changed!)
-			BOOST_FOREACH( CommunicationEvents* i, eventListener ){
-				i->onLinkChanged(
-					linkDesc.localLink,	// linkid
-					linkDesc.localLocator,	// old local
-					linkDesc.localLocator,	// new local
-					oldremote,		// old remote
-					linkDesc.remoteLocator	// new remote
-				);
-			}
-
-			// done
-			break;
-		}
-	}
-
-	delete msg;
+//		case AribaBaseMsg::typeLinkUpdate: {
+//			const LinkID& localLink = msg.getRemoteLink();
+//			logging_debug( "Received link update for link "
+//				<< localLink.toString() );
+//
+//			// find the link description
+//			LinkDescriptor& linkDesc = queryLocalLink( localLink );
+//			if (linkDesc.isUnspecified()) {
+//				logging_warn("Failed to update local link "
+//					<< localLink.toString());
+//				return;
+//			}
+//
+//			// update the remote locator
+//			addressing2::EndpointPtr oldremote = linkDesc.remoteLocator;
+//			linkDesc.remoteLocator = connection->getRemoteEndpoint();
+//			
+//			// TODO update linkDesc.connection ?
+//
+//			// inform the listeners (local link has _not_ changed!)
+//			foreach( CommunicationEvents* i, eventListener ){
+//				i->onLinkChanged(
+//					linkDesc.localLink,	// linkid
+//					linkDesc.localLocator,	// old local
+//					linkDesc.localLocator,	// new local
+//					oldremote,		        // old remote
+//					linkDesc.remoteLocator	// new remote
+//				);
+//			}
+//
+//			// done
+//			break;
+//		}
+		
+		
+        default: {
+            logging_warn( "Received unknown message type!" );
+            break;
+        }
+
+	}
 }
 
@@ -582,5 +730,5 @@
 	for(LinkSet::iterator i=linkSet.begin(); i != linkSet.end(); i++){
 		if( (*i)->localLink != localLink) continue;
-		remove_endpoint((*i)->remoteLocator);
+//		remove_endpoint((*i)->remoteLocator);  // XXX
 		delete *i;
 		linkSet.erase( i );
@@ -605,25 +753,18 @@
 }
 
-LinkIDs BaseCommunication::getLocalLinks( const address_v* addr ) const {
-	LinkIDs ids;
-	for (size_t i=0; i<linkSet.size(); i++){
-		if( addr == NULL ){
-			ids.push_back( linkSet[i]->localLink );
-		} else {
-			if ( *linkSet[i]->remoteLocator == *addr )
-				ids.push_back( linkSet[i]->localLink );
-		}
-	}
-	return ids;
-}
+//LinkIDs BaseCommunication::getLocalLinks( const address_v* addr ) const {
+//	LinkIDs ids;
+//	for (size_t i=0; i<linkSet.size(); i++){
+//		if( addr == NULL ){
+//			ids.push_back( linkSet[i]->localLink );
+//		} else {
+//			if ( *linkSet[i]->remoteLocator == *addr )
+//				ids.push_back( linkSet[i]->localLink );
+//		}
+//	}
+//	return ids;
+//}
 
 void BaseCommunication::onNetworkChange(const NetworkChangeInterface::NetworkChangeInfo& info){
-
-#ifdef UNDERLAY_OMNET
-
-	// we have no mobility support for simulations
-	return
-
-#endif // UNDERLAY_OMNET
 
 /*- disabled!
@@ -762,33 +903,77 @@
 }
 
-/// sends a message to all end-points in the end-point descriptor
-void BaseCommunication::send(Message* legacy_message, const EndpointDescriptor& endpoint) {
-	Data data = data_serialize(legacy_message, DEFAULT_V);
-	
-	//// Adapt to new message system ////
-	// transfer data buffer ownership to the shared_buffer
-    reboost::shared_buffer_t buf(data.getBuffer(), data.getLength() / 8);
-	
-	reboost::message_t message;
-	message.push_back(buf);
-	
-	transport->send(endpoint.getEndpoints(), message);
-}
-
-/// sends a message to the remote locator inside the link descriptor
-void BaseCommunication::send(Message* legacy_message, const LinkDescriptor& desc) {
-	if (desc.remoteLocator==NULL) return;
-	
-	Data data = data_serialize(legacy_message, DEFAULT_V);
-    
-    //// Adapt to new message system ////
-    // transfer data buffer ownership to the shared_buffer
-    reboost::shared_buffer_t buf(data.getBuffer(), data.getLength() / 8);
-    
-    reboost::message_t message;
-    message.push_back(buf);
-    
-	desc.connection->send(message);
-}
+
+addressing2::EndpointPtr BaseCommunication::get_local_endpoint_of_link(
+        const LinkID& linkid)
+{
+    LinkDescriptor& ld = queryLocalLink(linkid);
+    
+    return ld.get_connection()->getLocalEndpoint();
+}
+
+addressing2::EndpointPtr BaseCommunication::get_remote_endpoint_of_link(
+        const LinkID& linkid)
+{
+    LinkDescriptor& ld = queryLocalLink(linkid);
+    
+    return ld.get_connection()->getRemoteEndpoint();
+}
+
+
+
+bool BaseCommunication::send_over_link(
+        const uint8_t type,
+        reboost::message_t message,
+        const LinkDescriptor& desc,
+        const uint8_t priority)
+{
+    /*
+     * Create Link Message:
+     * - Type
+     * - Their LinkID
+     */
+    // link id
+    message.push_front(desc.remoteLink.serialize());
+    // type
+    memcpy(message.push_front(sizeof(uint8_t)).mutable_data(), &type, sizeof(uint8_t));
+    /* [ Create Link Message ] */
+    
+    
+    /* send message */
+    transport_connection::sptr conn = desc.get_connection();
+    if ( ! conn )
+    {
+        cout << "/// MARIO: No connection!!" << endl;  // XXX debug
+        return false;
+    }
+    
+    // * send over connection *
+    return conn->send(message, priority);
+}
+
+void BaseCommunication::send_to_peer(
+        const uint8_t type,
+        const PeerID& peer_id,
+        reboost::message_t message,
+        const EndpointDescriptor& endpoint,
+        const uint8_t priority )
+{
+    /*
+     * Create Peer Message:
+     * - Type
+     * - Their PeerID
+     */
+    // peer id
+    message.push_front(peer_id.serialize());
+    // type
+    memcpy(message.push_front(sizeof(uint8_t)).mutable_data(), &type, sizeof(uint8_t));
+    
+    
+    /* send message */
+    transport->send(endpoint.getEndpoints(), message, priority);
+}
+
+
+
 
 }} // namespace ariba, communication
Index: source/ariba/communication/BaseCommunication.h
===================================================================
--- source/ariba/communication/BaseCommunication.h	(revision 11885)
+++ source/ariba/communication/BaseCommunication.h	(revision 12060)
@@ -50,7 +50,13 @@
 #include <boost/foreach.hpp>
 
+#ifdef ECLIPSE_PARSER
+    #define foreach(a, b) for(a : b)
+#else
+    #define foreach(a, b) BOOST_FOREACH(a, b)
+#endif
+
 // utilities
 #include "ariba/utility/types.h"
-#include "ariba/utility/messages.h"
+#include "ariba/utility/messages/MessageReceiver.h"
 #include "ariba/utility/logging/Logging.h"
 #include "ariba/utility/misc/Demultiplexer.hpp"
@@ -58,7 +64,8 @@
 
 // new transport and addressing
-#include "ariba/utility/addressing/addressing.hpp"
-#include "ariba/utility/transport/transport.hpp"
-#include "ariba/utility/transport/transport_connection.hpp"
+#include "ariba/utility/transport/transport_peer.hpp"
+#include "ariba/utility/transport/interfaces/transport_connection.hpp"
+#include "ariba/utility/transport/interfaces/transport_listener.hpp"
+#include "ariba/utility/addressing2/endpoint.hpp"
 
 // communication
@@ -72,14 +79,6 @@
 #include "ariba/communication/networkinfo/NetworkInformation.h"
 
-// disabled
-//#ifndef UNDERLAY_OMNET
-//  #include "ariba/communication/modules/transport/tcp/TCPTransport.h"
-//  #include "ariba/communication/modules/network/ip/IPv4NetworkProtocol.h"
-//  using ariba::communication::IPv4NetworkProtocol;
-//  using ariba::communication::TCPTransport;
-//#endif
-
 namespace ariba {
-  class SideportListener;
+    class SideportListener;
 }
 
@@ -87,6 +86,20 @@
 namespace communication {
 
+
+class communication_message_not_sent: public std::runtime_error
+{
+public:
+    /** Takes a character string describing the error.  */
+    explicit communication_message_not_sent(const string& __arg)  :
+        std::runtime_error(__arg)
+    {
+    }
+    
+    virtual ~communication_message_not_sent() throw() {}
+};
+
+
+
 using namespace std;
-using namespace ariba::addressing;
 using namespace ariba::transport;
 using namespace ariba::utility;
@@ -102,9 +115,8 @@
  * protocols and addressing schemes.
  *
- * @author Sebastian Mies, Christoph Mayer
+ * @author Sebastian Mies, Christoph Mayer, Mario Hock
  */
 class BaseCommunication:
 	public NetworkChangeInterface,
-	public SystemEventListener,
 	public transport_listener {
 
@@ -120,11 +132,8 @@
 
 	/// Startup the base communication, start modules etc.
-	void start();
+	void start(addressing2::EndpointSetPtr listen_on);
 
 	/// Stops the base communication, stop modules etc.
 	void stop();
-
-	/// Sets the endpoints
-	void setEndpoints( string& endpoints );
 
 	/// Check whether the base communication has been started up
@@ -147,5 +156,8 @@
 	 * @return A sequence number for this message
 	 */
-	seqnum_t sendMessage(const LinkID lid, const Message* message);
+	seqnum_t sendMessage(const LinkID& lid,
+	        reboost::message_t message,
+	        uint8_t priority,
+	        bool bypass_overlay = false) throw(communication_message_not_sent);
 
 	/**
@@ -164,5 +176,5 @@
 	 * @return List of LinkID
 	 */
-	LinkIDs getLocalLinks(const address_v* addr) const;
+//	LinkIDs getLocalLinks(const address_v* addr) const;  // XXX aktuell
 
 	/**
@@ -187,7 +199,4 @@
 
 	void unregisterEventListener(CommunicationEvents* _events);
-
-	/// called when a system event is emitted by system queue
-	virtual void handleSystemEvent(const SystemEvent& event);
 
 	/**
@@ -196,6 +205,16 @@
 	 */ 
 	virtual void receive_message(transport_connection::sptr connection,
-		reboost::message_t msg);
-
+		reboost::shared_buffer_t msg);
+
+    /**
+     * called within the ASIO thread
+     * when a connection is terminated (e.g. TCP close)
+     */ 
+    virtual void connection_terminated(transport_connection::sptr connection);
+
+    addressing2::EndpointPtr get_local_endpoint_of_link(const LinkID& linkid);
+    addressing2::EndpointPtr get_remote_endpoint_of_link(const LinkID& linkid);
+
+	
 protected:
 
@@ -205,5 +224,12 @@
 	 */ 
 	void receiveMessage(transport_connection::sptr connection,
-	        reboost::message_t msg);
+	        reboost::shared_buffer_t message);
+	
+    /**
+     * called within the ARIBA thread (System Queue)
+     * when a connection is terminated (e.g. TCP close)
+     */ 
+    void connectionTerminated(transport_connection::sptr connection);
+	
 
 	/// called when a network interface change happens
@@ -221,12 +247,15 @@
 		/// default constructor
 		LinkDescriptor() :
-			localLink(LinkID::UNSPECIFIED), localLocator(NULL),
-			remoteLink(LinkID::UNSPECIFIED), remoteLocator(NULL),
+			localLink(LinkID::UNSPECIFIED),
+			remoteLink(LinkID::UNSPECIFIED),
 			up(false) {
 		}
 
-		~LinkDescriptor() {
-			if (localLocator!=NULL)  delete localLocator;
-			if (remoteLocator!=NULL) delete remoteLocator;
+		~LinkDescriptor()
+		{
+			if ( connection )
+			{
+			    connection->unregister_communication_link(&localLink);
+			}
 		}
 
@@ -240,4 +269,26 @@
 			return *unspec;
 		}
+		
+		
+		transport_connection::sptr get_connection() const
+		{
+		    return connection;
+		}
+		
+		void set_connection(const transport_connection::sptr& conn)
+		{
+		    // unregister from old connection,
+		    // if any (but normally there shouldn't..)
+		    if ( connection )
+		    {
+		        connection->unregister_communication_link(&localLink);
+		    }
+
+		    // * set_connection *
+		    connection = conn;
+		    
+		    // register this link with the connection
+		    conn->register_communication_link(&localLink);
+		}
 
 		bool unspecified;
@@ -245,16 +296,18 @@
 		/// link identifiers
 		LinkID localLink;
-		const address_v* localLocator;
+		addressing2::EndpointPtr localLocator;
 
 		/// used underlay addresses for the link
 		LinkID remoteLink;
-		const address_v* remoteLocator;
+		addressing2::EndpointPtr remoteLocator;
 
 		/// the remote end-point descriptor
-		EndpointDescriptor remoteEndpoint;
+		EndpointDescriptor remoteDescriptor;
 
 		/// flag, whether this link is up
 		bool up;
 		
+		
+	private:
 		/// connection if link is up
 		transport_connection::sptr connection;
@@ -281,23 +334,51 @@
 	/// The local end-point descriptor
 	EndpointDescriptor localDescriptor;
-
-#ifndef UNDERLAY_OMNET
+	
+	/**
+	 * endpoint_set holding the addresses of the "server"-sockets,
+	 * ---> that should be opened
+	 * 
+	 * (e.g. 0.0.0.0:41322)
+	 */
+	addressing2::EndpointSetPtr listenOn_endpoints;
+	
+    /**
+     * endpoint_set holding the addresses of the "server"-sockets,
+     * ---> that are actually open
+     * 
+     * (e.g. 0.0.0.0:41322)
+     * 
+     * XXX should only be in transport_peer
+     */
+	addressing2::EndpointSetPtr active_listenOn_endpoints;
+	
+    /**
+     * endpoint_set holding the addresses of the "server"-sockets,
+     * ---> here the discovered "addressable" addresses are stored
+     * 
+     * (e.g. 192.168.0.5:41322)
+     * 
+     * XXX should only be in localDescriptor
+     */
+	addressing2::EndpointSetPtr local_endpoints;
+
 	/// network change detector
 	NetworkChangeDetection networkMonitor;
-#endif
 
 	/// list of all remote addresses of links to end-points
-	class endpoint_reference {
-	public:
-		int count; ///< the number of open links to this end-point
-		const address_v* endpoint; ///< the end-point itself
-	};
-	vector<endpoint_reference> remote_endpoints;
-
-	/// adds an end-point to the list
-	void add_endpoint( const address_v* endpoint );
-
-	/// removes an end-point from the list
-	void remove_endpoint( const address_v* endpoint );
+	// XXX DEPRECATED
+//	class endpoint_reference {
+//	public:
+//		int count; ///< the number of open links to this end-point
+//		const address_v* endpoint; ///< the end-point itself
+//	};
+//	vector<endpoint_reference> remote_endpoints;
+
+	// XXX DEPRECATED
+//	/// adds an end-point to the list
+//	void add_endpoint( const address_v* endpoint );
+//
+//	/// removes an end-point from the list
+//	void remove_endpoint( const address_v* endpoint );
 
 	/// event listener
@@ -314,7 +395,26 @@
 	MessageReceiver* messageReceiver;
 
-	/// convenience: send message to peer
-	void send( Message* message, const EndpointDescriptor& endpoint );
-	void send( Message* message, const LinkDescriptor& descriptor );
+	
+	/* 
+	 * Sends a message over an existing link.
+	 *   ---> Adds Â»Link MessageÂ« Header
+	 */
+	bool send_over_link(
+	        const uint8_t type,
+	        reboost::message_t message,
+	        const LinkDescriptor& desc,
+	        const uint8_t priority);
+
+    /* 
+     * Sends a message to a known peer. (To all known endpoints.)
+     *   ---> Adds Â»Peer MessageÂ« Header
+     */
+	void send_to_peer(
+	        const uint8_t type,
+	        const PeerID& peer_id,
+	        reboost::message_t message,
+	        const EndpointDescriptor& endpoint,
+	        const uint8_t priority );
+	
 
 	/// state of the base communication
Index: source/ariba/communication/CommunicationEvents.cpp
===================================================================
--- source/ariba/communication/CommunicationEvents.cpp	(revision 11885)
+++ source/ariba/communication/CommunicationEvents.cpp	(revision 12060)
@@ -49,27 +49,35 @@
 
 bool CommunicationEvents::onLinkRequest(const LinkID& id,
-	const address_v* local, const address_v* remote) {
+        const addressing2::EndpointPtr local,
+        const addressing2::EndpointPtr remote)
+{
 	return true;
 }
 
-void CommunicationEvents::onLinkUp(const LinkID& id, const address_v* local,
-	const address_v* remote) {
+void CommunicationEvents::onLinkUp(const LinkID& id,
+        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote)
+{
 }
 
-void CommunicationEvents::onLinkDown(const LinkID& id, const address_v* local,
-	const address_v* remote) {
+void CommunicationEvents::onLinkDown(const LinkID& id,
+        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote)
+{
 }
 
 void CommunicationEvents::onLinkChanged(const LinkID& id,
-	const address_v* oldlocal, const address_v* newlocal,
-	const address_v* oldremote, const address_v* newremote) {
+        const addressing2::EndpointPtr oldlocal,  const addressing2::EndpointPtr newlocal,
+        const addressing2::EndpointPtr oldremote, const addressing2::EndpointPtr newremote)
+{
 }
 
-void CommunicationEvents::onLinkFail(const LinkID& id, const address_v* local,
-	const address_v* remote) {
+void CommunicationEvents::onLinkFail(const LinkID& id,
+        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote)
+{
 }
 
 void CommunicationEvents::onLinkQoSChanged(const LinkID& id,
-	const address_v* local, const address_v* remote, const QoSParameterSet& qos) {
+        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote,
+        const QoSParameterSet& qos)
+{
 }
 
Index: source/ariba/communication/CommunicationEvents.h
===================================================================
--- source/ariba/communication/CommunicationEvents.h	(revision 11885)
+++ source/ariba/communication/CommunicationEvents.h	(revision 12060)
@@ -42,5 +42,5 @@
 #include "ariba/utility/types/LinkID.h"
 #include "ariba/utility/types/QoSParameterSet.h"
-#include "ariba/utility/addressing/addressing.hpp"
+#include "ariba/utility/addressing2/endpoint.hpp"
 
 namespace ariba {
@@ -49,5 +49,4 @@
 using ariba::utility::LinkID;
 using ariba::utility::QoSParameterSet;
-using namespace ariba::addressing;
 
 class CommunicationEvents {
@@ -68,6 +67,7 @@
 	 * @return True, if the link should be established
 	 */
-	virtual bool onLinkRequest(const LinkID& id, const address_v* local,
-		const address_v* remote);
+	virtual bool onLinkRequest(const LinkID& id,
+	        const addressing2::EndpointPtr local,
+	        const addressing2::EndpointPtr remote);
 
 	/**
@@ -77,6 +77,6 @@
 	 * @param id The link id of the established link
 	 */
-	virtual void onLinkUp(const LinkID& id, const address_v* local,
-		const address_v* remote);
+	virtual void onLinkUp(const LinkID& id,
+	        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote);
 
 	/**
@@ -85,6 +85,6 @@
 	 * @param id The link identifier of the dropped link
 	 */
-	virtual void onLinkDown(const LinkID& id, const address_v* local,
-		const address_v* remote);
+	virtual void onLinkDown(const LinkID& id,
+	        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote);
 
 	/**
@@ -97,13 +97,13 @@
 	 */
 	virtual void onLinkChanged(const LinkID& id,
-		const address_v* oldlocal,  const address_v* newlocal,
-		const address_v* oldremote, const address_v* newremote
-	);
+		const addressing2::EndpointPtr oldlocal,  const addressing2::EndpointPtr newlocal,
+		const addressing2::EndpointPtr oldremote, const addressing2::EndpointPtr newremote);
 
-	virtual void onLinkFail(const LinkID& id, const address_v* local,
-		const address_v* remote);
+	virtual void onLinkFail(const LinkID& id,
+	        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote);
 
-	virtual void onLinkQoSChanged(const LinkID& id, const address_v* local,
-		const address_v* remote, const QoSParameterSet& qos);
+	virtual void onLinkQoSChanged(const LinkID& id,
+	        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote,
+	        const QoSParameterSet& qos);
 };
 
Index: source/ariba/communication/EndpointDescriptor.cpp
===================================================================
--- source/ariba/communication/EndpointDescriptor.cpp	(revision 11885)
+++ source/ariba/communication/EndpointDescriptor.cpp	(revision 12060)
@@ -42,7 +42,9 @@
 namespace communication {
 
-vsznDefault(EndpointDescriptor);
+//vsznDefault(EndpointDescriptor);
 
-EndpointDescriptor::EndpointDescriptor(){
+EndpointDescriptor::EndpointDescriptor()  :
+        endpoints(new addressing2::endpoint_set())
+{
 }
 
@@ -55,10 +57,37 @@
 }
 
-EndpointDescriptor::EndpointDescriptor(const endpoint_set& endpoints ) :
-	endpoints(endpoints){
+EndpointDescriptor::EndpointDescriptor(
+        const PeerID& peer_id,
+        addressing2::EndpointSetPtr endpoints ) :
+    peerId(peer_id),
+	endpoints(endpoints)
+{
 }
 
-EndpointDescriptor::EndpointDescriptor(const string& str) : endpoints(str){
+EndpointDescriptor::EndpointDescriptor(const string& str)  :
+        endpoints(new addressing2::endpoint_set())
+{
+    cout << "ERROR: Construction of EndpointDescriptor from String is not functional!!" << endl;
+    assert( false );
 }
 
+
+reboost::message_t EndpointDescriptor::serialize() const
+{
+    reboost::message_t msg;
+    msg.push_back(peerId.serialize());
+    msg.push_back(endpoints->serialize());
+    
+    return msg;
+}
+
+reboost::shared_buffer_t EndpointDescriptor::deserialize(reboost::shared_buffer_t buff)
+{
+    buff = peerId.deserialize(buff);
+    buff = endpoints->deserialize(buff);
+    
+    return buff;
+}
+
+
 }} // namespace ariba, communication
Index: source/ariba/communication/EndpointDescriptor.h
===================================================================
--- source/ariba/communication/EndpointDescriptor.h	(revision 11885)
+++ source/ariba/communication/EndpointDescriptor.h	(revision 12060)
@@ -42,7 +42,12 @@
 #include <string>
 #include <set>
-#include "ariba/utility/serialization.h"
+//#include "ariba/utility/serialization.h"
 #include "ariba/utility/types/PeerID.h"
-#include "ariba/utility/addressing/endpoint_set.hpp"
+
+#include "ariba/utility/addressing2/endpoint_set.hpp"
+
+// reboost messages
+#include "ariba/utility/transport/messages/message.hpp"
+
 
 namespace ariba {
@@ -51,9 +56,18 @@
 using_serialization;
 using namespace std;
-using namespace ariba::addressing;
 using ariba::utility::PeerID;
 
-class EndpointDescriptor: public VSerializeable { VSERIALIZEABLE
-	friend class BaseCommunication;
+
+/**
+ * This class is used a transitions helper between the old addressing and
+ * serialization to the new addressing2 and the new message classes
+ * 
+ * Maybe it will be replaced, or at least modified in the future.
+ */
+//class EndpointDescriptor: public VSerializeable { VSERIALIZEABLE
+//    friend class BaseCommunication;
+class EndpointDescriptor
+{
+    friend class BaseCommunication;
 
 public:
@@ -68,6 +82,7 @@
 
 	/// construct end-points from an endpoint set
-	EndpointDescriptor(const endpoint_set& endpoints );
+	EndpointDescriptor(const PeerID& peer_id, addressing2::EndpointSetPtr endpoints );
 
+	// FIXME NOT WORKING !!
 	/// construct end-points from a string
 	EndpointDescriptor(const string& str);
@@ -75,5 +90,5 @@
 	/// convert end-points to string
 	string toString() const {
-		return endpoints.to_string();
+		return endpoints->to_string();
 	}
 
@@ -90,8 +105,8 @@
 	}
 
-	/// create endpoint
-	static EndpointDescriptor* fromString(string str) {
-		return new EndpointDescriptor(str);
-	}
+//	/// create endpoint
+//	static EndpointDescriptor* fromString(string str) {
+//		return new EndpointDescriptor(str);
+//	}
 
 	bool operator==(const EndpointDescriptor& rh) const {
@@ -113,13 +128,13 @@
 
 	/// returns the end-points of this descriptor
-	endpoint_set& getEndpoints() {
+	addressing2::const_EndpointSetPtr getEndpoints() const {
 		return endpoints;
 	}
-
-	/// returns the end-points of this descriptor
-	const endpoint_set& getEndpoints() const {
-		return endpoints;
+	
+	void replace_endpoint_set(addressing2::EndpointSetPtr new_endpoints)
+	{
+	    endpoints = new_endpoints;
 	}
-
+	
 	/// returns a reference to the peer id
 	PeerID& getPeerId() {
@@ -132,6 +147,13 @@
 		return peerId;
 	}
+	
+	/// returns a message with peerId and endpoints in it
+	reboost::message_t serialize() const;
+	
+	/// deserialite peerId and endpoints
+	reboost::shared_buffer_t deserialize(reboost::shared_buffer_t buff);
+	
 private:
-	endpoint_set endpoints;
+	addressing2::EndpointSetPtr endpoints;
 	PeerID peerId;
 };
@@ -139,18 +161,21 @@
 }} // namespace ariba, communication
 
-sznBeginDefault( ariba::communication::EndpointDescriptor, X ){
-
-	// serialize peer id
-	X && &peerId;
-
-	// serialize end-points
-	uint16_t len = endpoints.to_bytes_size();
-	X && len;
-	uint8_t* buffer = X.bytes( len );
-	if (buffer!=NULL) {
-		if (X.isDeserializer()) endpoints.assign(buffer,len);
-		else endpoints.to_bytes(buffer);
-	}
-}sznEnd();
+//sznBeginDefault( ariba::communication::EndpointDescriptor, X ){
+//
+//    // TODO
+//    assert(false);
+//    
+//	// serialize peer id
+//	X && &peerId;
+//
+//	// serialize end-points
+//	uint16_t len = endpoints.to_bytes_size();
+//	X && len;
+//	uint8_t* buffer = X.bytes( len );
+//	if (buffer!=NULL) {
+//		if (X.isDeserializer()) endpoints.assign(buffer,len);
+//		else endpoints.to_bytes(buffer);
+//	}
+//}sznEnd();
 
 #endif /*ENDPOINTDESCRIPTOR_H_*/
Index: source/ariba/communication/messages/AribaBaseMsg.h
===================================================================
--- source/ariba/communication/messages/AribaBaseMsg.h	(revision 11885)
+++ source/ariba/communication/messages/AribaBaseMsg.h	(revision 12060)
@@ -42,5 +42,6 @@
 #include <string>
 #include <boost/cstdint.hpp>
-#include "ariba/utility/messages.h"
+//#include "ariba/utility/messages.h"
+#include "ariba/utility/messages/Message.h"
 #include "ariba/utility/serialization.h"
 #include "ariba/utility/types/LinkID.h"
@@ -61,4 +62,5 @@
 using_serialization;
 
+// XXX This whole message is DEPRECATED
 class AribaBaseMsg : public Message {
 	VSERIALIZEABLE;
@@ -69,5 +71,6 @@
 		typeLinkReply = 2,
 		typeLinkClose = 3,
-		typeLinkUpdate = 4
+		typeLinkUpdate = 4,
+		typeDirectData = 5
 	};
 
@@ -115,8 +118,8 @@
 
 sznBeginDefault( ariba::communication::AribaBaseMsg, X ) {
-	X && type && &localLink && &remoteLink;
+	X && type && &remoteLink;
 	if (type == typeLinkReply || type == typeLinkRequest)
-		X && localDescriptor && remoteDescriptor;
-	X && Payload();
+		X && &localLink && localDescriptor && remoteDescriptor;
+//	X && Payload();
 } sznEnd();
 
Index: source/ariba/communication/messages/CMakeLists.txt
===================================================================
--- source/ariba/communication/messages/CMakeLists.txt	(revision 11885)
+++ source/ariba/communication/messages/CMakeLists.txt	(revision 12060)
@@ -37,5 +37,5 @@
 # [License]
 
-add_headers(AribaBaseMsg.h)
+#add_headers(AribaBaseMsg.h)
 
-add_sources(AribaBaseMsg.cpp)
+#add_sources(AribaBaseMsg.cpp)
Index: source/ariba/communication/networkinfo/AddressDiscovery.cpp
===================================================================
--- source/ariba/communication/networkinfo/AddressDiscovery.cpp	(revision 11885)
+++ source/ariba/communication/networkinfo/AddressDiscovery.cpp	(revision 12060)
@@ -49,4 +49,11 @@
 #include <ifaddrs.h>
 
+#include <string>
+#include <boost/asio/ip/address.hpp>
+#include <boost/foreach.hpp>
+
+#include "ariba/utility/addressing2/tcpip_endpoint.hpp"
+#include "ariba/utility/addressing/mac_address.hpp"
+
 #ifdef HAVE_LIBBLUETOOTH
   #include <bluetooth/bluetooth.h>
@@ -58,5 +65,13 @@
 namespace communication {
 
-mac_address AddressDiscovery::getMacFromIF( const char* name ) {
+
+using namespace std;
+using namespace addressing2;
+using namespace boost::asio::ip;
+
+using ariba::addressing::mac_address;
+
+mac_address getMacFromIF( const char* name )
+{
 	mac_address addr;
 #ifdef HAVE_LIBBLUETOOTH
@@ -73,72 +88,156 @@
 }
 
-int AddressDiscovery::dev_info(int s, int dev_id, long arg) {
-#ifdef HAVE_LIBBLUETOOTH
-	endpoint_set* set = (endpoint_set*)arg;
-	struct hci_dev_info di;
-	memset(&di, 0, sizeof(struct hci_dev_info));
-	di.dev_id = dev_id;
-	if (ioctl(s, HCIGETDEVINFO, (void *) &di)) return 0;
-	mac_address mac;
-	mac.bluetooth( di.bdaddr );
-	address_vf vf = mac;
-	set->add(vf);
+int dev_info(int s, int dev_id, long arg)
+{
+#ifdef HAVE_LIBBLUETOOTH
+//	endpoint_set* set = (endpoint_set*)arg;
+//	struct hci_dev_info di;
+//	memset(&di, 0, sizeof(struct hci_dev_info));
+//	di.dev_id = dev_id;
+//	if (ioctl(s, HCIGETDEVINFO, (void *) &di)) return 0;
+//	mac_address mac;
+//	mac.bluetooth( di.bdaddr );
+//	address_vf vf = mac;
+//	set->add(vf);
 #endif
 	return 0;
 }
 
-void AddressDiscovery::discover_bluetooth( endpoint_set& endpoints ) {
-#ifdef HAVE_LIBBLUETOOTH
-	hci_for_each_dev(HCI_UP, &AddressDiscovery::dev_info, (long)&endpoints );
-#endif
-}
-
-void AddressDiscovery::discover_ip_addresses( endpoint_set& endpoints ) {
-	struct ifaddrs* ifaceBuffer = NULL;
-	void*           tmpAddrPtr  = NULL;
-
-	int ret = getifaddrs( &ifaceBuffer );
-	if( ret != 0 ) return;
-
-	for( struct ifaddrs* i=ifaceBuffer; i != NULL; i=i->ifa_next ) {
-
-		// ignore devices that are disabled or have no ip
-		if(i == NULL) continue;
-		struct sockaddr* addr = i->ifa_addr;
-		if (addr==NULL) continue;
-
-		// ignore tun devices
-		string device = string(i->ifa_name);
-		if(device.find_first_of("tun") == 0) continue;
-
-		if (addr->sa_family == AF_INET) {
-			// look for ipv4
-			char straddr[INET_ADDRSTRLEN];
-			tmpAddrPtr= &((struct sockaddr_in*)addr)->sin_addr;
-			inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) );
-			ip_address ip = straddr;
-			if (ip.is_loopback()) continue;
-			address_vf vf = ip;
-			endpoints.add( vf );
-		} else
-		if (addr->sa_family == AF_INET6) {
-			// look for ipv6
-			char straddr[INET6_ADDRSTRLEN];
-			tmpAddrPtr= &((struct sockaddr_in6*)addr)->sin6_addr;
-			inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) );
-			ip_address ip = straddr;
-			if (ip.is_loopback()) continue;
-//			if (ip.is_link_local()) continue;
-			address_vf vf = ip;
-			endpoints.add( vf );
-		}
-	}
-
-	freeifaddrs(ifaceBuffer);
-}
-
-void AddressDiscovery::discover_endpoints( endpoint_set& endpoints ) {
-	discover_ip_addresses( endpoints );
-	discover_bluetooth( endpoints );
+void discover_bluetooth(
+        EndpointSetPtr listenOn_endpoints,
+        EndpointSetPtr discovered_endpoints )
+{
+#ifdef HAVE_LIBBLUETOOTH
+    // FIXME aktuell bluetooth
+//	hci_for_each_dev(HCI_UP, &AddressDiscovery::dev_info, (long)&endpoints );
+#endif
+}
+
+void discover_ip_addresses(
+        EndpointSetPtr listenOn_endpoints,
+        EndpointSetPtr discovered_endpoints )
+{
+    bool discover_ipv4 = false;
+    bool discover_ipv6 = false;
+    vector<uint16_t> ipv4_ports;
+    vector<uint16_t> ipv6_ports;
+    
+    /* analyze listenOn_endpoints */
+    BOOST_FOREACH( TcpIP_EndpointPtr endp, listenOn_endpoints->get_tcpip_endpoints() )
+    {
+        // BRANCH: IPv4 any [0.0.0.0]
+        if ( endp->to_asio().address() == address_v4::any() )
+        {
+            // add port
+            ipv4_ports.push_back(endp->to_asio().port());
+            
+            discover_ipv4 = true;
+        }
+
+        // BRANCH: IPv6 any [::]
+        else if ( endp->to_asio().address() == address_v6::any() )
+        {
+            // add port
+            ipv6_ports.push_back(endp->to_asio().port());
+            
+            discover_ipv6 = true;
+
+            
+            // NOTE: on linux the ipv6-any address [::] catches ipv4 as well
+            ipv4_ports.push_back(endp->to_asio().port());
+            discover_ipv4 = true;
+        }
+        
+        // BRANCH: explicit ip address
+        else
+        {
+            // ---> don't discover anything, just add it directly
+            discovered_endpoints->add_endpoint(endp);
+        }
+    }
+    
+    
+    /* discover addresses */
+    if ( discover_ipv4 || discover_ipv6 )
+    {
+        struct ifaddrs* ifaceBuffer = NULL;
+        void*           tmpAddrPtr  = NULL;
+    
+        int ret = getifaddrs( &ifaceBuffer );
+        if( ret != 0 ) return;
+    
+        for( struct ifaddrs* i=ifaceBuffer; i != NULL; i=i->ifa_next )
+        {
+            // ignore devices that are disabled or have no ip
+            if(i == NULL) continue;
+            struct sockaddr* addr = i->ifa_addr;
+            if (addr==NULL) continue;
+    
+    //		// ignore tun devices  // XXX why?
+    //		string device = string(i->ifa_name);
+    //		if(device.find_first_of("tun") == 0) continue;
+
+            // IPv4
+            if ( discover_ipv4 && addr->sa_family == AF_INET )
+            {
+                char straddr[INET_ADDRSTRLEN];
+                tmpAddrPtr= &((struct sockaddr_in*)addr)->sin_addr;
+                inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) );
+                
+                address ip_addr = address::from_string(straddr);
+    
+                // skip loopback address
+                if ( ip_addr.to_v4() == address_v4::loopback() )
+                    continue;
+
+                // add endpoint for this address and every given ipv4 port
+                BOOST_FOREACH( uint16_t port, ipv4_ports )
+                {
+                    tcp::endpoint tcpip_endp(ip_addr, port);
+                    TcpIP_EndpointPtr endp(new tcpip_endpoint(tcpip_endp));
+                    
+                    discovered_endpoints->add_endpoint(endp);
+                }
+            }
+            
+            // IPv6
+            else if ( discover_ipv6 && addr->sa_family == AF_INET6 )
+            {
+                // look for ipv6
+                char straddr[INET6_ADDRSTRLEN];
+                tmpAddrPtr= &((struct sockaddr_in6*)addr)->sin6_addr;
+                inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) );
+                
+                address ip_addr = address::from_string(straddr);
+                
+                // skip loopback address
+                if ( ip_addr.to_v6() == address_v6::loopback() )
+                    continue;
+
+                // add endpoint for this address and every given ipv4 port
+                BOOST_FOREACH( uint16_t port, ipv6_ports )
+                {
+                    tcp::endpoint tcpip_endp(ip_addr, port);
+                    TcpIP_EndpointPtr endp(new tcpip_endpoint(tcpip_endp));
+                    
+                    discovered_endpoints->add_endpoint(endp);
+                }
+            }
+        }
+    
+        freeifaddrs(ifaceBuffer);
+    }
+}
+
+
+
+EndpointSetPtr AddressDiscovery::discover_endpoints(EndpointSetPtr listenOn_endpoints)
+{
+    EndpointSetPtr discovered_endpoints(new addressing2::endpoint_set());
+    
+	discover_ip_addresses( listenOn_endpoints, discovered_endpoints );
+	discover_bluetooth( listenOn_endpoints, discovered_endpoints );
+	
+	return discovered_endpoints;
 }
 
Index: source/ariba/communication/networkinfo/AddressDiscovery.h
===================================================================
--- source/ariba/communication/networkinfo/AddressDiscovery.h	(revision 11885)
+++ source/ariba/communication/networkinfo/AddressDiscovery.h	(revision 12060)
@@ -40,20 +40,21 @@
 #define __ADDRESS_DISCOVERY_H
 
-#include "ariba/utility/addressing/addressing.hpp"
-
-using namespace ariba::addressing;
+#include "ariba/utility/addressing2/endpoint_set.hpp"
 
 namespace ariba {
 namespace communication {
 
+using addressing2::EndpointSetPtr;
+
 class AddressDiscovery {
 public:
-	static void discover_endpoints( endpoint_set& endpoints );
+	static EndpointSetPtr discover_endpoints(EndpointSetPtr listenOn_endpoints);
 
 private:
-	static mac_address getMacFromIF( const char* name );
-	static int dev_info(int s, int dev_id, long arg);
-	static void discover_bluetooth( endpoint_set& endpoints );
-	static void discover_ip_addresses( endpoint_set& endpoints );
+	// TODO aktuell weg damit..
+//	static mac_address getMacFromIF( const char* name );
+//	static int dev_info(int s, int dev_id, long arg);
+//	static void discover_bluetooth( EndpointSetPtr listenOn_endpoints, EndpointSetPtr discovered_endpoints );
+//	static void discover_ip_addresses( EndpointSetPtr listenOn_endpoints, EndpointSetPtr discovered_endpoints );
 };
 
Index: source/ariba/overlay/BaseOverlay.cpp
===================================================================
--- source/ariba/overlay/BaseOverlay.cpp	(revision 11885)
+++ source/ariba/overlay/BaseOverlay.cpp	(revision 12060)
@@ -57,11 +57,23 @@
 #include "ariba/utility/visual/DddVis.h"
 #include "ariba/utility/visual/ServerVis.h"
+#include <ariba/utility/misc/sha1.h>
 
 namespace ariba {
 namespace overlay {
+
+using namespace std;
+using ariba::transport::system_priority;
 
 #define visualInstance 		ariba::utility::DddVis::instance()
 #define visualIdOverlay 	ariba::utility::ServerVis::NETWORK_ID_BASE_OVERLAY
 #define visualIdBase		ariba::utility::ServerVis::NETWORK_ID_BASE_COMMUNICATION
+
+
+// time constants (in seconds)
+#define KEEP_ALIVE_TIME         60                      // send keep-alive message after link is not used for #s  
+
+#define LINK_ESTABLISH_TIME_OUT 10                      // timeout: link requested but not up
+#define KEEP_ALIVE_TIME_OUT     KEEP_ALIVE_TIME + LINK_ESTABLISH_TIME_OUT     // timeout: no data received on this link (incl. keep-alive messages)
+#define AUTO_LINK_TIME_OUT      KEEP_ALIVE_TIME_OUT                    // timeout: auto link not used for #s
 
 
@@ -85,5 +97,5 @@
 
 LinkDescriptor* BaseOverlay::getDescriptor( const LinkID& link, bool communication ) {
-	BOOST_FOREACH( LinkDescriptor* lp, links )
+	foreach( LinkDescriptor* lp, links )
 				if ((communication ? lp->communicationId : lp->overlayId) == link)
 					return lp;
@@ -92,5 +104,5 @@
 
 const LinkDescriptor* BaseOverlay::getDescriptor( const LinkID& link, bool communication ) const {
-	BOOST_FOREACH( const LinkDescriptor* lp, links )
+	foreach( const LinkDescriptor* lp, links )
 				if ((communication ? lp->communicationId : lp->overlayId) == link)
 					return lp;
@@ -122,13 +134,23 @@
 
 /// returns a auto-link descriptor
-LinkDescriptor* BaseOverlay::getAutoDescriptor( const NodeID& node, const ServiceID& service ) {
+LinkDescriptor* BaseOverlay::getAutoDescriptor( const NodeID& node, const ServiceID& service )
+{
 	// search for a descriptor that is already up
-	BOOST_FOREACH( LinkDescriptor* lp, links )
-				if (lp->autolink && lp->remoteNode == node && lp->service == service && lp->up && lp->keepAliveMissed == 0)
-					return lp;
+	foreach( LinkDescriptor* lp, links )
+    {
+        if (lp->autolink && lp->remoteNode == node && lp->service == service && isLinkVital(lp) )
+            return lp;
+    }
+	
 	// if not found, search for one that is about to come up...
-	BOOST_FOREACH( LinkDescriptor* lp, links )
-	if (lp->autolink && lp->remoteNode == node && lp->service == service && lp->keepAliveMissed == 0 )
-		return lp;
+	foreach( LinkDescriptor* lp, links )
+	{
+	    time_t now = time(NULL);
+	    
+        if (lp->autolink && lp->remoteNode == node && lp->service == service
+                && difftime( now, lp->keepAliveReceived ) <= LINK_ESTABLISH_TIME_OUT )
+            return lp;
+	}
+	
 	return NULL;
 }
@@ -136,35 +158,47 @@
 /// stabilizes link information
 void BaseOverlay::stabilizeLinks() {
-	// send keep-alive messages over established links
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
+    time_t now = time(NULL);
+    
+    // send keep-alive messages over established links
+	foreach( LinkDescriptor* ld, links )
+    {
 		if (!ld->up) continue;
-		OverlayMsg msg( OverlayMsg::typeLinkAlive,
-				OverlayInterface::OVERLAY_SERVICE_ID, nodeId, ld->remoteNode );
-		if (ld->relayed) msg.setRouteRecord(true);
-		send_link( &msg, ld->overlayId );
+		
+		if ( difftime( now, ld->keepAliveSent ) >= KEEP_ALIVE_TIME )
+		{
+		    logging_debug("[BaseOverlay] Sending KeepAlive over "
+		            << ld->to_string()
+		            << " after "
+		            << difftime( now, ld->keepAliveSent )
+		            << "s");
+		    
+            OverlayMsg msg( OverlayMsg::typeKeepAlive,
+                    OverlayInterface::OVERLAY_SERVICE_ID, nodeId, ld->remoteNode );
+            msg.setRouteRecord(true);
+            ld->keepAliveSent = now;
+            send_link( &msg, ld->overlayId, system_priority::OVERLAY );
+		}
 	}
 
 	// iterate over all links and check for time boundaries
 	vector<LinkDescriptor*> oldlinks;
-	time_t now = time(NULL);
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
-
-		// keep alives and not up? yes-> link connection request is stale!
-		if ( !ld->up && difftime( now, ld->keepAliveTime ) >= 2 ) {
-
-			// increase counter
-			ld->keepAliveMissed++;
-
-			// missed more than four keep-alive messages (10 sec)? -> drop link
-			if (ld->keepAliveMissed > 4) {
-				logging_info( "Link connection request is stale, closing: " << ld );
-				oldlinks.push_back( ld );
-				continue;
-			}
+	foreach( LinkDescriptor* ld, links ) {
+
+		// link connection request stale?
+		if ( !ld->up && difftime( now, ld->keepAliveReceived ) >= LINK_ESTABLISH_TIME_OUT )  // NOTE: keepAliveReceived == now, on connection request
+		{
+            logging_info( "Link connection request is stale, closing: " << ld );
+            ld->failed = true;
+            oldlinks.push_back( ld );
+            continue;
 		}
 
 		if (!ld->up) continue;
 
+		
+		
+		
 		// check if link is relayed and retry connecting directly
+		// TODO Mario: What happens here?  --> There are 3 attempts to replace a relayed link with a direct one. see: handleLinkReply
 		if ( ld->relayed && !ld->communicationUp && ld->retryCounter > 0) {
 			ld->retryCounter--;
@@ -173,5 +207,5 @@
 
 		// remote used as relay flag
-		if ( ld->relaying && difftime( now, ld->timeRelaying ) > 10)
+		if ( ld->relaying && difftime( now, ld->timeRelaying ) > KEEP_ALIVE_TIME_OUT)  // TODO is this a reasonable timeout ??
 			ld->relaying = false;
 
@@ -183,5 +217,5 @@
 
 		// auto-link time exceeded?
-		if ( ld->autolink && difftime( now, ld->lastuse ) > 30 ) {
+		if ( ld->autolink && difftime( now, ld->lastuse ) > AUTO_LINK_TIME_OUT ) {
 			oldlinks.push_back( ld );
 			continue;
@@ -189,20 +223,15 @@
 
 		// keep alives missed? yes->
-		if ( difftime( now, ld->keepAliveTime ) > 4 ) {
-
-			// increase counter
-			ld->keepAliveMissed++;
-
-			// missed more than four keep-alive messages (4 sec)? -> drop link
-			if (ld->keepAliveMissed >= 2) {
-				logging_info( "Link is stale, closing: " << ld );
-				oldlinks.push_back( ld );
-				continue;
-			}
+		if ( difftime( now, ld->keepAliveReceived ) >= KEEP_ALIVE_TIME_OUT )
+		{
+            logging_info( "Link is stale, closing: " << ld );
+            ld->failed = true;
+            oldlinks.push_back( ld );
+            continue;
 		}
 	}
 
 	// drop links
-	BOOST_FOREACH( LinkDescriptor* ld, oldlinks ) {
+	foreach( LinkDescriptor* ld, oldlinks ) {
 		logging_info( "Link timed out. Dropping " << ld );
 		ld->relaying = false;
@@ -210,8 +239,17 @@
 	}
 
-	// show link state
-	counter++;
-	if (counter>=4) showLinks();
-	if (counter>=4 || counter<0) counter = 0;
+	
+	
+	
+	// show link state  (debug output)
+	if (counter>=10 || counter<0)
+    {
+	    showLinks();
+	    counter = 0;
+    }
+	else
+	{
+	    counter++;
+	}
 }
 
@@ -230,8 +268,8 @@
 
 		int i=0;
-		BOOST_FOREACH( LinkDescriptor* ld, links ) {
-			if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID) continue;
+		foreach( LinkDescriptor* ld, links ) {
+			if (!isLinkVital(ld) || ld->service != OverlayInterface::OVERLAY_SERVICE_ID) continue;
 			bool found = false;
-			BOOST_FOREACH(NodeID& id, nodes)
+			foreach(NodeID& id, nodes)
 			if (id  == ld->remoteNode) found = true;
 			if (found) continue;
@@ -261,8 +299,15 @@
 	int i=0;
 	logging_info("--- link state -------------------------------");
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
+	foreach( LinkDescriptor* ld, links ) {
 		string epd = "";
-		if (ld->isDirectVital())
-			epd = getEndpointDescriptor(ld->remoteNode).toString();
+		if (isLinkDirectVital(ld))
+		{
+//			epd = getEndpointDescriptor(ld->remoteNode).toString();
+		    
+		    epd = "Connection: ";
+		    epd += bc->get_local_endpoint_of_link(ld->communicationId)->to_string();
+		    epd += " <---> ";
+		    epd += bc->get_remote_endpoint_of_link(ld->communicationId)->to_string();
+		}
 
 		logging_info("LINK_STATE: " << i << ": " << ld << " " << epd);
@@ -289,11 +334,38 @@
 // internal message delivery ---------------------------------------------------
 
+
+seqnum_t BaseOverlay::send_overlaymessage_down( OverlayMsg* message, const LinkID& bc_link, uint8_t priority )
+{
+    // set priority
+    message->setPriority(priority);
+    
+    // wrap old OverlayMsg into reboost message
+    reboost::message_t wrapped_message = message->wrap_up_for_sending();
+    
+    // send down to BaseCommunication
+    try
+    {
+        // * send *
+        return bc->sendMessage(bc_link, wrapped_message, priority, false);
+    }
+    catch ( communication::communication_message_not_sent& e )
+    {
+        ostringstream out;
+        out << "Communication message not sent: " << e.what();
+        throw message_not_sent(out.str());
+    }
+    
+    throw logic_error("This should never happen!");
+}
+
+
 /// routes a message to its destination node
-void BaseOverlay::route( OverlayMsg* message ) {
-
+void BaseOverlay::route( OverlayMsg* message, const NodeID& last_hop )
+{
 	// exceeded time-to-live? yes-> drop message
-	if (message->getNumHops() > message->getTimeToLive()) {
-		logging_warn("Message exceeded TTL. Dropping message and relay routes"
-				"for recovery.");
+	if (message->getNumHops() > message->getTimeToLive())
+	{
+		logging_warn("Message exceeded TTL. Dropping message and relay routes "
+            << "for recovery. Hop count: " << (int) message->getNumHops());
 		removeRelayNode(message->getDestinationNode());
 		return;
@@ -301,132 +373,279 @@
 
 	// no-> forward message
-	else {
+	else
+	{
 		// destinastion myself? yes-> handle message
-		if (message->getDestinationNode() == nodeId) {
-			logging_warn("Usually I should not route messages to myself!");
-			Message msg;
-			msg.encapsulate(message);
-			handleMessage( &msg, NULL );
-		} else {
-			// no->send message to next hop
-			send( message, message->getDestinationNode() );
-		}
-	}
+		if (message->getDestinationNode() == nodeId)
+		{
+			logging_warn("Usually I should not route messages to myself. And I won't!");
+		}
+
+		// no->send message to next hop
+		else
+		{
+		    try
+		    {
+                /* (deep) packet inspection to determine priority */
+                // BRANCH: typeData  -->  send with low priority
+                if ( message->getType() == OverlayMsg::typeData )
+                {
+                    // TODO think about implementing explicit routing queue (with active queue management??)
+                    send( message,
+                          message->getDestinationNode(),
+                          message->getPriority(),
+                          last_hop );
+                }
+                // BRANCH: internal message  -->  send with higher priority
+                else
+                {
+                    send( message,
+                          message->getDestinationNode(),
+                          system_priority::HIGH,
+                          last_hop );
+                }
+		    }
+		    catch ( message_not_sent& e )
+		    {
+		        logging_warn("Unable to route message of type "
+		                << message->getType()
+		                << " to "
+		                << message->getDestinationNode()
+		                << ". Reason: "
+		                << e.what());
+		        
+		        // inform sender
+                if ( message->getType() != OverlayMsg::typeMessageLost )
+                {
+                    report_lost_message(message);
+                }
+		    }
+		}
+	}
+}
+
+void BaseOverlay::report_lost_message( const OverlayMsg* message )
+{
+    OverlayMsg reply(OverlayMsg::typeMessageLost);
+    reply.setSeqNum(message->getSeqNum());
+    
+    /**
+     * MessageLost-Message
+     * 
+     * - Type of lost message
+     * - Hop count of lost message
+     * - Source-LinkID  of lost message
+     */
+    reboost::shared_buffer_t b(sizeof(uint8_t)*2);
+    b.mutable_data()[0] = message->getType();
+    b.mutable_data()[1] = message->getNumHops();
+    reply.append_buffer(b);
+    reply.append_buffer(message->getSourceLink().serialize());
+    
+    try
+    {
+        send_node(&reply, message->getSourceNode(),
+                system_priority::OVERLAY,
+                OverlayInterface::OVERLAY_SERVICE_ID);
+    }
+    catch ( message_not_sent& e )
+    {
+        logging_warn("Tried to inform another node that we could'n route their message. But we were not able to send this error-message, too.");
+    }
 }
 
 /// sends a message to another node, delivers it to the base overlay class
-seqnum_t BaseOverlay::send( OverlayMsg* message, const NodeID& destination ) {
+seqnum_t BaseOverlay::send( OverlayMsg* message,
+        const NodeID& destination,
+        uint8_t priority,
+        const NodeID& last_hop ) throw(message_not_sent)
+{
 	LinkDescriptor* next_link = NULL;
 
 	// drop messages to unspecified destinations
-	if (destination.isUnspecified()) return -1;
-
-	// send messages to myself -> handle message and drop warning!
-	if (destination == nodeId) {
-		logging_warn("Sent message to myself. Handling message.")
-		Message msg;
-		msg.encapsulate(message);
-		handleMessage( &msg, NULL );
-		return -1;
+	if (destination.isUnspecified())
+	    throw message_not_sent("No destination specified. Drop!");
+
+	// send messages to myself -> drop!
+    // TODO maybe this is not what we want. why not just deliver this message?
+    //   There is a similar check in the route function, there it should be okay.
+	if (destination == nodeId)
+	{
+	    logging_warn("Sent message to myself. Drop!");
+	    
+	    throw message_not_sent("Sent message to myself. Drop!");
 	}
 
 	// use relay path?
-	if (message->isRelayed()) {
+	if (message->isRelayed())
+	{
 		next_link = getRelayLinkTo( destination );
-		if (next_link != NULL) {
+		
+		if (next_link != NULL)
+		{
 			next_link->setRelaying();
-			return bc->sendMessage(next_link->communicationId, message);
-		} else {
-			logging_warn("Could not send message. No relay hop found to "
-					<< destination << " -- trying to route over overlay paths ...")
-//			logging_error("ERROR: " << debugInformation() );
-		//			return -1;
-		}
-	}
-
+
+			// * send message over relayed link *
+			return send_overlaymessage_down(message, next_link->communicationId, priority);
+		}
+		else
+		{
+			logging_warn("No relay hop found to " << destination
+			        << " -- trying to route over overlay paths ...")
+		}
+	}
+
+	
 	// last resort -> route over overlay path
 	LinkID next_id = overlayInterface->getNextLinkId( destination );
-	if (next_id.isUnspecified()) {
-		logging_warn("Could not send message. No next hop found to " <<
-				destination );
-		logging_error("ERROR: " << debugInformation() );
-		return -1;
-	}
-
-	// get link descriptor, up and running? yes-> send message
+	if ( next_id.isUnspecified() )
+	{		
+        // apperently we're the closest node --> try second best node
+        //   NOTE: This is helpful if our routing table is not up-to-date, but 
+        //   may lead to circles. So we have to be careful.
+        std::vector<const LinkID*> next_ids = 
+            overlayInterface->getSortedLinkIdsTowardsNode( destination );
+            
+        for ( int i = 0; i < next_ids.size(); i++ )
+        {
+            const LinkID& link = *next_ids[i];
+            
+            if ( ! link.isUnspecified() )
+            {
+                next_id = link;
+                
+                break;
+            }
+        }
+     
+        // still no next hop found. drop.
+        if ( next_id.isUnspecified() )
+        {
+            logging_warn("Could not send message. No next hop found to " <<
+                destination );
+            logging_error("ERROR: " << debugInformation() );
+            
+            throw message_not_sent("No next hop found.");
+        }
+	}
+
+	
+	/* get link descriptor, do some checks and send message */
 	next_link = getDescriptor(next_id);
-	if (next_link != NULL && next_link->up) {
-		// send message over relayed link
-		return send(message, next_link);
-	}
-
-	// no-> error, dropping message
-	else {
-		logging_warn("Could not send message. Link not known or up");
-		logging_error("ERROR: " << debugInformation() );
-		return -1;
-	}
-
-	// not reached-> fail
-	return -1;
-}
+    
+    // check pointer
+    if ( next_link == NULL )
+    {
+        // NOTE: this shuldn't happen
+        throw message_not_sent("Could not send message. Link not known.");
+    }
+    
+    // avoid circles
+    if ( next_link->remoteNode == last_hop )
+    {
+        // XXX logging_debug
+        logging_info("Possible next hop would create a circle: "
+            << next_link->remoteNode);
+        
+        throw message_not_sent("Could not send message. Possible next hop would create a circle.");
+    }
+    
+    // check if link is up
+	if ( ! next_link->up)
+	{
+        logging_warn("Could not send message. Link not up");
+        logging_error("ERROR: " << debugInformation() );
+        
+        throw message_not_sent("Could not send message. Link not up");
+	}
+
+	// * send message over overlay link *
+	return send(message, next_link, priority);
+}
+
 
 /// send a message using a link descriptor, delivers it to the base overlay class
-seqnum_t BaseOverlay::send( OverlayMsg* message, LinkDescriptor* ldr, bool ignore_down ) {
+seqnum_t BaseOverlay::send( OverlayMsg* message,
+        LinkDescriptor* ldr,
+        uint8_t priority ) throw(message_not_sent)
+{
 	// check if null
-	if (ldr == NULL) {
-		logging_error("Can not send message to " << message->getDestinationAddress());
-		return -1;
+	if (ldr == NULL)
+	{
+        ostringstream out;
+        out << "Can not send message to " << message->getDestinationAddress();
+        throw message_not_sent(out.str());
 	}
 
 	// check if up
-	if (!ldr->up && !ignore_down) {
-		logging_error("Can not send message. Link not up:" << ldr );
+	if ( !ldr->up )
+	{
 		logging_error("DEBUG_INFO: " << debugInformation() );
-		return -1;
-	}
-	LinkDescriptor* ld = NULL;
-
-	// handle relayed link
-	if (ldr->relayed) {
+
+        ostringstream out;
+        out << "Can not send message. Link not up:" << ldr->to_string();
+        throw message_not_sent(out.str());
+	}
+	
+	LinkDescriptor* next_hop_ld = NULL;
+
+	// BRANCH: relayed link
+	if (ldr->relayed)
+	{
 		logging_debug("Resolving direct link for relayed link to "
 				<< ldr->remoteNode);
-		ld = getRelayLinkTo( ldr->remoteNode );
-		if (ld==NULL) {
-			logging_error("No relay path found to link " << ldr );
+		
+		next_hop_ld = getRelayLinkTo( ldr->remoteNode );
+		
+		if (next_hop_ld==NULL)
+		{
 			logging_error("DEBUG_INFO: " << debugInformation() );
-			return -1;
-		}
-		ld->setRelaying();
+			
+	        ostringstream out;
+	        out << "No relay path found to link: " << ldr;
+	        throw message_not_sent(out.str());
+		}
+		
+		next_hop_ld->setRelaying();
 		message->setRelayed(true);
-	} else
-		ld = ldr;
-
-	// handle direct link
-	if (ld->communicationUp) {
-		logging_debug("send(): Sending message over direct link.");
-		return bc->sendMessage( ld->communicationId, message );
-	} else {
-		logging_error("send(): Could not send message. "
-				"Not a relayed link and direct link is not up.");
-		return -1;
-	}
-	return -1;
+	}
+	// BRANCH: direct link
+	else
+	{
+		next_hop_ld = ldr;
+	}
+
+	
+	// check next hop-link
+	if ( ! next_hop_ld->communicationUp)
+	{
+	    throw message_not_sent( "send(): Could not send message."
+	            " Not a relayed link and direct link is not up." );
+	}
+
+	// send over next link
+    logging_debug("send(): Sending message over direct link.");
+    return send_overlaymessage_down(message, next_hop_ld->communicationId, priority);
+
 }
 
 seqnum_t BaseOverlay::send_node( OverlayMsg* message, const NodeID& remote,
-		const ServiceID& service) {
+        uint8_t priority, const ServiceID& service) throw(message_not_sent)
+{
 	message->setSourceNode(nodeId);
 	message->setDestinationNode(remote);
 	message->setService(service);
-	return send( message, remote );
-}
-
-seqnum_t BaseOverlay::send_link( OverlayMsg* message, const LinkID& link,bool ignore_down ) {
+	return send( message, remote, priority );
+}
+
+void BaseOverlay::send_link( OverlayMsg* message,
+        const LinkID& link,
+        uint8_t priority ) throw(message_not_sent)
+{
 	LinkDescriptor* ld = getDescriptor(link);
-	if (ld==NULL) {
-		logging_error("Cannot find descriptor to link id=" << link.toString());
-		return -1;
-	}
+	if (ld==NULL)
+	{
+	    throw message_not_sent("Cannot find descriptor to link id=" + link.toString());
+	}
+	
 	message->setSourceNode(nodeId);
 	message->setDestinationNode(ld->remoteNode);
@@ -437,5 +656,17 @@
 	message->setService(ld->service);
 	message->setRelayed(ld->relayed);
-	return send( message, ld, ignore_down );
+    
+    
+    try
+    {
+        // * send message *
+        send( message, ld, priority );
+    }
+    catch ( message_not_sent& e )
+    {
+        // drop failed link
+        ld->failed = true;
+        dropLink(ld->overlayId);
+    }
 }
 
@@ -451,6 +682,7 @@
 		// relay link still used and alive?
 		if (ld==NULL
-				|| !ld->isDirectVital()
-				|| difftime(route.used, time(NULL)) > 8) {
+				|| !isLinkDirectVital(ld)
+				|| difftime(route.used, time(NULL)) > KEEP_ALIVE_TIME_OUT)  // TODO this was set to 8 before.. Is the new timeout better?
+		{
 			logging_info("Forgetting relay information to node "
 					<< route.node.toString() );
@@ -488,5 +720,5 @@
 	if (message->isRelayed()) {
 		// try to find source node
-		BOOST_FOREACH( relay_route& route, relay_routes ) {
+		foreach( relay_route& route, relay_routes ) {
 			// relay route found? yes->
 			if ( route.node == message->getDestinationNode() ) {
@@ -504,5 +736,5 @@
 
 		// try to find source node
-		BOOST_FOREACH( relay_route& route, relay_routes ) {
+		foreach( relay_route& route, relay_routes ) {
 
 			// relay route found? yes->
@@ -516,8 +748,8 @@
 				if (route.hops > message->getNumHops()
 						|| rld == NULL
-						|| !rld->isDirectVital()) {
+						|| !isLinkDirectVital(ld)) {
 					logging_info("Updating relay information to node "
 							<< route.node.toString()
-							<< " reducing to " << message->getNumHops() << " hops.");
+							<< " reducing to " << (int) message->getNumHops() << " hops.");
 					route.hops = message->getNumHops();
 					route.link = ld->overlayId;
@@ -542,8 +774,8 @@
 LinkDescriptor* BaseOverlay::getRelayLinkTo( const NodeID& remote ) {
 	// try to find source node
-	BOOST_FOREACH( relay_route& route, relay_routes ) {
+	foreach( relay_route& route, relay_routes ) {
 		if (route.node == remote ) {
 			LinkDescriptor* ld = getDescriptor( route.link );
-			if (ld==NULL || !ld->isDirectVital()) return NULL; else {
+			if (ld==NULL || !isLinkDirectVital(ld)) return NULL; else {
 				route.used = time(NULL);
 				return ld;
@@ -575,9 +807,9 @@
 // ----------------------------------------------------------------------------
 
-void BaseOverlay::start( BaseCommunication& _basecomm, const NodeID& _nodeid ) {
+void BaseOverlay::start( BaseCommunication* _basecomm, const NodeID& _nodeid ) {
 	logging_info("Starting...");
 
 	// set parameters
-	bc = &_basecomm;
+	bc = _basecomm;
 	nodeId = _nodeid;
 
@@ -587,5 +819,6 @@
 
 	// timer for auto link management
-	Timer::setInterval( 1000 );
+	Timer::setInterval( 1000 ); // XXX
+//	Timer::setInterval( 10000 );
 	Timer::start();
 
@@ -641,5 +874,5 @@
 		overlayInterface->joinOverlay();
 		state = BaseOverlayStateCompleted;
-		BOOST_FOREACH( NodeListener* i, nodeListeners )
+		foreach( NodeListener* i, nodeListeners )
 			i->onJoinCompleted( spovnetId );
 
@@ -682,5 +915,6 @@
 	// gather all service links
 	vector<LinkID> servicelinks;
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
+	foreach( LinkDescriptor* ld, links )
+	{
 		if( ld->service != OverlayInterface::OVERLAY_SERVICE_ID )
 			servicelinks.push_back( ld->overlayId );
@@ -688,15 +922,23 @@
 
 	// drop all service links
-	BOOST_FOREACH( LinkID lnk, servicelinks )
-	dropLink( lnk );
+	foreach( LinkID lnk, servicelinks )
+	{
+	    logging_debug("Dropping service link " << lnk.toString());
+	    dropLink( lnk );
+	}
 
 	// let the node leave the spovnet overlay interface
 	logging_debug( "Leaving overlay" );
 	if( overlayInterface != NULL )
+	{
 		overlayInterface->leaveOverlay();
+	}
 
 	// drop still open bootstrap links
-	BOOST_FOREACH( LinkID lnk, bootstrapLinks )
-	bc->dropLink( lnk );
+	foreach( LinkID lnk, bootstrapLinks )
+	{
+	    logging_debug("Dropping bootstrap link " << lnk.toString());
+	    bc->dropLink( lnk );
+	}
 
 	// change to inalid state
@@ -708,5 +950,6 @@
 
 	// inform all registered services of the event
-	BOOST_FOREACH( NodeListener* i, nodeListeners ) {
+	foreach( NodeListener* i, nodeListeners )
+	{
 		if( ret ) i->onLeaveCompleted( spovnetId );
 		else i->onLeaveFailed( spovnetId );
@@ -731,5 +974,5 @@
 		state = BaseOverlayStateInvalid;
 
-		BOOST_FOREACH( NodeListener* i, nodeListeners )
+		foreach( NodeListener* i, nodeListeners )
 		i->onJoinFailed( spovnetId );
 
@@ -783,7 +1026,11 @@
 		const ServiceID& service ) {
 
+    // TODO What if we already have a Link to this node and this service id?
+    
 	// do not establish a link to myself!
-	if (remote == nodeId) return LinkID::UNSPECIFIED;
-
+	if (remote == nodeId) return 
+	        LinkID::UNSPECIFIED;
+
+	
 	// create a link descriptor
 	LinkDescriptor* ld = addDescriptor();
@@ -792,4 +1039,8 @@
 	ld->service = service;
 	ld->listener = getListener(ld->service);
+    
+    // initialize sequence numbers
+    ld->last_sent_seqnum = SequenceNumber::createRandomSeqNum_Short();
+    logging_debug("Creating new link with initial SeqNum: " << ld->last_sent_seqnum);
 
 	// create link request message
@@ -800,4 +1051,7 @@
 	msg.setRelayed(true);
 	msg.setRegisterRelay(true);
+//	msg.setRouteRecord(true);
+    
+    msg.setSeqNum(ld->last_sent_seqnum);
 
 	// debug message
@@ -809,17 +1063,71 @@
 	);
 
+	
 	// sending message to node
-	send_node( &msg, ld->remoteNode, ld->service );
-
+	try
+	{
+	    // * send *
+	    seqnum_t seq = send_node( &msg, ld->remoteNode, system_priority::OVERLAY, ld->service );
+	}
+	catch ( message_not_sent& e )
+	{
+	    logging_warn("Link request not sent: " << e.what());
+	    
+	    // Message not sent. Cancel link request.
+	    SystemQueue::instance().scheduleCall(
+	            boost::bind(
+	                    &BaseOverlay::__onLinkEstablishmentFailed,
+	                    this,
+	                    ld->overlayId)
+	        );
+	}
+	
 	return ld->overlayId;
 }
 
+/// NOTE: "id" is an Overlay-LinkID
+void BaseOverlay::__onLinkEstablishmentFailed(const LinkID& id)
+{
+    // TODO This code redundant. But also it's not easy to aggregate in one function.
+    
+    // get descriptor for link
+    LinkDescriptor* ld = getDescriptor(id, false);
+    if ( ld == NULL ) return; // not found? ->ignore!
+
+    logging_debug( "__onLinkEstablishmentFaild: " << ld );
+
+    // removing relay link information
+    removeRelayLink(ld->overlayId);
+
+    // inform listeners about link down
+    ld->communicationUp = false;
+    if (!ld->service.isUnspecified())
+    {
+        CommunicationListener* lst = getListener(ld->service);
+        if(lst != NULL) lst->onLinkFail( ld->overlayId, ld->remoteNode );
+        sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
+    }
+
+    // delete all queued messages (auto links)
+    if( ld->messageQueue.size() > 0 ) {
+        logging_warn( "Dropping link " << id.toString() << " that has "
+                << ld->messageQueue.size() << " waiting messages" );
+        ld->flushQueue();
+    }
+
+    // erase mapping
+    eraseDescriptor(ld->overlayId);
+}
+
+
 /// drops an established link
-void BaseOverlay::dropLink(const LinkID& link) {
-	logging_info( "Dropping link (initiated locally):" << link.toString() );
+void BaseOverlay::dropLink(const LinkID& link)
+{
+	logging_info( "Dropping link: " << link.toString() );
 
 	// find the link item to drop
 	LinkDescriptor* ld = getDescriptor(link);
-	if( ld == NULL ) {
+	if( ld == NULL )
+	{
 		logging_warn( "Can't drop link, link is unknown!");
 		return;
@@ -827,25 +1135,73 @@
 
 	// delete all queued messages
-	if( ld->messageQueue.size() > 0 ) {
+	if( ld->messageQueue.size() > 0 )
+	{
 		logging_warn( "Dropping link " << ld->overlayId.toString() << " that has "
 				<< ld->messageQueue.size() << " waiting messages" );
 		ld->flushQueue();
 	}
-
-	// inform sideport and listener
-	if(ld->listener != NULL)
-		ld->listener->onLinkDown( ld->overlayId, ld->remoteNode );
-	sideport->onLinkDown(ld->overlayId, this->nodeId, ld->remoteNode, this->spovnetId );
-
-	// do not drop relay links
-	if (!ld->relaying) {
-		// drop the link in base communication
-		if (ld->communicationUp) bc->dropLink( ld->communicationId );
-
-		// erase descriptor
-		eraseDescriptor( ld->overlayId );
-	} else {
-		ld->dropAfterRelaying = true;
-	}
+	
+	    
+	// inform application and remote note (but only once)
+	//   NOTE: If we initiated the drop, this function is called twice, but on 
+	//   the second call, there is noting to do.
+	if ( ld->up && ! ld->failed )
+	{
+        // inform sideport and listener
+        if(ld->listener != NULL)
+        {
+            ld->listener->onLinkDown( ld->overlayId, ld->remoteNode );
+        }
+        sideport->onLinkDown(ld->overlayId, this->nodeId, ld->remoteNode, this->spovnetId );
+	
+        // send link-close to remote node
+        logging_info("Sending LinkClose message to remote node.");
+        OverlayMsg close_msg(OverlayMsg::typeLinkClose);
+        send_link(&close_msg, link, system_priority::OVERLAY);
+    
+        // deactivate link
+        ld->up = false;
+//         ld->closing = true;
+	}
+	
+	else if ( ld->failed )
+    {
+        // inform listener
+        if( ld->listener != NULL )
+        {
+            ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
+        }
+        
+        ld->up = false;
+        __removeDroppedLink(ld->overlayId);
+    }
+}
+
+/// called from typeLinkClose-handler
+void BaseOverlay::__removeDroppedLink(const LinkID& link)
+{
+    // find the link item to drop
+    LinkDescriptor* ld = getDescriptor(link);
+    if( ld == NULL )
+    {
+        return;
+    }
+
+    // do not drop relay links
+    if (!ld->relaying)
+    {
+        // drop the link in base communication
+        if (ld->communicationUp)
+        {
+            bc->dropLink( ld->communicationId );
+        }
+
+        // erase descriptor
+        eraseDescriptor( ld->overlayId );
+    }
+    else
+    {
+        ld->dropAfterRelaying = true;
+    }
 }
 
@@ -853,40 +1209,86 @@
 
 /// internal send message, always use this functions to send messages over links
-seqnum_t BaseOverlay::sendMessage( const Message* message, const LinkID& link ) {
+const SequenceNumber& BaseOverlay::sendMessage( reboost::message_t message,
+        const LinkID& link,
+        uint8_t priority ) throw(message_not_sent)
+{
 	logging_debug( "Sending data message on link " << link.toString() );
 
 	// get the mapping for this link
 	LinkDescriptor* ld = getDescriptor(link);
-	if( ld == NULL ) {
-		logging_error("Could not send message. "
-				<< "Link not found id=" << link.toString());
-		return -1;
+	if( ld == NULL )
+	{
+	    throw message_not_sent("Could not send message. Link not found id=" + link.toString());
 	}
 
 	// check if the link is up yet, if its an auto link queue message
-	if( !ld->up ) {
+	if( !ld->up )
+	{
 		ld->setAutoUsed();
-		if( ld->autolink ) {
+		if( ld->autolink )
+		{
 			logging_info("Auto-link " << link.toString() << " not up, queue message");
-			Data data = data_serialize( message );
-			const_cast<Message*>(message)->dropPayload();
-			ld->messageQueue.push_back( new Message(data) );
-		} else {
-			logging_error("Link " << link.toString() << " not up, drop message");
-		}
-		return -1;
-	}
-
-	// compile overlay message (has service and node id)
-	OverlayMsg overmsg( OverlayMsg::typeData );
-	overmsg.encapsulate( const_cast<Message*>(message) );
-
-	// send message over relay/direct/overlay
-	return send_link( &overmsg, ld->overlayId );
-}
-
-
-seqnum_t BaseOverlay::sendMessage(const Message* message,
-		const NodeID& node, const ServiceID& service) {
+			
+			// queue message
+	        LinkDescriptor::message_queue_entry msg;
+	        msg.message = message;
+	        msg.priority = priority;
+
+			ld->messageQueue.push_back( msg );
+			
+			return SequenceNumber::DISABLED;  // TODO what to return if message is queued?
+		}
+		else
+		{
+		    throw message_not_sent("Link " + link.toString() + " not up, drop message");
+		}
+	}
+	
+	// TODO AKTUELL: sequence numbers
+	// TODO seqnum on fast path ?
+	ld->last_sent_seqnum.increment();
+	
+	/* choose fast-path for direct links; normal overlay-path otherwise */
+	// BRANCH: direct link
+	if ( ld->communicationUp && !ld->relayed )
+	{
+	    // * send down to BaseCommunication *
+	    try
+	    {
+	        bc->sendMessage(ld->communicationId, message, priority, true);
+        }
+        catch ( communication::communication_message_not_sent& e )
+        {
+            ostringstream out;
+            out << "Communication message on fast-path not sent: " << e.what();
+            throw message_not_sent(out.str());
+        }
+	}
+
+	// BRANCH: use (slow) overlay-path
+	else
+	{
+        // compile overlay message (has service and node id)
+        OverlayMsg overmsg( OverlayMsg::typeData );
+        overmsg.set_payload_message(message);
+        
+        // set SeqNum
+        if ( ld->transmit_seqnums )
+        {
+            overmsg.setSeqNum(ld->last_sent_seqnum);
+        }
+        logging_debug("Sending Message with SeqNum: " << overmsg.getSeqNum());
+    
+        // send message over relay/direct/overlay
+        send_link( &overmsg, ld->overlayId, priority );
+	}
+	
+	// return seqnum
+ 	return ld->last_sent_seqnum;
+}
+
+
+const SequenceNumber& BaseOverlay::sendMessage(reboost::message_t message,
+		const NodeID& node, uint8_t priority, const ServiceID& service) {
 
 	// find link for node and service
@@ -907,5 +1309,5 @@
 		if( ld == NULL ) {
 			logging_error( "Failed to establish auto-link.");
-			return -1;
+            throw message_not_sent("Failed to establish auto-link.");
 		}
 		ld->autolink = true;
@@ -920,10 +1322,10 @@
 
 	// send / queue message
-	return sendMessage( message, ld->overlayId );
-}
-
-
-NodeID BaseOverlay::sendMessageCloserToNodeID(const Message* message,
-        const NodeID& address, const ServiceID& service) {
+	return sendMessage( message, ld->overlayId, priority );
+}
+
+
+NodeID BaseOverlay::sendMessageCloserToNodeID(reboost::message_t message,
+        const NodeID& address, uint8_t priority, const ServiceID& service) {
     
     if ( overlayInterface->isClosestNodeTo(address) )
@@ -936,8 +1338,8 @@
     if ( closest_node != NodeID::UNSPECIFIED )
     {
-        seqnum_t seqnum = sendMessage(message, closest_node, service);
+        sendMessage(message, closest_node, priority, service);
     }
     
-    return closest_node;  // XXX return seqnum ?? tuple? closest_node via (non const) reference?
+    return closest_node;  // return seqnum ?? tuple? closest_node via (non const) reference?
 }
 // ----------------------------------------------------------------------------
@@ -978,5 +1380,5 @@
 
 	// see if we can find the node in our own table
-	BOOST_FOREACH(const LinkDescriptor* ld, links){
+	foreach(const LinkDescriptor* ld, links){
 		if(ld->remoteNode != node) continue;
 		if(!ld->communicationUp) continue;
@@ -1079,5 +1481,6 @@
 
 void BaseOverlay::onLinkUp(const LinkID& id,
-		const address_v* local, const address_v* remote) {
+        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote)
+{
 	logging_debug( "Link up with base communication link id=" << id );
 
@@ -1085,8 +1488,9 @@
 	LinkDescriptor* ld = getDescriptor(id, true);
 
-	// handle bootstrap link we initiated
+	// BRANCH: handle bootstrap link we initiated
 	if( std::find(bootstrapLinks.begin(), bootstrapLinks.end(), id) != bootstrapLinks.end() ){
 		logging_info(
 				"Join has been initiated by me and the link is now up. " <<
+				"LinkID: " << id.toString() <<
 				"Sending out join request for SpoVNet " << spovnetId.toString()
 		);
@@ -1096,10 +1500,12 @@
 				OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
 		JoinRequest joinRequest( spovnetId, nodeId );
-		overlayMsg.encapsulate( &joinRequest );
-		bc->sendMessage( id, &overlayMsg );
+		overlayMsg.append_buffer(joinRequest.serialize_into_shared_buffer());
+
+		send_overlaymessage_down(&overlayMsg, id, system_priority::OVERLAY);
+		
 		return;
 	}
 
-	// no link found? -> link establishment from remote, add one!
+	// BRANCH: link establishment from remote, add one!
 	if (ld == NULL) {
 		ld = addDescriptor( id );
@@ -1115,7 +1521,9 @@
 		// in this case, do not inform listener, since service it unknown
 		// -> wait for update message!
-
-		// link mapping found? -> send update message with node-id and service id
-	} else {
+	}
+	
+	// BRANCH: We requested this link in the first place
+	else
+	{
 		logging_info( "onLinkUp descriptor (initiated locally):" << ld );
 
@@ -1126,14 +1534,34 @@
 		ld->fromRemote = false;
 
-		// if link is a relayed link->convert to direct link
-		if (ld->relayed) {
-			logging_info( "Converting to direct link: " << ld );
+		// BRANCH: this was a relayed link before --> convert to direct link
+		//   TODO do we really have to send a message here?
+		if (ld->relayed)
+		{
 			ld->up = true;
 			ld->relayed = false;
+			logging_info( "Converting to direct link: " << ld );
+			
+			// send message
 			OverlayMsg overMsg( OverlayMsg::typeLinkDirect );
 			overMsg.setSourceLink( ld->overlayId );
 			overMsg.setDestinationLink( ld->remoteLink );
-			send_link( &overMsg, ld->overlayId );
-		} else {
+			send_link( &overMsg, ld->overlayId, system_priority::OVERLAY );
+			
+		    // inform listener
+		    if( ld->listener != NULL)
+		        ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
+		}
+		
+
+        /* NOTE: Chord is opening direct-links in it's setup routine which are
+         *   neither set to "relayed" nor to "up". To activate these links a
+         *   typeLinkUpdate must be sent.
+         *   
+         * This branch is would also be taken when we had a working link before 
+         *   (ld->up == true). I'm not sure if this case does actually happen 
+         *   and whether it's tested.
+         */
+		else
+		{
 			// note: necessary to validate the link on the remote side!
 			logging_info( "Sending out update" <<
@@ -1144,7 +1572,15 @@
 			// compile and send update message
 			OverlayMsg overlayMsg( OverlayMsg::typeLinkUpdate );
-			overlayMsg.setSourceLink(ld->overlayId);
 			overlayMsg.setAutoLink( ld->autolink );
-			send_link( &overlayMsg, ld->overlayId, true );
+		    overlayMsg.setSourceNode(nodeId);
+		    overlayMsg.setDestinationNode(ld->remoteNode);
+		    overlayMsg.setSourceLink(ld->overlayId);
+		    overlayMsg.setDestinationLink(ld->remoteLink);
+		    overlayMsg.setService(ld->service);
+		    overlayMsg.setRelayed(false);
+
+		    // TODO ld->communicationId = id ??
+		    
+		    send_overlaymessage_down(&overlayMsg, id, system_priority::OVERLAY);
 		}
 	}
@@ -1152,6 +1588,7 @@
 
 void BaseOverlay::onLinkDown(const LinkID& id,
-		const address_v* local, const address_v* remote) {
-
+        const addressing2::EndpointPtr local,
+        const addressing2::EndpointPtr remote)
+{
 	// erase bootstrap links
 	vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
@@ -1185,61 +1622,111 @@
 }
 
+
+void BaseOverlay::onLinkFail(const LinkID& id,
+        const addressing2::EndpointPtr local,
+        const addressing2::EndpointPtr remote)
+{
+	logging_debug( "Link fail with base communication link id=" << id );
+
+//	// erase bootstrap links
+//	vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
+//	if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
+//
+//	// get descriptor for link
+//	LinkDescriptor* ld = getDescriptor(id, true);
+//	if ( ld == NULL ) return; // not found? ->ignore!
+//	logging_debug( "Link failed id=" << ld->overlayId.toString() );
+//
+//	// inform listeners
+//	ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
+//	sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
+	
+	logging_debug( "  ... calling onLinkDown ..." );
+	onLinkDown(id, local, remote);
+}
+
+
 void BaseOverlay::onLinkChanged(const LinkID& id,
-		const address_v* oldlocal, const address_v* newlocal,
-		const address_v* oldremote, const address_v* newremote) {
-
-	// get descriptor for link
-	LinkDescriptor* ld = getDescriptor(id, true);
-	if ( ld == NULL ) return; // not found? ->ignore!
-	logging_debug( "onLinkChanged descriptor: " << ld );
-
-	// inform listeners
-	ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
-	sideport->onLinkChanged( id, this->nodeId, ld->remoteNode, this->spovnetId );
-
-	// autolinks: refresh timestamp
-	ld->setAutoUsed();
-}
-
-void BaseOverlay::onLinkFail(const LinkID& id,
-		const address_v* local, const address_v* remote) {
-	logging_debug( "Link fail with base communication link id=" << id );
-
-	// erase bootstrap links
-	vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
-	if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
-
-	// get descriptor for link
-	LinkDescriptor* ld = getDescriptor(id, true);
-	if ( ld == NULL ) return; // not found? ->ignore!
-	logging_debug( "Link failed id=" << ld->overlayId.toString() );
-
-	// inform listeners
-	ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
-	sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
-}
-
-void BaseOverlay::onLinkQoSChanged(const LinkID& id, const address_v* local,
-		const address_v* remote, const QoSParameterSet& qos) {
-	logging_debug( "Link quality changed with base communication link id=" << id );
-
-	// get descriptor for link
-	LinkDescriptor* ld = getDescriptor(id, true);
-	if ( ld == NULL ) return; // not found? ->ignore!
-	logging_debug( "Link quality changed id=" << ld->overlayId.toString() );
-}
-
-bool BaseOverlay::onLinkRequest( const LinkID& id, const address_v* local,
-		const address_v* remote ) {
+        const addressing2::EndpointPtr oldlocal,  const addressing2::EndpointPtr newlocal,
+        const addressing2::EndpointPtr oldremote, const addressing2::EndpointPtr newremote)
+{
+    // get descriptor for link
+    LinkDescriptor* ld = getDescriptor(id, true);
+    if ( ld == NULL ) return; // not found? ->ignore!
+    logging_debug( "onLinkChanged descriptor: " << ld );
+
+    // inform listeners
+    ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
+    sideport->onLinkChanged( id, this->nodeId, ld->remoteNode, this->spovnetId );
+
+    // autolinks: refresh timestamp
+    ld->setAutoUsed();
+}
+
+//void BaseOverlay::onLinkQoSChanged(const LinkID& id,
+//        const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote,
+//        const QoSParameterSet& qos)
+//{
+//	logging_debug( "Link quality changed with base communication link id=" << id );
+//
+//	// get descriptor for link
+//	LinkDescriptor* ld = getDescriptor(id, true);
+//	if ( ld == NULL ) return; // not found? ->ignore!
+//	logging_debug( "Link quality changed id=" << ld->overlayId.toString() );
+//}
+
+bool BaseOverlay::onLinkRequest(const LinkID& id,
+        const addressing2::EndpointPtr local,
+        const addressing2::EndpointPtr remote)
+{
 	logging_debug("Accepting link request from " << remote->to_string() );
+	
+	// TODO ask application..?
+	
 	return true;
 }
 
+
+
+
 /// handles a message from base communication
-bool BaseOverlay::receiveMessage(const Message* message,
-		const LinkID& link, const NodeID& ) {
+bool BaseOverlay::receiveMessage( reboost::shared_buffer_t message,
+		const LinkID& link,
+		const NodeID&,
+		bool bypass_overlay )
+{
 	// get descriptor for link
 	LinkDescriptor* ld = getDescriptor( link, true );
-	return handleMessage( message, ld, link );
+
+	
+	/* choose fastpath for direct links; normal overlay-path otherwise */	
+	if ( bypass_overlay && ld )
+	{
+        // message received --> link is alive
+        ld->keepAliveReceived = time(NULL);
+        // hop count on this link
+        ld->hops = 0;
+
+        
+        // hand over to CommunicationListener (aka Application) 
+	    CommunicationListener* lst = getListener(ld->service);
+	    if ( lst != NULL )
+	    {
+	        lst->onMessage(
+	                message,
+	                ld->remoteNode,
+	                ld->overlayId,
+                    SequenceNumber::DISABLED,
+	                NULL );
+	        
+	        return true;
+	    }
+
+	    return false;
+	}
+	else
+	{
+	    return handleMessage( message, ld, link );	    
+	}
 }
 
@@ -1247,17 +1734,19 @@
 
 /// Handle spovnet instance join requests
-bool BaseOverlay::handleJoinRequest( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
-
+bool BaseOverlay::handleJoinRequest( reboost::shared_buffer_t message, const NodeID& source, const LinkID& bcLink )
+{
 	// decapsulate message
-	JoinRequest* joinReq = overlayMsg->decapsulate<JoinRequest>();
+	JoinRequest joinReq;
+	joinReq.deserialize_from_shared_buffer(message);
+	
 	logging_info( "Received join request for spovnet " <<
-			joinReq->getSpoVNetID().toString() );
+			joinReq.getSpoVNetID().toString() );
 
 	// check spovnet id
-	if( joinReq->getSpoVNetID() != spovnetId ) {
+	if( joinReq.getSpoVNetID() != spovnetId ) {
 		logging_error(
 				"Received join request for spovnet we don't handle " <<
-				joinReq->getSpoVNetID().toString() );
-		delete joinReq;
+				joinReq.getSpoVNetID().toString() );
+
 		return false;
 	}
@@ -1267,7 +1756,7 @@
 	logging_info( "Sending join reply for spovnet " <<
 			spovnetId.toString() << " to node " <<
-			overlayMsg->getSourceNode().toString() <<
+			source.toString() <<
 			". Result: " << (allow ? "allowed" : "denied") );
-	joiningNodes.push_back( overlayMsg->getSourceNode() );
+	joiningNodes.push_back( source );
 
 	// return overlay parameters
@@ -1276,32 +1765,44 @@
 			<< getEndpointDescriptor().toString() )
 	OverlayParameterSet parameters = overlayInterface->getParameters();
+	
+	
+	// create JoinReplay Message
 	OverlayMsg retmsg( OverlayMsg::typeJoinReply,
 			OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
-	JoinReply replyMsg( spovnetId, parameters,
-			allow, getEndpointDescriptor() );
-	retmsg.encapsulate(&replyMsg);
-	bc->sendMessage( bcLink, &retmsg );
-
-	delete joinReq;
+	JoinReply replyMsg( spovnetId, parameters, allow );
+	retmsg.append_buffer(replyMsg.serialize_into_shared_buffer());
+
+	// XXX This is unlovely clash between the old message system and the new one,
+	// but a.t.m. we can't migrate everything to the new system at once..
+	// ---> Consider the EndpointDescriptor as part of the JoinReply..
+	retmsg.append_buffer(getEndpointDescriptor().serialize());
+	
+	// * send *
+	send_overlaymessage_down(&retmsg, bcLink, system_priority::OVERLAY);
+
 	return true;
 }
 
 /// Handle replies to spovnet instance join requests
-bool BaseOverlay::handleJoinReply( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
+bool BaseOverlay::handleJoinReply( reboost::shared_buffer_t message, const LinkID& bcLink )
+{
 	// decapsulate message
 	logging_debug("received join reply message");
-	JoinReply* replyMsg = overlayMsg->decapsulate<JoinReply>();
+	JoinReply replyMsg;
+	EndpointDescriptor endpoints;
+	reboost::shared_buffer_t buff = replyMsg.deserialize_from_shared_buffer(message);
+	buff = endpoints.deserialize(buff);
 
 	// correct spovnet?
-	if( replyMsg->getSpoVNetID() != spovnetId ) { // no-> fail
+	if( replyMsg.getSpoVNetID() != spovnetId ) { // no-> fail
 		logging_error( "Received SpoVNet join reply for " <<
-				replyMsg->getSpoVNetID().toString() <<
+				replyMsg.getSpoVNetID().toString() <<
 				" != " << spovnetId.toString() );
-		delete replyMsg;
+
 		return false;
 	}
 
 	// access granted? no -> fail
-	if( !replyMsg->getJoinAllowed() ) {
+	if( !replyMsg.getJoinAllowed() ) {
 		logging_error( "Our join request has been denied" );
 
@@ -1317,8 +1818,7 @@
 
 		// inform all registered services of the event
-		BOOST_FOREACH( NodeListener* i, nodeListeners )
+		foreach( NodeListener* i, nodeListeners )
 		i->onJoinFailed( spovnetId );
 
-		delete replyMsg;
 		return true;
 	}
@@ -1329,5 +1829,5 @@
 
 	logging_debug( "Using bootstrap end-point "
-			<< replyMsg->getBootstrapEndpoint().toString() );
+			<< endpoints.toString() );
 
 	// create overlay structure from spovnet parameter set
@@ -1338,5 +1838,5 @@
 
 		overlayInterface = OverlayFactory::create(
-				*this, replyMsg->getParam(), nodeId, this );
+				*this, replyMsg.getParam(), nodeId, this );
 
 		// overlay structure supported? no-> fail!
@@ -1354,8 +1854,7 @@
 
 			// inform all registered services of the event
-			BOOST_FOREACH( NodeListener* i, nodeListeners )
+			foreach( NodeListener* i, nodeListeners )
 			i->onJoinFailed( spovnetId );
 
-			delete replyMsg;
 			return true;
 		}
@@ -1365,6 +1864,6 @@
 		overlayInterface->createOverlay();
 
-		overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
-		overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
+		overlayInterface->joinOverlay( endpoints );
+		overlayBootstrap.recordJoin( endpoints );
 
 		// update ovlvis
@@ -1372,18 +1871,13 @@
 
 		// inform all registered services of the event
-		BOOST_FOREACH( NodeListener* i, nodeListeners )
-		i->onJoinCompleted( spovnetId );
-
-		delete replyMsg;
-
-	} else {
-
+		foreach( NodeListener* i, nodeListeners )
+		    i->onJoinCompleted( spovnetId );
+	}
+	else
+	{
 		// this is not the first bootstrap, just join the additional node
 		logging_debug("not first-time bootstrapping");
-		overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
-		overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
-
-		delete replyMsg;
-
+		overlayInterface->joinOverlay( endpoints );
+		overlayBootstrap.recordJoin( endpoints );
 	} // if( overlayInterface == NULL )
 
@@ -1392,7 +1886,9 @@
 
 
-bool BaseOverlay::handleData( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
+bool BaseOverlay::handleData( reboost::shared_buffer_t message, OverlayMsg* overlayMsg, LinkDescriptor* ld )
+{
 	// get service
-	const ServiceID& service = overlayMsg->getService();
+	const ServiceID& service = ld->service; //overlayMsg->getService();
+
 	logging_debug( "Received data for service " << service.toString()
 			<< " on link " << overlayMsg->getDestinationLink().toString() );
@@ -1402,7 +1898,11 @@
 	if(lst != NULL){
 		lst->onMessage(
-				overlayMsg,
-				overlayMsg->getSourceNode(),
-				overlayMsg->getDestinationLink()
+				message,
+//				overlayMsg->getSourceNode(),
+//				overlayMsg->getDestinationLink(),
+				ld->remoteNode,
+				ld->overlayId,
+                overlayMsg->getSeqNum(),
+				overlayMsg
 		);
 	}
@@ -1411,4 +1911,105 @@
 }
 
+bool BaseOverlay::handleLostMessage( reboost::shared_buffer_t message, OverlayMsg* msg )
+{
+    /**
+     * Deserialize MessageLost-Message
+     * 
+     * - Type of lost message
+     * - Hop count of lost message
+     * - Source-LinkID  of lost message
+     */
+    const uint8_t* buff = message(0, sizeof(uint8_t)*2).data();
+    uint8_t type = buff[0];
+    uint8_t hops = buff[1];
+    LinkID linkid;
+    linkid.deserialize(message(sizeof(uint8_t)*2));
+    
+    logging_warn("Node " << msg->getSourceNode()
+            << " informed us, that our message of type " << (int) type
+            << " is lost after traveling " << (int) hops << " hops."
+            << " (LinkID: " << linkid.toString());
+
+    
+    // TODO switch-case ?
+    
+    // BRANCH: LinkRequest --> link request failed
+    if ( type == OverlayMsg::typeLinkRequest )
+    {
+        __onLinkEstablishmentFailed(linkid);
+    }
+    
+    // BRANCH: Data --> link disrupted. Drop link.
+    //   (We could use something more advanced here. e.g. At least send a 
+    //    keep-alive message and wait for a keep-alive reply.)
+    if ( type == OverlayMsg::typeData )
+    {
+        LinkDescriptor* link_desc = getDescriptor(linkid);
+        
+        if ( link_desc )
+        {
+            link_desc->failed = true;
+        }
+        
+        dropLink(linkid);
+    }
+    
+    // BRANCH: ping lost
+    if ( type == OverlayMsg::typePing )
+    {
+        CommunicationListener* lst = getListener(msg->getService());
+        if( lst != NULL )
+        {
+            lst->onPingLost(msg->getSourceNode());
+        }
+    }
+    
+    return true;
+}
+
+bool BaseOverlay::handlePing( OverlayMsg* overlayMsg, LinkDescriptor* ld )
+{
+    // TODO AKTUELL: implement interfaces: Node::ping(node); BaseOverlay::ping(node)
+    
+    bool send_pong = false;
+    
+    // inform application and ask permission to send a pong message
+    CommunicationListener* lst = getListener(overlayMsg->getService());
+    if( lst != NULL )
+    {
+        send_pong = lst->onPing(overlayMsg->getSourceNode());
+    }
+    
+    // send pong message if allowed
+    if ( send_pong )
+    {
+        OverlayMsg pong_msg(OverlayMsg::typePong);
+        pong_msg.setSeqNum(overlayMsg->getSeqNum());
+        
+        // send message
+        try
+        {
+            send_node( &pong_msg, 
+                overlayMsg->getSourceNode(), 
+                system_priority::OVERLAY,
+                overlayMsg->getService() );
+        }
+        catch ( message_not_sent& e )
+        {
+            logging_info("Could not send Pong-Message to node: " << 
+                overlayMsg->getSourceNode());
+        }
+    }
+}
+
+bool BaseOverlay::handlePong( OverlayMsg* overlayMsg, LinkDescriptor* ld )
+{
+    // inform application
+    CommunicationListener* lst = getListener(overlayMsg->getService());
+    if( lst != NULL )
+    {
+        lst->onPong(overlayMsg->getSourceNode());
+    }
+}
 
 bool BaseOverlay::handleLinkUpdate( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
@@ -1439,5 +2040,5 @@
 		overlayMsg->setSourceLink(ld->overlayId);
 		overlayMsg->setService(ld->service);
-		send( overlayMsg, ld );
+		send( overlayMsg, ld, system_priority::OVERLAY );
 	}
 
@@ -1481,8 +2082,8 @@
 	if( ld->messageQueue.size() > 0 ) {
 		logging_info( "Sending out queued messages on link " << ld );
-		BOOST_FOREACH( Message* msg, ld->messageQueue ) {
-			sendMessage( msg, ld->overlayId );
-			delete msg;
-		}
+        foreach( LinkDescriptor::message_queue_entry msg, ld->messageQueue )
+        {
+            sendMessage( msg.message, ld->overlayId, msg.priority );
+        }
 		ld->messageQueue.clear();
 	}
@@ -1497,5 +2098,4 @@
 /// handle a link request and reply
 bool BaseOverlay::handleLinkRequest( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
-	logging_info( "Link request received from node id=" << overlayMsg->getSourceNode() );
 
 	//TODO: Check if a request has already been sent using getSourceLink() ...
@@ -1514,16 +2114,33 @@
 	ldn->remoteNode = overlayMsg->getSourceNode();
 	ldn->remoteLink = overlayMsg->getSourceLink();
-
+	ldn->hops = overlayMsg->getNumHops();
+	
+    // initialize sequence numbers
+    ldn->last_sent_seqnum = SequenceNumber::createRandomSeqNum_Short();
+    logging_debug("Creating new link with initial SeqNum: " << ldn->last_sent_seqnum);
+    
+    
 	// update time-stamps
 	ldn->setAlive();
 	ldn->setAutoUsed();
 
+	logging_info( "Link request received from node id="
+	        << overlayMsg->getSourceNode()
+	        << " LINK: "
+	        << ldn);
+	
 	// create reply message and send back!
 	overlayMsg->swapRoles(); // swap source/destination
 	overlayMsg->setType(OverlayMsg::typeLinkReply);
 	overlayMsg->setSourceLink(ldn->overlayId);
-	overlayMsg->setSourceEndpoint( bc->getEndpointDescriptor() );
 	overlayMsg->setRelayed(true);
-	send( overlayMsg, ld ); // send back to link
+//	overlayMsg->setRouteRecord(true);
+    overlayMsg->setSeqNum(ld->last_sent_seqnum);
+	
+	// TODO aktuell do the same thing in the typeLinkRequest-Message, too. But be careful with race conditions!!
+	// append our endpoints (for creation of a direct link)
+	overlayMsg->set_payload_message(bc->getEndpointDescriptor().serialize());
+	
+	send( overlayMsg, ld, system_priority::OVERLAY ); // send back to link
 
 	// inform listener
@@ -1534,6 +2151,13 @@
 }
 
-bool BaseOverlay::handleLinkReply( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
-
+bool BaseOverlay::handleLinkReply(
+        OverlayMsg* overlayMsg,
+        reboost::shared_buffer_t sub_message,
+        LinkDescriptor* ld )
+{
+    // deserialize EndpointDescriptor
+    EndpointDescriptor endpoints;
+    endpoints.deserialize(sub_message);
+    
 	// find link request
 	LinkDescriptor* ldn = getDescriptor(overlayMsg->getDestinationLink());
@@ -1554,9 +2178,10 @@
 
 	// debug message
-	logging_debug( "Link request reply received. Establishing link"
+	logging_info( "Link request reply received. Establishing link"
 			<< " for service " << overlayMsg->getService().toString()
 			<< " with local id=" << overlayMsg->getDestinationLink()
 			<< " and remote link id=" << overlayMsg->getSourceLink()
-			<< " to " << overlayMsg->getSourceEndpoint().toString()
+			<< " to " << endpoints.toString()
+			<< " hop count: " << overlayMsg->getRouteRecord().size()
 	);
 
@@ -1577,7 +2202,7 @@
 		logging_info( "Sending out queued messages on link " <<
 				ldn->overlayId.toString() );
-		BOOST_FOREACH( Message* msg, ldn->messageQueue ) {
-			sendMessage( msg, ldn->overlayId );
-			delete msg;
+		foreach( LinkDescriptor::message_queue_entry msg, ldn->messageQueue )
+		{
+			sendMessage( msg.message, ldn->overlayId, msg.priority );
 		}
 		ldn->messageQueue.clear();
@@ -1589,5 +2214,5 @@
 	// try to replace relay link with direct link
 	ldn->retryCounter = 3;
-	ldn->endpoint = overlayMsg->getSourceEndpoint();
+	ldn->endpoint = endpoints;
 	ldn->communicationId =	bc->establishLink( ldn->endpoint );
 
@@ -1596,15 +2221,42 @@
 
 /// handle a keep-alive message for a link
-bool BaseOverlay::handleLinkAlive( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
+bool BaseOverlay::handleLinkAlive( OverlayMsg* overlayMsg, LinkDescriptor* ld )
+{
 	LinkDescriptor* rld = getDescriptor(overlayMsg->getDestinationLink());
-	if ( rld != NULL ) {
-		logging_debug("Keep-Alive for " <<
-				overlayMsg->getDestinationLink() );
+	
+	if ( rld != NULL )
+	{
+		logging_debug("Keep-Alive for " << overlayMsg->getDestinationLink() );
 		if (overlayMsg->isRouteRecord())
+		{
 			rld->routeRecord = overlayMsg->getRouteRecord();
+		}
+		
+		// set alive
 		rld->setAlive();
+		
+		
+		/* answer keep alive */
+		if ( overlayMsg->getType() == OverlayMsg::typeKeepAlive )
+		{
+            time_t now = time(NULL);
+            logging_debug("[BaseOverlay] Answering KeepAlive over "
+                    << ld->to_string()
+                    << " after "
+                    << difftime( now, ld->keepAliveSent )
+                    << "s");
+            
+            OverlayMsg msg( OverlayMsg::typeKeepAliveReply,
+                    OverlayInterface::OVERLAY_SERVICE_ID, nodeId, ld->remoteNode );
+            msg.setRouteRecord(true);
+            ld->keepAliveSent = now;
+            send_link( &msg, ld->overlayId, system_priority::OVERLAY );
+		}
+
 		return true;
-	} else {
-		logging_error("Keep-Alive for "
+	}
+	else
+	{
+		logging_error("No Keep-Alive for "
 				<< overlayMsg->getDestinationLink() << ": link unknown." );
 		return false;
@@ -1636,17 +2288,28 @@
 	// erase the original descriptor
 	eraseDescriptor(ld->overlayId);
+	
+    // inform listener
+    if( rld->listener != NULL)
+        rld->listener->onLinkChanged( rld->overlayId, rld->remoteNode );
+	
 	return true;
 }
 
 /// handles an incoming message
-bool BaseOverlay::handleMessage( const Message* message, LinkDescriptor* ld,
-		const LinkID bcLink ) {
-	logging_debug( "Handling message: " << message->toString());
-
+bool BaseOverlay::handleMessage( reboost::shared_buffer_t message, LinkDescriptor* ld,
+		const LinkID bcLink )
+{
 	// decapsulate overlay message
-	OverlayMsg* overlayMsg =
-			const_cast<Message*>(message)->decapsulate<OverlayMsg>();
-	if( overlayMsg == NULL ) return false;
-
+	OverlayMsg* overlayMsg = new OverlayMsg();
+	reboost::shared_buffer_t sub_buff = overlayMsg->deserialize_from_shared_buffer(message);
+
+// 	// XXX debug
+// 	logging_info( "Received overlay message."
+// 	        << " Hops: " << (int) overlayMsg->getNumHops()
+// 	        << " Type: " << (int) overlayMsg->getType()
+// 	        << " Payload size: " << sub_buff.size()
+//             << " SeqNum: " << overlayMsg->getSeqNum() );
+	
+	
 	// increase number of hops
 	overlayMsg->increaseNumHops();
@@ -1660,6 +2323,7 @@
 	// handle signaling messages (do not route!)
 	if (overlayMsg->getType()>=OverlayMsg::typeSignalingStart &&
-			overlayMsg->getType()<=OverlayMsg::typeSignalingEnd ) {
-		overlayInterface->onMessage(overlayMsg, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
+			overlayMsg->getType()<=OverlayMsg::typeSignalingEnd )
+	{
+		overlayInterface->onMessage(overlayMsg, sub_buff, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
 		delete overlayMsg;
 		return true;
@@ -1673,42 +2337,110 @@
 				<< " to " << overlayMsg->getDestinationNode()
 		);
-		route( overlayMsg );
+		
+//		// XXX testing AKTUELL
+//        logging_info("MARIO: Routing message "
+//                << " from " << overlayMsg->getSourceNode()
+//                << " to " << overlayMsg->getDestinationNode() );
+//        logging_info( "Type: " << overlayMsg->getType() << " Payload size: " << sub_buff.size());
+		overlayMsg->append_buffer(sub_buff);
+		
+		route( overlayMsg, ld->remoteNode );
 		delete overlayMsg;
 		return true;
 	}
 
-	// handle base overlay message
+	
+	/* handle base overlay message */
 	bool ret = false; // return value
-	switch ( overlayMsg->getType() ) {
-
-	// data transport messages
-	case OverlayMsg::typeData:
-		ret = handleData(overlayMsg, ld); 			break;
-
-		// overlay setup messages
-	case OverlayMsg::typeJoinRequest:
-		ret = handleJoinRequest(overlayMsg, bcLink ); 	break;
-	case OverlayMsg::typeJoinReply:
-		ret = handleJoinReply(overlayMsg, bcLink ); 	break;
-
-		// link specific messages
-	case OverlayMsg::typeLinkRequest:
-		ret = handleLinkRequest(overlayMsg, ld ); 	break;
-	case OverlayMsg::typeLinkReply:
-		ret = handleLinkReply(overlayMsg, ld ); 	break;
-	case OverlayMsg::typeLinkUpdate:
-		ret = handleLinkUpdate(overlayMsg, ld );  	break;
-	case OverlayMsg::typeLinkAlive:
-		ret = handleLinkAlive(overlayMsg, ld );   	break;
-	case OverlayMsg::typeLinkDirect:
-		ret = handleLinkDirect(overlayMsg, ld );  	break;
-
-		// handle unknown message type
-	default: {
-		logging_error( "received message in invalid state! don't know " <<
-				"what to do with this message of type " << overlayMsg->getType() );
-		ret = false;
-		break;
-	}
+	try
+	{
+        switch ( overlayMsg->getType() ) 
+        {
+            // data transport messages
+            case OverlayMsg::typeData:
+            {
+                // NOTE: On relayed links, Â»ldÂ« does not point to our link, but on the relay link. 
+                LinkDescriptor* end_to_end_ld = getDescriptor(overlayMsg->getDestinationLink());
+                
+                if ( ! end_to_end_ld )
+                {
+                    logging_warn("Error: Data-Message claims to belong to a link we don't know.");
+                    
+                    ret = false;
+                }
+                else
+                {
+                    // message received --> link is alive
+                    end_to_end_ld->keepAliveReceived = time(NULL);
+                    // hop count on this link
+                    end_to_end_ld->hops = overlayMsg->getNumHops();
+                    
+                    // * call handler *
+                    ret = handleData(sub_buff, overlayMsg, end_to_end_ld);
+                }
+                
+                break;
+            }
+            case OverlayMsg::typeMessageLost:
+                ret = handleLostMessage(sub_buff, overlayMsg);
+                
+                break;
+        
+                // overlay setup messages
+            case OverlayMsg::typeJoinRequest:
+                ret = handleJoinRequest(sub_buff, overlayMsg->getSourceNode(), bcLink ); 	break;
+            case OverlayMsg::typeJoinReply:
+                ret = handleJoinReply(sub_buff, bcLink ); 	break;
+        
+                // link specific messages
+            case OverlayMsg::typeLinkRequest:
+                ret = handleLinkRequest(overlayMsg, ld ); 	break;
+            case OverlayMsg::typeLinkReply:
+                ret = handleLinkReply(overlayMsg, sub_buff, ld ); 	break;
+            case OverlayMsg::typeLinkUpdate:
+                ret = handleLinkUpdate(overlayMsg, ld );  	break;
+            case OverlayMsg::typeKeepAlive:
+            case OverlayMsg::typeKeepAliveReply:
+                ret = handleLinkAlive(overlayMsg, ld );   	break;
+            case OverlayMsg::typeLinkDirect:
+                ret = handleLinkDirect(overlayMsg, ld );  	break;
+                
+            case OverlayMsg::typeLinkClose:
+            {
+                dropLink(overlayMsg->getDestinationLink());
+                __removeDroppedLink(overlayMsg->getDestinationLink());
+                
+                break;
+            }
+            
+            /// ping over overlay path (or similar)
+            case OverlayMsg::typePing:
+            {
+                ret = handlePing(overlayMsg, ld);
+                break;
+            }
+            case OverlayMsg::typePong:
+            {
+                ret = handlePong(overlayMsg, ld);
+                break;
+            }
+            
+                // handle unknown message type
+            default:
+            {
+                logging_error( "received message in invalid state! don't know " <<
+                        "what to do with this message of type " << overlayMsg->getType() );
+                ret = false;
+                break;
+            }
+        }
+	}
+	catch ( reboost::illegal_sub_buffer& e )
+	{
+	    logging_error( "Failed to create sub-buffer while reading message: Â»"
+	            << e.what()
+	            << "Â« Message too short? ");
+	    
+	    assert(false); // XXX
 	}
 
@@ -1720,11 +2452,8 @@
 // ----------------------------------------------------------------------------
 
-void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service) {
+void BaseOverlay::broadcastMessage(reboost::message_t message, const ServiceID& service, uint8_t priority) {
 
 	logging_debug( "broadcasting message to all known nodes " <<
 			"in the overlay from service " + service.toString() );
-
-	if(message == NULL) return;
-	message->setReleasePayload(false);
 
 	OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes(true);
@@ -1732,6 +2461,6 @@
 		NodeID& id = nodes.at(i);
 		if(id == this->nodeId) continue; // don't send to ourselfs
-		if(i+1 == nodes.size()) message->setReleasePayload(true); // release payload on last send
-		sendMessage( message, id, service );
+
+		sendMessage( message, id, priority, service );
 	}
 }
@@ -1755,5 +2484,5 @@
 vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
 	vector<LinkID> linkvector;
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
+	foreach( LinkDescriptor* ld, links ) {
 		if( ld->remoteNode == nid || nid == NodeID::UNSPECIFIED ) {
 			linkvector.push_back( ld->overlayId );
@@ -1779,4 +2508,43 @@
 	updateVisual();
 }
+
+
+
+/* link status */
+bool BaseOverlay::isLinkDirect(const ariba::LinkID& lnk) const
+{
+    const LinkDescriptor* ld = getDescriptor(lnk);
+    
+    if (!ld)
+        return false;
+    
+    return ld->communicationUp && !ld->relayed;
+}
+
+int BaseOverlay::getHopCount(const ariba::LinkID& lnk) const
+{
+    const LinkDescriptor* ld = getDescriptor(lnk);
+    
+    if (!ld)
+        return -1;
+    
+    return ld->hops;    
+}
+
+
+bool BaseOverlay::isLinkVital(const LinkDescriptor* link) const
+{
+    time_t now = time(NULL);
+
+    return link->up && difftime( now, link->keepAliveReceived ) <= KEEP_ALIVE_TIME_OUT; // TODO is this too long for a "vital" link..? 
+}
+
+bool BaseOverlay::isLinkDirectVital(const LinkDescriptor* link) const
+{
+    return isLinkVital(link) && link->communicationUp && !link->relayed;
+}
+
+/* [link status] */
+
 
 void BaseOverlay::updateVisual(){
@@ -1878,6 +2646,6 @@
 	static set<NodeID> linkset;
 	set<NodeID> remotenodes;
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
-		if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID)
+	foreach( LinkDescriptor* ld, links ) {
+		if (!isLinkVital(ld) || ld->service != OverlayInterface::OVERLAY_SERVICE_ID)
 			continue;
 
@@ -1895,5 +2663,5 @@
 	do{
 		changed = false;
-		BOOST_FOREACH(NodeID n, linkset){
+		foreach(NodeID n, linkset){
 			if(remotenodes.find(n) == remotenodes.end()){
 				visualInstance.visDisconnect(visualIdBase, this->nodeId, n, "");
@@ -1908,5 +2676,5 @@
 	do{
 		changed = false;
-		BOOST_FOREACH(NodeID n, remotenodes){
+		foreach(NodeID n, remotenodes){
 			if(linkset.find(n) == linkset.end()){
 				visualInstance.visConnect(visualIdBase, this->nodeId, n, "");
@@ -1933,5 +2701,5 @@
 	// dump link state
 	s << "--- link state -------------------------------" << endl;
-	BOOST_FOREACH( LinkDescriptor* ld, links ) {
+	foreach( LinkDescriptor* ld, links ) {
 		s << "link " << i << ": " << ld << endl;
 		i++;
Index: source/ariba/overlay/BaseOverlay.h
===================================================================
--- source/ariba/overlay/BaseOverlay.h	(revision 11885)
+++ source/ariba/overlay/BaseOverlay.h	(revision 12060)
@@ -47,5 +47,12 @@
 #include <vector>
 #include <deque>
+#include <stdexcept>
 #include <boost/foreach.hpp>
+
+#ifdef ECLIPSE_PARSER
+    #define foreach(a, b) for(a : b)
+#else
+    #define foreach(a, b) BOOST_FOREACH(a, b)
+#endif
 
 #include "ariba/utility/messages.h"
@@ -64,4 +71,5 @@
 #include "ariba/overlay/modules/OverlayStructureEvents.h"
 #include "ariba/overlay/OverlayBootstrap.h"
+#include "ariba/overlay/SequenceNumber.h"
 
 // forward declarations
@@ -92,4 +100,7 @@
 using ariba::communication::BaseCommunication;
 using ariba::communication::CommunicationEvents;
+
+// transport
+//using ariba::transport::system_priority;
 
 // utilities
@@ -103,5 +114,4 @@
 using ariba::utility::Demultiplexer;
 using ariba::utility::MessageReceiver;
-using ariba::utility::MessageSender;
 using ariba::utility::seqnum_t;
 using ariba::utility::Timer;
@@ -110,5 +120,19 @@
 namespace overlay {
 
-using namespace ariba::addressing;
+
+
+class message_not_sent: public std::runtime_error
+{
+public:
+    /** Takes a character string describing the error.  */
+    explicit message_not_sent(const string& __arg)  :
+        std::runtime_error(__arg)
+    {
+    }
+    
+    virtual ~message_not_sent() throw() {}
+};
+
+
 
 class LinkDescriptor;
@@ -121,5 +145,5 @@
 		protected Timer {
 
-	friend class OneHop;
+//	friend class OneHop;  // DEPRECATED
 	friend class Chord;
 	friend class ariba::SideportListener;
@@ -128,5 +152,4 @@
 
 public:
-
 	/**
 	 * Constructs an empty non-functional base overlay instance
@@ -142,5 +165,5 @@
 	 * Starts the Base Overlay instance
 	 */
-	void start(BaseCommunication& _basecomm, const NodeID& _nodeid);
+	void start(BaseCommunication* _basecomm, const NodeID& _nodeid);
 
 	/**
@@ -161,5 +184,5 @@
 	 * Starts a link establishment procedure to the specfied node
 	 * for the service with id service
-	 *
+	 * 
 	 * @param node Destination node id
 	 * @param service Service to connect to
@@ -179,10 +202,20 @@
 	void dropLink( const LinkID& link );
 
+	
+	
+	/* +++++ Message sending +++++ */
+	
+	
 	/// sends a message over an existing link
-	seqnum_t sendMessage(const Message* message, const LinkID& link );
+	const SequenceNumber& sendMessage(reboost::message_t message,
+	        const LinkID& link,
+	        uint8_t priority ) throw(message_not_sent);
 
 	/// sends a message to a node and a specific service
-	seqnum_t sendMessage(const Message* message, const NodeID& remote,
-		const ServiceID& service = OverlayInterface::OVERLAY_SERVICE_ID);
+    const SequenceNumber& sendMessage(reboost::message_t message,
+	        const NodeID& remote,
+	        uint8_t priority,
+	        const ServiceID& service = OverlayInterface::OVERLAY_SERVICE_ID);
+
 
     /**
@@ -191,6 +224,6 @@
      *  @return NodeID of the (closest) destination node; 
      */
-	NodeID sendMessageCloserToNodeID(const Message* message, const NodeID& address,
-	        const ServiceID& service = OverlayInterface::OVERLAY_SERVICE_ID);
+	NodeID sendMessageCloserToNodeID(reboost::message_t message, const NodeID& address,
+	        uint8_t priority, const ServiceID& service = OverlayInterface::OVERLAY_SERVICE_ID);
 	
 	/**
@@ -198,6 +231,11 @@
 	 * Depending on the structure of the overlay, this can be very different.
 	 */
-	void broadcastMessage(Message* message, const ServiceID& service);
-
+	void broadcastMessage(reboost::message_t message, const ServiceID& service, uint8_t priority);
+
+	
+	/* +++++ [Message sending] +++++ */
+	
+	
+	
 	/**
 	 * Returns the end-point descriptor of a link.
@@ -294,44 +332,59 @@
 	 */
 	void leaveSpoVNet();
+	
+	
+	/* link status */
+	bool isLinkDirect(const ariba::LinkID& lnk) const;
+	int getHopCount(const ariba::LinkID& lnk) const;
+
+    bool isLinkVital(const LinkDescriptor* link) const;
+    bool isLinkDirectVital(const LinkDescriptor* link) const;
 
 protected:
-	/**
-	 * @see ariba::communication::CommunicationEvents.h
-	 */
-	virtual void onLinkUp(const LinkID& id, const address_v* local,
-		const address_v* remote);
-
-	/**
-	 * @see ariba::communication::CommunicationEvents.h
-	 */
-	virtual void onLinkDown(const LinkID& id, const address_v* local,
-		const address_v* remote);
-
-	/**
-	 * @see ariba::communication::CommunicationEvents.h
-	 */
-	virtual void onLinkChanged(const LinkID& id,
-		const address_v* oldlocal, const address_v* newlocal,
-		const address_v* oldremote, const address_v* newremote);
-
-	/**
-	 * @see ariba::communication::CommunicationEvents.h
-	 */
-	virtual void onLinkFail(const LinkID& id, const address_v* local,
-		const address_v* remote);
-
-	/**
-	 * @see ariba::communication::CommunicationEvents.h
-	 */
-	virtual void onLinkQoSChanged(const LinkID& id,
-		const address_v* local, const address_v* remote,
-		const QoSParameterSet& qos);
-
-	/**
-	 * @see ariba::communication::CommunicationEvents.h
-	 */
-	virtual bool onLinkRequest(const LinkID& id, const address_v* local,
-		const address_v* remote);
-
+
+    /**
+     * @see ariba::communication::CommunicationEvents.h
+     */
+    virtual bool onLinkRequest(const LinkID& id,
+            const addressing2::EndpointPtr local,
+            const addressing2::EndpointPtr remote);
+
+    /**
+     * @see ariba::communication::CommunicationEvents.h
+     */
+    virtual void onLinkUp(const LinkID& id,
+            const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote);
+
+    /**
+     * @see ariba::communication::CommunicationEvents.h
+     */
+    virtual void onLinkDown(const LinkID& id,
+            const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote);
+
+    /**
+     * @see ariba::communication::CommunicationEvents.h
+     */
+    virtual void onLinkChanged(const LinkID& id,
+        const addressing2::EndpointPtr oldlocal,  const addressing2::EndpointPtr newlocal,
+        const addressing2::EndpointPtr oldremote, const addressing2::EndpointPtr newremote);
+
+    /**
+     * @see ariba::communication::CommunicationEvents.h
+     * 
+     * NOTE: Just calls onLinkDown (at the moment..)
+     */
+    virtual void onLinkFail(const LinkID& id,
+            const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote);
+
+    /**
+     * @see ariba::communication::CommunicationEvents.h
+     */
+//    virtual void onLinkQoSChanged(const LinkID& id,
+//            const addressing2::EndpointPtr local, const addressing2::EndpointPtr remote,
+//            const QoSParameterSet& qos);
+
+	
+	
+	
 	/**
 	 * Processes a received message from BaseCommunication
@@ -340,6 +393,8 @@
 	 * the node the message came from!
 	 */
-	virtual bool receiveMessage( const Message* message, const LinkID& link,
-		const NodeID& );
+	virtual bool receiveMessage( reboost::shared_buffer_t message,
+	        const LinkID& link,
+	        const NodeID&,
+	        bool bypass_overlay );
 
 	/**
@@ -359,4 +414,12 @@
 	std::string getLinkHTMLInfo();
 
+
+private:
+	/// NOTE: "id" is an Overlay-LinkID
+	void __onLinkEstablishmentFailed(const LinkID& id);
+	
+	/// called from typeLinkClose-handler
+    void __removeDroppedLink(const LinkID& link);
+	
 private:
 	/// is the base overlay started yet
@@ -396,21 +459,26 @@
 
 	/// demultiplexes a incoming message with link descriptor
-	bool handleMessage( const Message* message, LinkDescriptor* ld,
+	bool handleMessage( reboost::shared_buffer_t message, LinkDescriptor* ld,
 		const LinkID bcLink = LinkID::UNSPECIFIED );
 
 	// handle data and signalling messages
-	bool handleData( OverlayMsg* msg, LinkDescriptor* ld );
+	bool handleData( reboost::shared_buffer_t message, OverlayMsg* msg, LinkDescriptor* ld );
+	bool handleLostMessage( reboost::shared_buffer_t message, OverlayMsg* msg );
 	bool handleSignaling( OverlayMsg* msg, LinkDescriptor* ld );
 
 	// handle join request / reply messages
-	bool handleJoinRequest( OverlayMsg* msg, const LinkID& bcLink );
-	bool handleJoinReply( OverlayMsg* msg, const LinkID& bcLink );
+	bool handleJoinRequest( reboost::shared_buffer_t message, const NodeID& source, const LinkID& bcLink );
+	bool handleJoinReply( reboost::shared_buffer_t message, const LinkID& bcLink );
 
 	// handle link messages
 	bool handleLinkRequest( OverlayMsg* msg, LinkDescriptor* ld );
-	bool handleLinkReply( OverlayMsg* msg, LinkDescriptor* ld );
+	bool handleLinkReply( OverlayMsg* msg, reboost::shared_buffer_t sub_message, LinkDescriptor* ld );
 	bool handleLinkUpdate( OverlayMsg* msg, LinkDescriptor* ld );
 	bool handleLinkDirect( OverlayMsg* msg, LinkDescriptor* ld );
 	bool handleLinkAlive( OverlayMsg* msg, LinkDescriptor* ld );
+    
+    // ping-pong over overlaypath/routing
+    bool handlePing( OverlayMsg* overlayMsg, LinkDescriptor* ld );
+    bool handlePong( OverlayMsg* overlayMsg, LinkDescriptor* ld );
 
 
@@ -478,24 +546,40 @@
 	// internal message delivery -----------------------------------------------
 
+    // Convert OverlayMessage into new format and give it down to BaseCommunication
+    seqnum_t send_overlaymessage_down( OverlayMsg* message, const LinkID& bc_link, uint8_t priority );
+
+    
 	/// routes a message to its destination node
-	void route( OverlayMsg* message );
-
+	void route( OverlayMsg* message, const NodeID& last_hop = NodeID::UNSPECIFIED );
+	
 	/// sends a raw message to another node, delivers it to the base overlay class
-	seqnum_t send( OverlayMsg* message, const NodeID& destination );
+	/// may throw "message_not_sent"-exception
+	seqnum_t send( OverlayMsg* message,
+                   const NodeID& destination,
+                   uint8_t priority,
+                const NodeID& last_hop = NodeID::UNSPECIFIED )
+    throw(message_not_sent);
 
 	/// send a raw message using a link descriptor, delivers it to the base overlay class
-	seqnum_t send( OverlayMsg* message, LinkDescriptor* ld,
-		bool ignore_down = false );
+	seqnum_t send( OverlayMsg* message,
+	        LinkDescriptor* ld,
+	        uint8_t priority ) throw(message_not_sent);
 
 	/// send a message using a node id using overlay routing
 	/// sets necessary fields in the overlay message!
-	seqnum_t send_node( OverlayMsg* message, const NodeID& remote,
-		const ServiceID& service = OverlayInterface::OVERLAY_SERVICE_ID);
+	/// may throw "message_not_sent"-exception
+	seqnum_t send_node( OverlayMsg* message, const NodeID& remote, uint8_t priority,
+		const ServiceID& service = OverlayInterface::OVERLAY_SERVICE_ID) throw(message_not_sent);
 
 	/// send a message using a node id using overlay routing using a link
 	/// sets necessary fields in the overlay message!
-	seqnum_t send_link( OverlayMsg* message, const LinkID& link,
-		bool ignore_down = false );
-
+	void send_link( OverlayMsg* message,
+	        const LinkID& link,
+	        uint8_t priority ) throw(message_not_sent);
+
+	
+	/// sends a notification to a sender from whom we just dropped a message
+	void report_lost_message( const OverlayMsg* message );
+	
 	// misc --------------------------------------------------------------------
 
Index: source/ariba/overlay/CMakeLists.txt
===================================================================
--- source/ariba/overlay/CMakeLists.txt	(revision 11885)
+++ source/ariba/overlay/CMakeLists.txt	(revision 12060)
@@ -41,4 +41,5 @@
     LinkDescriptor.h
     OverlayBootstrap.h
+    SequenceNumber.h
     )
 
@@ -47,4 +48,5 @@
     LinkDescriptor.cpp
     OverlayBootstrap.cpp
+    SequenceNumber.cpp
     )
 
Index: source/ariba/overlay/LinkDescriptor.h
===================================================================
--- source/ariba/overlay/LinkDescriptor.h	(revision 11885)
+++ source/ariba/overlay/LinkDescriptor.h	(revision 12060)
@@ -12,4 +12,11 @@
 #include "ariba/communication/EndpointDescriptor.h"
 #include "ariba/CommunicationListener.h"
+
+// reboost messages
+#include "ariba/utility/transport/messages/message.hpp"
+#include <ariba/utility/misc/sha1.h>
+
+#include "ariba/overlay/SequenceNumber.h"
+
 
 namespace ariba {
@@ -37,8 +44,18 @@
 class LinkDescriptor {
 public:
+    struct message_queue_entry
+    {
+        reboost::message_t message;
+        uint8_t priority;
+    };
+    
 	// ctor
 	LinkDescriptor() {
+	    time_t now = time(NULL);
+	    
 		// default values
 		this->up = false;
+//         this->closing = false;
+        this->failed = false;
 		this->fromRemote = false;
 		this->remoteNode = NodeID::UNSPECIFIED;
@@ -46,8 +63,8 @@
 		this->communicationUp = false;
 		this->communicationId = LinkID::UNSPECIFIED;
-		this->keepAliveTime = time(NULL);
-		this->keepAliveMissed = 0;
+		this->keepAliveReceived = now;
+		this->keepAliveSent = now;
 		this->relaying     = false;
-		this->timeRelaying = time(NULL);
+		this->timeRelaying = now;
 		this->dropAfterRelaying = false;
 		this->service  = ServiceID::UNSPECIFIED;
@@ -56,6 +73,9 @@
 		this->remoteLink = LinkID::UNSPECIFIED;
 		this->autolink = false;
-		this->lastuse = time(NULL);
+		this->lastuse = now;
 		this->retryCounter = 0;
+		this->hops = -1;
+        
+        this->transmit_seqnums = false; // XXX
 	}
 
@@ -67,12 +87,8 @@
 	// general information about the link --------------------------------------
 	bool up;           ///< flag whether this link is up and running
+// 	bool closing;      ///< flag, whether this link is in the regular process of closing
+	bool failed;       ///< flag, whether communication is (assumed to be) not/no longer possible on this link
 	bool fromRemote;   ///< flag, whether this link was requested from remote
 	NodeID remoteNode; ///< remote end-point node
-	bool isVital() {
-		return up && keepAliveMissed == 0;
-	}
-	bool isDirectVital() {
-		return isVital() && communicationUp && !relayed;
-	}
 
 
@@ -82,4 +98,8 @@
 	bool   communicationUp;   ///< flag, whether the communication is up
 
+	// sequence numbers --------------------------------------------------------
+	SequenceNumber last_sent_seqnum;
+    bool transmit_seqnums;
+    
 	// direct link retries -----------------------------------------------------
 	EndpointDescriptor endpoint;
@@ -87,9 +107,9 @@
 
 	// link alive information --------------------------------------------------
-	time_t keepAliveTime; ///< the last time a keep-alive message was received
-	int keepAliveMissed;  ///< the number of missed keep-alive messages
+	time_t keepAliveReceived; ///< the last time a keep-alive message was received
+	time_t keepAliveSent;  ///< the number of missed keep-alive messages
 	void setAlive() {
-		keepAliveMissed = 0;
-		keepAliveTime = time(NULL);
+//		keepAliveSent = time(NULL);
+		keepAliveReceived = time(NULL);
 	}
 
@@ -98,4 +118,5 @@
 	LinkID remoteLink; ///< the remote link id
 	vector<NodeID> routeRecord;
+	int hops;
 
 	// relay state -------------------------------------------------------------
@@ -114,6 +135,6 @@
 	// auto links --------------------------------------------------------------
 	bool autolink;  ///< flag, whether this link is a auto-link
-	time_t lastuse; ///< time, when the link was last used
-	deque<Message*> messageQueue; ///< waiting messages to be delivered
+	time_t lastuse; ///< time, when the link was last used XXX AUTO_LINK-ONLY
+	deque<message_queue_entry> messageQueue; ///< waiting messages to be delivered
 	void setAutoUsed() {
 		if (autolink) lastuse = time(NULL);
@@ -121,5 +142,5 @@
 	/// drops waiting auto-link messages
 	void flushQueue() {
-		BOOST_FOREACH( Message* msg, messageQueue )	delete msg;
+//		BOOST_FOREACH( Message* msg, messageQueue )	delete msg;  // XXX MARIO: shouldn't be necessary anymore, since we're using shared pointers
 		messageQueue.clear();
 	}
@@ -127,13 +148,21 @@
 	// string representation ---------------------------------------------------
 	std::string to_string() const {
+	    time_t now = time(NULL);
+	    
 		std::ostringstream s;
+        if ( relayed )
+            s << "[RELAYED-";
+        else
+            s << "[DIRECT-";
+        s << "LINK] ";
+        s << "id=" << overlayId.toString().substr(0,4) << " ";
+        s << "serv=" << service.toString() << " ";
 		s << "up=" << up << " ";
 		s << "init=" << !fromRemote << " ";
-		s << "id=" << overlayId.toString().substr(0,4) << " ";
-		s << "serv=" << service.toString() << " ";
 		s << "node=" << remoteNode.toString().substr(0,4) << " ";
 		s << "relaying=" << relaying << " ";
-		s << "miss=" << keepAliveMissed << " ";
+		s << "last_received=" << now - keepAliveReceived << "s ";
 		s << "auto=" << autolink << " ";
+		s << "hops=" << hops << " ";
 		if ( relayed ) {
 			s << "| Relayed: ";
@@ -146,5 +175,5 @@
 		} else {
 			s << "| Direct: ";
-			s << "using id=" << communicationId.toString().substr(0,4) << " ";
+			s << "using [COMMUNICATION-LINK] id=" << communicationId.toString().substr(0,4) << " ";
 			s << "(up=" << communicationUp << ") ";
 		}
Index: source/ariba/overlay/SequenceNumber.cpp
===================================================================
--- source/ariba/overlay/SequenceNumber.cpp	(revision 12060)
+++ source/ariba/overlay/SequenceNumber.cpp	(revision 12060)
@@ -0,0 +1,167 @@
+
+#include "SequenceNumber.h"
+#include <ctime>
+#include <limits>
+
+namespace ariba {
+namespace overlay {
+
+/** static initializers **/
+// DISABLED_SEQNUM const
+const SequenceNumber SequenceNumber::DISABLED;
+    
+// seed the RNG
+boost::mt19937 SequenceNumber::rng_32bit(std::time(NULL));
+
+boost::uniform_int<uint32_t> SequenceNumber::seqnum_distribution_32bit(
+    MIN_SEQ_NUM, std::numeric_limits<uint32_t>::max());
+
+boost::uniform_int<uint32_t> SequenceNumber::distribution_full32bit(
+    0, std::numeric_limits<uint32_t>::max());
+
+
+
+/** class implementation **/
+SequenceNumber::SequenceNumber():
+    seqnum_32(SEQ_NUM_DISABLED),
+    seqnum_64(SEQ_NUM_DISABLED)
+{
+}
+SequenceNumber::SequenceNumber(uint32_t seqnum):
+    seqnum_32(seqnum),
+    seqnum_64(SEQ_NUM_DISABLED)
+{
+}
+SequenceNumber::SequenceNumber(uint64_t seqnum):
+    seqnum_32(SEQ_NUM_DISABLED),
+    seqnum_64(seqnum)
+{
+}
+
+
+SequenceNumber SequenceNumber::createRandomSeqNum_Short() 
+{
+    uint32_t num = seqnum_distribution_32bit(rng_32bit);
+    return SequenceNumber(num);
+}
+
+SequenceNumber SequenceNumber::createRandomSeqNum_Long() 
+{
+    uint64_t num = distribution_full32bit(rng_32bit);
+    num << 32;
+    num += seqnum_distribution_32bit(rng_32bit);
+    
+    return SequenceNumber(num);
+}
+
+bool SequenceNumber::isShortSeqNum() const 
+{
+    return seqnum_32 >= MIN_SEQ_NUM && seqnum_64 == SEQ_NUM_DISABLED;
+}
+
+bool SequenceNumber::isLongSeqNum() const 
+{
+    return seqnum_32 == SEQ_NUM_DISABLED && seqnum_64 >= MIN_SEQ_NUM;
+}
+
+bool SequenceNumber::isDisabled() const 
+{
+    return seqnum_32 == SEQ_NUM_DISABLED && seqnum_64 == SEQ_NUM_DISABLED;
+}
+
+bool SequenceNumber::isValid() const 
+{
+    return isShortSeqNum() || isLongSeqNum();
+}
+
+void SequenceNumber::increment() 
+{
+    // BRANCH: short seqnum
+    if ( isShortSeqNum() )
+    {
+        seqnum_32++;
+        
+        // wrap overflow
+        if ( seqnum_32 < MIN_SEQ_NUM )
+        {
+            seqnum_32 = MIN_SEQ_NUM;
+        }
+    }
+    
+    // BRANCH: long seqnum
+    else if ( isLongSeqNum() )
+    {
+        seqnum_64++;
+        
+        // wrap overflow
+        if ( seqnum_64 < MIN_SEQ_NUM )
+        {
+            seqnum_64 = MIN_SEQ_NUM;
+        }
+    }
+}
+
+bool SequenceNumber::operator==(const SequenceNumber& rhs) const 
+{
+    return seqnum_32 + seqnum_64 == rhs.seqnum_32 + rhs.seqnum_64;
+}
+
+bool SequenceNumber::operator<(const SequenceNumber& rhs) const 
+{
+    return seqnum_32 + seqnum_64 < rhs.seqnum_32 + rhs.seqnum_64;
+}
+
+bool SequenceNumber::isSuccessor(const SequenceNumber& rhs) 
+{
+    // TODO implement
+    
+    return false;
+}
+
+bool SequenceNumber::isPredecessor(const SequenceNumber& rhs) 
+{
+    // TODO implement
+    
+    return false;
+}
+
+uint32_t SequenceNumber::getShortSeqNum() const 
+{
+    return seqnum_32;
+}
+
+uint64_t SequenceNumber::getLongSeqNum() const 
+{
+    return seqnum_64;
+}
+
+
+std::ostream& operator<<(std::ostream& stream, const SequenceNumber& rhs) 
+{
+    if ( rhs.isDisabled() )
+    {
+        return stream << "DISABLED";
+    }
+    
+    else if ( ! rhs.isValid() )
+    {
+        return stream << "INVALID";
+    }
+    
+    else if ( rhs.isShortSeqNum() )
+    {
+        return stream << rhs.seqnum_32;
+    }
+    
+    else if ( rhs.isLongSeqNum() )
+    {
+        return stream << rhs.seqnum_64;
+    }
+    
+    else
+    {
+        return stream << "ERROR";
+    }
+}
+
+}} // [namespace ariba::overlay]
Index: source/ariba/overlay/SequenceNumber.h
===================================================================
--- source/ariba/overlay/SequenceNumber.h	(revision 12060)
+++ source/ariba/overlay/SequenceNumber.h	(revision 12060)
@@ -0,0 +1,81 @@
+
+#ifndef SEQUENCENUMBER_H
+#define SEQUENCENUMBER_H
+
+#include <stdint.h>
+#include <iostream>
+
+// random
+#include <boost/random/mersenne_twister.hpp>
+#include <boost/random/uniform_int.hpp>
+
+namespace ariba {
+namespace overlay {
+
+#define MIN_SEQ_NUM           100
+#define SEQ_NUM_DISABLED        0
+
+class SequenceNumber
+{
+public:
+    static const SequenceNumber DISABLED;
+    
+    /// constructors
+    SequenceNumber();
+    SequenceNumber(uint32_t seqnum);
+    SequenceNumber(uint64_t seqnum);
+    
+    /// factories
+    static SequenceNumber createRandomSeqNum_Short();
+    static SequenceNumber createRandomSeqNum_Long();
+
+
+    /// get type information
+    bool isShortSeqNum() const;
+    bool isLongSeqNum() const;
+    bool isDisabled() const;
+    bool isValid() const;
+
+    
+    /// operators
+    void increment();
+    
+    /// NOTE: this is also Â»trueÂ« if the long seq_num matches the short seq_num
+    bool operator== (const SequenceNumber& rhs) const;
+    
+    /// NOTE: return value is only meaningful if Â»isValid() == trueÂ« for both values
+    bool operator< (const SequenceNumber& rhs) const;
+
+    bool isSuccessor(const SequenceNumber& rhs);
+    bool isPredecessor(const SequenceNumber& rhs);
+    
+    
+    /// getter
+    uint32_t getShortSeqNum() const;
+    uint64_t getLongSeqNum() const;
+
+    
+    /// to string
+    friend std::ostream& operator<< (std::ostream& stream, const SequenceNumber& rhs);
+    
+private:
+    uint32_t seqnum_32;
+    uint64_t seqnum_64;
+
+    /// static random_number_generator
+    static boost::mt19937 rng_32bit;
+    static boost::uniform_int<uint32_t> seqnum_distribution_32bit;
+    
+    // XXX NOTE: on later boost versions these are:
+    //   boost::random::mt19937
+    //   boost::random::uniform_int_distribution<>
+        
+    // NOTE: since the mt19937_64 is not available in this boost version, we 
+    //   need an addition distribution
+    static boost::uniform_int<uint32_t> distribution_full32bit;
+};
+
+
+}} // [namespace ariba::overlay]
+
+#endif // SEQUENCENUMBER_H
Index: source/ariba/overlay/messages/JoinReply.cpp
===================================================================
--- source/ariba/overlay/messages/JoinReply.cpp	(revision 11885)
+++ source/ariba/overlay/messages/JoinReply.cpp	(revision 12060)
@@ -44,6 +44,7 @@
 vsznDefault(JoinReply);
 
-JoinReply::JoinReply(const SpoVNetID _spovnetid, const OverlayParameterSet _param, bool _joinAllowed, const EndpointDescriptor _bootstrapEp)
-	: spovnetid( _spovnetid ), param( _param ), joinAllowed( _joinAllowed ), bootstrapEp( _bootstrapEp ){
+JoinReply::JoinReply(const SpoVNetID _spovnetid, const OverlayParameterSet _param, bool _joinAllowed)
+	: spovnetid( _spovnetid ), param( _param ), joinAllowed( _joinAllowed )
+{
 }
 
@@ -64,7 +65,7 @@
 }
 
-const EndpointDescriptor& JoinReply::getBootstrapEndpoint(){
-	return bootstrapEp;
-}
+//const EndpointDescriptor& JoinReply::getBootstrapEndpoint(){
+//	return bootstrapEp;
+//}
 
 }} // ariba::overlay
Index: source/ariba/overlay/messages/JoinReply.h
===================================================================
--- source/ariba/overlay/messages/JoinReply.h	(revision 11885)
+++ source/ariba/overlay/messages/JoinReply.h	(revision 12060)
@@ -40,10 +40,11 @@
 #define JOIN_REPLY_H__
 
-#include "ariba/utility/messages.h"
+//#include "ariba/utility/messages.h"
+#include "ariba/utility/messages/Message.h"
 #include "ariba/utility/serialization.h"
 #include "ariba/utility/types/SpoVNetID.h"
 #include "ariba/utility/types/NodeID.h"
 #include "ariba/utility/types/OverlayParameterSet.h"
-#include "ariba/communication/EndpointDescriptor.h"
+//#include "ariba/communication/EndpointDescriptor.h"
 
 using ariba::utility::OverlayParameterSet;
@@ -51,5 +52,5 @@
 using ariba::utility::SpoVNetID;
 using ariba::utility::NodeID;
-using ariba::communication::EndpointDescriptor;
+//using ariba::communication::EndpointDescriptor;
 
 namespace ariba {
@@ -64,5 +65,5 @@
 	OverlayParameterSet param; //< overlay parameters
 	bool joinAllowed; //< join successfull or access denied
-	EndpointDescriptor bootstrapEp; //< the endpoint for bootstrapping the overlay interface
+//	EndpointDescriptor bootstrapEp; //< the endpoint for bootstrapping the overlay interface
 
 public:
@@ -70,6 +71,6 @@
 		const SpoVNetID _spovnetid = SpoVNetID::UNSPECIFIED,
 		const OverlayParameterSet _param = OverlayParameterSet::DEFAULT,
-		bool _joinAllowed = false,
-		const EndpointDescriptor _bootstrapEp = EndpointDescriptor::UNSPECIFIED()
+		bool _joinAllowed = false  /*,
+		const EndpointDescriptor _bootstrapEp = EndpointDescriptor::UNSPECIFIED()*/
 	);
 
@@ -79,5 +80,5 @@
 	const OverlayParameterSet& getParam();
 	bool getJoinAllowed();
-	const EndpointDescriptor& getBootstrapEndpoint();
+//	const EndpointDescriptor& getBootstrapEndpoint();
 };
 
@@ -86,5 +87,7 @@
 sznBeginDefault( ariba::overlay::JoinReply, X ) {
 	uint8_t ja = joinAllowed;
-	X && &spovnetid && param && bootstrapEp && ja;
+	X && &spovnetid && param;
+//	X && bootstrapEp;
+	X && ja;
 	if (X.isDeserializer()) joinAllowed = ja;
 } sznEnd();
Index: source/ariba/overlay/messages/OverlayMsg.h
===================================================================
--- source/ariba/overlay/messages/OverlayMsg.h	(revision 11885)
+++ source/ariba/overlay/messages/OverlayMsg.h	(revision 12060)
@@ -47,6 +47,6 @@
 #include "ariba/utility/types/NodeID.h"
 #include "ariba/utility/types/LinkID.h"
-#include "ariba/communication/EndpointDescriptor.h"
-
+// #include <ariba/utility/misc/sha1.h>
+#include "ariba/overlay/SequenceNumber.h"
 
 namespace ariba {
@@ -57,5 +57,5 @@
 using ariba::utility::ServiceID;
 using ariba::utility::Message;
-using ariba::communication::EndpointDescriptor;
+//using ariba::communication::EndpointDescriptor;
 using_serialization;
 
@@ -64,5 +64,5 @@
  * between nodes.
  *
- * @author Sebastian Mies <mies@tm.uka.de>
+ * @author Sebastian Mies <mies@tm.uka.de>, Mario Hock
  */
 class OverlayMsg: public Message { VSERIALIZEABLE;
@@ -75,4 +75,5 @@
 		maskTransfer    = 0x10, ///< bit mask for transfer messages
 		typeData        = 0x11, ///< message contains data for higher layers
+		typeMessageLost = 0x12, ///< message contains info about a dropped message
 
 		// join signaling
@@ -87,5 +88,7 @@
 		typeLinkUpdate  = 0x33, ///< update message for link association
 		typeLinkDirect  = 0x34, ///< direct connection has been established
-		typeLinkAlive   = 0x35, ///< keep-alive message
+		typeKeepAlive   = 0x35, ///< keep-alive message
+		typeKeepAliveReply   = 0x36, ///< keep-alive message (replay)
+		typeLinkClose   = 0x37,
 
 		/// DHT routed messages
@@ -100,4 +103,8 @@
 		maskDHTResponse = 0x50, ///< bit mask for dht responses
 		typeDHTData     = 0x51, ///< DHT get data
+        
+        /// misc message types
+        typePing        = 0x44,
+        typePong        = 0x45,
 
 		// topology signaling
@@ -105,4 +112,17 @@
 		typeSignalingEnd = 0xFF    ///< end of the signaling types
 	};
+    
+    /// message flags (uint8_t)
+    enum flags_
+    {
+        flagRelayed         = 1 << 0,
+        flagRegisterRelay   = 1 << 1,
+        flagRouteRecord     = 1 << 2,
+        flagSeqNum1         = 1 << 3,
+        flagSeqNum2         = 1 << 4,
+        flagAutoLink        = 1 << 5,
+        flagLinkMessage     = 1 << 6,
+        flagHasMoreFlags    = 1 << 7
+    };
 
 	/// default constructor
@@ -114,5 +134,5 @@
 		const LinkID& _sourceLink      = LinkID::UNSPECIFIED,
 		const LinkID& _destinationLink = LinkID::UNSPECIFIED )
-	:	type(type), flags(0), hops(0), ttl(10),
+    :	type(type), flags(0), extended_flags(0), hops(0), ttl(10), priority(0),
 		service(_service),
 		sourceNode(_sourceNode), destinationNode(_destinationNode),
@@ -125,6 +145,7 @@
 	// copy constructor
 	OverlayMsg(const OverlayMsg& rhs)
-	:	type(rhs.type), flags(rhs.flags), hops(rhs.hops), ttl(rhs.ttl),
-		service(rhs.service),
+    :	type(rhs.type), flags(rhs.flags), extended_flags(rhs.extended_flags), 
+        hops(rhs.hops), ttl(rhs.ttl),
+		priority(rhs.priority), service(rhs.service),
 		sourceNode(rhs.sourceNode), destinationNode(rhs.destinationNode),
 		sourceLink(rhs.sourceLink), destinationLink(rhs.destinationLink),
@@ -149,53 +170,59 @@
 	}
 
+	/// priority ------------------------------------------------------------------
+	
+	uint8_t getPriority() const {
+	    return priority;
+	}
+	
+	void setPriority(uint8_t priority) {
+	    this->priority = priority;
+	}
+	
 	/// flags ------------------------------------------------------------------
 
 	bool isRelayed() const {
-		return (flags & 0x01)!=0;
+        return (flags & flagRelayed)!=0;
 	}
 
 	void setRelayed( bool relayed = true ) {
-		if (relayed) flags |= 1; else flags &= ~1;
+        if (relayed) flags |= flagRelayed; else flags &= ~flagRelayed;
 	}
 
 	bool isRegisterRelay() const {
-		return (flags & 0x02)!=0;
+		return (flags & flagRegisterRelay)!=0;
 	}
 
 	void setRegisterRelay( bool relayed = true ) {
-		if (relayed) flags |= 0x02; else flags &= ~0x02;
+        if (relayed) flags |= flagRegisterRelay; else flags &= ~flagRegisterRelay;
 	}
 
 	bool isRouteRecord() const {
-		return (flags & 0x04)!=0;
+		return (flags & flagRouteRecord)!=0;
 	}
 
 	void setRouteRecord( bool route_record = true ) {
-		if (route_record) flags |= 0x04; else flags &= ~0x04;
+        if (route_record) flags |= flagRouteRecord; else flags &= ~flagRouteRecord;
 	}
 
 	bool isAutoLink() const {
-		return (flags & 0x80) == 0x80;
+        return (flags & flagAutoLink) == flagAutoLink;
 	}
 
 	void setAutoLink(bool auto_link = true ) {
-		if (auto_link) flags |= 0x80; else flags &= ~0x80;
+        if (auto_link) flags |= flagAutoLink; else flags &= ~flagAutoLink;
 	}
 
 	bool isLinkMessage() const {
-		return (flags & 0x40)!=0;
+		return (flags & flagLinkMessage)!=0;
 	}
 
 	void setLinkMessage(bool link_info = true ) {
-		if (link_info) flags |= 0x40; else flags &= ~0x40;
-	}
-
-	bool containsSourceEndpoint() const {
-		return (flags & 0x20)!=0;
-	}
-
-	void setContainsSourceEndpoint(bool contains_endpoint) {
-		if (contains_endpoint) flags |= 0x20; else flags &= ~0x20;
-	}
+        if (link_info) flags |= flagLinkMessage; else flags &= ~flagLinkMessage;
+	}
+	
+	bool hasExtendedFlags() const {
+        return (flags & flagHasMoreFlags) == flagHasMoreFlags;
+    }
 
 	/// number of hops and time to live ----------------------------------------
@@ -264,13 +291,4 @@
 		this->destinationLink = link;
 		setLinkMessage();
-	}
-
-	void setSourceEndpoint( const EndpointDescriptor& endpoint ) {
-		sourceEndpoint = endpoint;
-		setContainsSourceEndpoint(true);
-	}
-
-	const EndpointDescriptor& getSourceEndpoint() const {
-		return sourceEndpoint;
 	}
 
@@ -284,4 +302,5 @@
 		destinationLink = dummyLink;
 		hops = 0;
+		routeRecord.clear();
 	}
 
@@ -294,7 +313,48 @@
 			routeRecord.push_back(node);
 	}
+	
+	/// sequence numbers
+	bool hasShortSeqNum() const
+    {
+        return (flags & (flagSeqNum1 | flagSeqNum2)) == flagSeqNum1;
+    }
+    
+    bool hasLongSeqNum() const
+    {
+        return (flags & (flagSeqNum1 | flagSeqNum2)) == flagSeqNum2;
+    }
+    
+    void setSeqNum(const SequenceNumber& sequence_number)
+    {
+        this->seqnum = sequence_number;
+        
+        // short seqnum
+        if ( sequence_number.isShortSeqNum() )
+        {
+            flags |= flagSeqNum1;
+            flags &= ~flagSeqNum2;
+        }
+        // longseqnum
+        else if ( sequence_number.isShortSeqNum() )
+        {
+            flags &= ~flagSeqNum1;
+            flags |= flagSeqNum2;
+        }
+        // no seqnum
+        else
+        {
+            flags &= ~flagSeqNum1;
+            flags &= ~flagSeqNum2;
+        }
+    }
+    
+    const SequenceNumber& getSeqNum() const
+    {
+        return seqnum;
+    }
+    
 
 private:
-	uint8_t type, flags, hops, ttl;
+	uint8_t type, flags, extended_flags, hops, ttl, priority;
 	ServiceID service;
 	NodeID sourceNode;
@@ -302,6 +362,7 @@
 	LinkID sourceLink;
 	LinkID destinationLink;
-	EndpointDescriptor sourceEndpoint;
+//	EndpointDescriptor sourceEndpoint;
 	vector<NodeID> routeRecord;
+    SequenceNumber seqnum;
 };
 
@@ -311,8 +372,16 @@
 sznBeginDefault( ariba::overlay::OverlayMsg, X ){
 	// header
-	X && type && flags && hops && ttl;
+	X && type && flags;
+    
+    if ( hasExtendedFlags() )
+        X && extended_flags;
+    
+    X && hops && ttl;
 
 	// addresses
 	X && &service && &sourceNode && &destinationNode;
+	
+	// priority
+	X && priority;
 
 	// message is associated with a end-to-end link
@@ -320,8 +389,40 @@
 		X && &sourceLink && &destinationLink;
 
-	// message is associated with a source end-point
-	if (containsSourceEndpoint())
-		X && sourceEndpoint;
-
+    
+    /* seqnum */
+    // serialize
+    if ( X.isSerializer() )
+    {
+        if ( hasShortSeqNum() )
+        {
+            uint32_t short_seqnum;
+            short_seqnum = seqnum.getShortSeqNum();
+            X && short_seqnum;
+        }
+        if ( hasLongSeqNum() )
+        {
+            uint64_t long_seqnum;
+            long_seqnum = seqnum.getLongSeqNum();
+            X && long_seqnum;
+        }
+    }
+    // deserialize
+    else
+    {
+        if ( hasShortSeqNum() )
+        {
+            uint32_t short_seqnum;
+            X && short_seqnum;
+            seqnum = ariba::overlay::SequenceNumber(short_seqnum);
+        }
+        if ( hasLongSeqNum() )
+        {
+            uint64_t long_seqnum;
+            X && long_seqnum;
+            seqnum = ariba::overlay::SequenceNumber(long_seqnum);
+        }        
+    }
+    
+    
 	// message should record its route
 	if (isRouteRecord()) {
@@ -333,5 +434,5 @@
 
 	// payload
-	X && Payload();
+//	X && Payload();
 } sznEnd();
 
Index: source/ariba/overlay/modules/OverlayFactory.cpp
===================================================================
--- source/ariba/overlay/modules/OverlayFactory.cpp	(revision 11885)
+++ source/ariba/overlay/modules/OverlayFactory.cpp	(revision 12060)
@@ -41,5 +41,5 @@
 // structured overlays
 #include "chord/Chord.h"
-#include "onehop/OneHop.h"
+//#include "onehop/OneHop.h"  //DEPRECATED
 
 namespace ariba {
@@ -57,11 +57,17 @@
 			return new Chord( baseoverlay, nodeid, routeReceiver, param );
 
-		case OverlayParameterSet::OverlayStructureOneHop:
-			return new OneHop( baseoverlay, nodeid, routeReceiver, param );
+//		case OverlayParameterSet::OverlayStructureOneHop:
+//			return new OneHop( baseoverlay, nodeid, routeReceiver, param );
 
 		default:
+		    // NEVER return "NULL"
+		    assert(false);
+		    throw 42;
 			return NULL;
 	}
 
+	// NEVER return "NULL"
+	assert(false);
+	throw 42;
 	return NULL;
 }
Index: source/ariba/overlay/modules/OverlayInterface.cpp
===================================================================
--- source/ariba/overlay/modules/OverlayInterface.cpp	(revision 11885)
+++ source/ariba/overlay/modules/OverlayInterface.cpp	(revision 12060)
@@ -68,4 +68,5 @@
 
 void OverlayInterface::onLinkFail(const LinkID& lnk, const NodeID& remote) {
+    onLinkDown(lnk, remote);
 }
 
@@ -79,5 +80,7 @@
 }
 
-void OverlayInterface::onMessage(const DataMessage& msg, const NodeID& remote,
+void OverlayInterface::onMessage(OverlayMsg* msg,
+        reboost::shared_buffer_t sub_msg,
+        const NodeID& remote,
 		const LinkID& lnk) {
 }
Index: source/ariba/overlay/modules/OverlayInterface.h
===================================================================
--- source/ariba/overlay/modules/OverlayInterface.h	(revision 11885)
+++ source/ariba/overlay/modules/OverlayInterface.h	(revision 12060)
@@ -145,5 +145,26 @@
 	 */
 	virtual const LinkID& getNextLinkId( const NodeID& id ) const = 0;
-	
+
+    /**
+     * Returns link ids of possible next hops a route message could take,
+     * sorted by "quality" (e.g. overlay-distance).
+     *
+     * The Â»numÂ« parameter can be used to specify the desired number of elements 
+     * in the returned vector. This is intendet for optimizations. The
+     * implementation may choose to return a different number of elements than
+     * requested.
+     * 
+     * NOTE: The returned vector may contain Â»unspecifiedÂ« links. These refer to 
+     * to the own node. (e.g. If there's no closer node, the top element in the 
+     * returned vector is unsoecified.)
+     * 
+     * @param id The destination node id
+     * @param num The desired number of elements in the returned vector.
+     *            (0 means Â»not specified/max)Â«
+     * @return A sorted vector of link ids to possible next hops.
+     */
+    virtual std::vector<const LinkID*> getSortedLinkIdsTowardsNode(
+        const NodeID& id, int num = 0 ) const = 0;
+
 	/**
 	 * Returns the NodeID of the next hop a route message would take.
@@ -176,5 +197,7 @@
 
 	/// @see CommunicationListener
-	virtual void onMessage(const DataMessage& msg, const NodeID& remote,
+	virtual void onMessage(OverlayMsg* msg,
+	        reboost::shared_buffer_t sub_msg,
+	        const NodeID& remote,
 			const LinkID& lnk = LinkID::UNSPECIFIED);
 
Index: source/ariba/overlay/modules/OverlayStructureEvents.h
===================================================================
--- source/ariba/overlay/modules/OverlayStructureEvents.h	(revision 11885)
+++ source/ariba/overlay/modules/OverlayStructureEvents.h	(revision 12060)
@@ -41,7 +41,9 @@
 
 #include "ariba/utility/types/NodeID.h"
-#include "ariba/utility/messages.h"
+#include "ariba/utility/types/LinkID.h"
+#include "ariba/utility/messages/Message.h"
 
 using ariba::utility::NodeID;
+using ariba::utility::LinkID;
 using ariba::utility::Message;
 
@@ -50,9 +52,9 @@
 
 class OverlayInterface;
-class OneHop;
+//class OneHop;
 
 class OverlayStructureEvents {
 	friend class ariba::overlay::OverlayInterface;
-	friend class ariba::overlay::OneHop;
+//	friend class ariba::overlay::OneHop;
 
 public:
Index: source/ariba/overlay/modules/chord/Chord.cpp
===================================================================
--- source/ariba/overlay/modules/chord/Chord.cpp	(revision 11885)
+++ source/ariba/overlay/modules/chord/Chord.cpp	(revision 12060)
@@ -43,5 +43,5 @@
 #include "detail/chord_routing_table.hpp"
 
-#include "messages/Discovery.h"
+//#include "messages/Discovery.h"  // XXX DEPRECATED
 
 namespace ariba {
@@ -55,5 +55,60 @@
 typedef chord_routing_table::item route_item;
 
+using ariba::transport::system_priority;
+
 use_logging_cpp( Chord );
+
+
+////// Messages
+struct DiscoveryMessage
+{
+    /**
+     * DiscoveryMessage
+     * - type
+     * - data
+     * - Endpoint
+     */
+
+    // type enum
+    enum type_ {
+        invalid = 0,
+        normal = 1,
+        successor = 2,
+        predecessor = 3
+    };
+
+    
+    // data
+    uint8_t type;
+    uint8_t ttl;
+    EndpointDescriptor endpoint;
+
+    // serialize
+    reboost::message_t serialize()
+    {
+        // serialize endpoint
+        reboost::message_t msg = endpoint.serialize();
+        
+        // serialize type and ttl
+        uint8_t* buff1 = msg.push_front(2*sizeof(uint8_t)).mutable_data();
+        buff1[0] = type;
+        buff1[1] = ttl;
+        
+        return msg;
+    }
+    
+    //deserialize
+    reboost::shared_buffer_t deserialize(reboost::shared_buffer_t buff)
+    {
+        // deserialize type and ttl
+        const uint8_t* bytes = buff.data();
+        type = bytes[0];
+        ttl = bytes[1];
+        
+        // deserialize endpoint
+        return endpoint.deserialize(buff(2*sizeof(uint8_t)));
+    }
+};
+
 
 Chord::Chord(BaseOverlay& _baseoverlay, const NodeID& _nodeid,
@@ -102,7 +157,22 @@
 
 /// helper: sends a message using the "base overlay"
-seqnum_t Chord::send( OverlayMsg* msg, const LinkID& link ) {
-	if (link.isUnspecified()) return 0;
-	return baseoverlay.send_link( msg, link );
+void Chord::send( OverlayMsg* msg, const LinkID& link ) {
+	if (link.isUnspecified())
+        return;
+    
+	baseoverlay.send_link( msg, link, system_priority::OVERLAY );
+}
+
+void Chord::send_node( OverlayMsg* message, const NodeID& remote )
+{
+    try
+    {
+        baseoverlay.send( message, remote, system_priority::OVERLAY );
+    }
+    catch ( message_not_sent& e )
+    {
+        logging_warn("Chord: Could not send message to " << remote
+                << ": " << e.what());
+    }
 }
 
@@ -116,20 +186,44 @@
 	OverlayMsg msg( typeDiscovery );
 	msg.setRegisterRelay(true);
-	Discovery dmsg( Discovery::normal, (uint8_t)ttl, baseoverlay.getEndpointDescriptor() );
-	msg.encapsulate(&dmsg);
+	
+	// create DiscoveryMessage
+	DiscoveryMessage dmsg;
+	dmsg.type = DiscoveryMessage::normal;
+	dmsg.ttl = ttl;
+	dmsg.endpoint = baseoverlay.getEndpointDescriptor();
+
+	msg.set_payload_message(dmsg.serialize());
 
 	// send to node
-	baseoverlay.send_node( &msg, remote );
+    try
+    {
+        baseoverlay.send_node( &msg, remote, system_priority::OVERLAY );
+    }
+    catch ( message_not_sent& e )
+    {
+        logging_warn("Chord: Could not send message to " << remote
+                << ": " << e.what());
+    }
 }
 
 void Chord::discover_neighbors( const LinkID& link ) {
 	uint8_t ttl = 1;
+	
+    // FIXME try-catch for the send operations
+    
+    // create DiscoveryMessage
+    DiscoveryMessage dmsg;
+    dmsg.ttl = ttl;
+    dmsg.endpoint = baseoverlay.getEndpointDescriptor();
 	{
 		// send predecessor discovery
 		OverlayMsg msg( typeDiscovery );
 		msg.setRegisterRelay(true);
-		Discovery dmsg( Discovery::predecessor, ttl,
-			baseoverlay.getEndpointDescriptor() );
-		msg.encapsulate(&dmsg);
+
+		// set type
+	    dmsg.type = DiscoveryMessage::predecessor;
+
+	    // send
+	    msg.set_payload_message(dmsg.serialize());
 		send(&msg, link);
 	}
@@ -137,9 +231,12 @@
 		// send successor discovery
 		OverlayMsg msg( typeDiscovery );
-		msg.setSourceEndpoint( baseoverlay.getEndpointDescriptor() );
+//		msg.setSourceEndpoint( baseoverlay.getEndpointDescriptor() );  // XXX this was redundand, wasn't it?
 		msg.setRegisterRelay(true);
-		Discovery dmsg( Discovery::successor, ttl,
-			baseoverlay.getEndpointDescriptor() );
-		msg.encapsulate(&dmsg);
+
+		// set type
+        dmsg.type = DiscoveryMessage::successor;
+
+        // send
+        msg.set_payload_message(dmsg.serialize());
 		send(&msg, link);
 	}
@@ -163,5 +260,6 @@
 
 	// timer for stabilization management
-	Timer::setInterval(1000);
+//	Timer::setInterval(1000);  // TODO find an appropriate interval!
+	Timer::setInterval(10000);  // XXX testing...
 	Timer::start();
 }
@@ -200,4 +298,48 @@
 	return item->info;
 }
+
+std::vector<const LinkID*> Chord::getSortedLinkIdsTowardsNode(
+    const NodeID& id, int num ) const
+{
+    std::vector<const LinkID*> ret;
+    
+    switch ( num )
+    {
+        // special case: just call Â»getNextLinkIdÂ«
+        case 1:
+        {
+            ret.push_back(&getNextLinkId(id));
+            
+            break;
+        }
+        
+        // * calculate top 2 *
+        case 0:
+        case 2:
+        {
+            std::vector<const route_item*> items = table->get_next_2_hops(id);
+            
+            ret.reserve(items.size());
+            
+            BOOST_FOREACH( const route_item* item, items )
+            {
+                ret.push_back(&item->info);
+            }
+            
+            break;
+        }
+        
+        // NOTE: implement real sorting, if needed (and handle "case 0" properly, then)
+        default:
+        {
+            throw std::runtime_error("Not implemented. (Chord::getSortedLinkIdsTowardsNode with num != 2)");
+            
+            break;
+        }
+    }
+    
+    return ret;
+}
+
 
 /// @see OverlayInterface.h
@@ -253,4 +395,5 @@
 	if (remote==nodeid) {
 		logging_warn("dropping link that has been established to myself (nodes have same nodeid?)");
+		logging_warn("NodeID: " << remote);
 		baseoverlay.dropLink(lnk);
 		return;
@@ -290,5 +433,6 @@
 /// @see CommunicationListener.h or @see OverlayInterface.h
 void Chord::onLinkDown(const LinkID& lnk, const NodeID& remote) {
-	logging_debug("link_down: link=" << lnk.toString() << " remote=" <<
+    // XXX logging_debug
+	logging_info("link_down (Chord): link=" << lnk.toString() << " remote=" <<
 			remote.toString() );
 
@@ -303,23 +447,24 @@
 /// @see CommunicationListener.h
 /// @see OverlayInterface.h
-void Chord::onMessage(const DataMessage& msg, const NodeID& remote,
+void Chord::onMessage(OverlayMsg* msg,
+        reboost::shared_buffer_t sub_msg,
+        const NodeID& remote,
 		const LinkID& link) {
 
-	// decode message
-	OverlayMsg* m = dynamic_cast<OverlayMsg*>(msg.getMessage());
-	if (m == NULL) return;
-
 	// handle messages
-	switch ((signalMessageTypes)m->getType()) {
+	switch ((signalMessageTypes) msg->getType()) {
 
 	// discovery request
-	case typeDiscovery: {
-		// decapsulate message
-		Discovery* dmsg = m->decapsulate<Discovery> ();
+	case typeDiscovery:
+	{
+		// deserialize discovery message
+		DiscoveryMessage dmsg;
+		dmsg.deserialize(sub_msg);
+		
 		logging_debug("Received discovery message with"
-			    << " src=" << m->getSourceNode().toString()
-				<< " dst=" << m->getDestinationNode().toString()
-				<< " ttl=" << (int)dmsg->getTTL()
-				<< " type=" << (int)dmsg->getType()
+			    << " src=" << msg->getSourceNode().toString()
+				<< " dst=" << msg->getDestinationNode().toString()
+				<< " ttl=" << (int)dmsg.ttl
+				<< " type=" << (int)dmsg.type
 		);
 
@@ -327,108 +472,125 @@
 		bool found = false;
 		BOOST_FOREACH( NodeID& value, discovery )
-			if (value == m->getSourceNode()) {
+			if (value == msg->getSourceNode()) {
 				found = true;
 				break;
 			}
-		if (!found) discovery.push_back(m->getSourceNode());
+		if (!found) discovery.push_back(msg->getSourceNode());
 
 		// check if source node can be added to routing table and setup link
-		if (m->getSourceNode() != nodeid)
-			setup( dmsg->getEndpoint(), m->getSourceNode() );
+		if (msg->getSourceNode() != nodeid)
+			setup( dmsg.endpoint, msg->getSourceNode() );
 
 		// process discovery message -------------------------- switch start --
-		switch (dmsg->getType()) {
-
-		// normal: route discovery message like every other message
-		case Discovery::normal: {
-			// closest node? yes-> split to follow successor and predecessor
-			if ( table->is_closest_to(m->getDestinationNode()) ) {
-				logging_debug("Discovery split:");
-				if (!table->get_successor()->isUnspecified()) {
-					OverlayMsg omsg(*m);
-					dmsg->setType(Discovery::successor);
-					omsg.encapsulate(dmsg);
-					logging_debug("* Routing to successor "
-							<< table->get_successor()->toString() );
-					baseoverlay.send( &omsg, *table->get_successor() );
-				}
-
-				// send predecessor message
-				if (!table->get_predesessor()->isUnspecified()) {
-					OverlayMsg omsg(*m);
-					dmsg->setType(Discovery::predecessor);
-					omsg.encapsulate(dmsg);
-					logging_debug("* Routing to predecessor "
-							<< table->get_predesessor()->toString() );
-					baseoverlay.send( &omsg, *table->get_predesessor() );
-				}
-			}
-			// no-> route message
-			else {
-				baseoverlay.route( m );
-			}
-			break;
-		}
-
-		// successor mode: follow the successor until TTL is zero
-		case Discovery::successor:
-		case Discovery::predecessor: {
-			// reached destination? no->forward!
-			if (m->getDestinationNode() != nodeid) {
-				OverlayMsg omsg(*m);
-				omsg.encapsulate(dmsg);
-				omsg.setService(OverlayInterface::OVERLAY_SERVICE_ID);
-				baseoverlay.route( &omsg );
-				break;
-			}
-
-			// time to live ended? yes-> stop routing
-			if (dmsg->getTTL() == 0 || dmsg->getTTL() > 10) break;
-
-			// decrease time-to-live
-			dmsg->setTTL(dmsg->getTTL() - 1);
-
-			const route_item* item = NULL;
-			if (dmsg->getType() == Discovery::successor &&
-					table->get_successor() != NULL) {
-				item = table->get(*table->get_successor());
-			} else {
-				if (table->get_predesessor()!=NULL)
-					item = table->get(*table->get_predesessor());
-			}
-			if (item == NULL)
-				break;
-
-			logging_debug("Routing discovery message to succ/pred "
-				<< item->id.toString() );
-			OverlayMsg omsg(*m);
-			omsg.encapsulate(dmsg);
-			omsg.setDestinationNode(item->id);
-			omsg.setService(OverlayInterface::OVERLAY_SERVICE_ID);
-			baseoverlay.send(&omsg, omsg.getDestinationNode());
-			break;
-		}
-		case Discovery::invalid:
-			break;
-
-		default:
-			break;
-		}
-		// process discovery message ---------------------------- switch end --
-
-		delete dmsg;
-		break;
-	}
-
-	// leave
-	case typeLeave: {
-		if (link!=LinkID::UNSPECIFIED) {
-			route_item* item = table->get(remote);
-			if (item!=NULL) item->info = LinkID::UNSPECIFIED;
-			table->remove(remote);
-			baseoverlay.dropLink(link);
-		}
-		break;
-	}}
+		switch ( dmsg.type )
+		{
+            // normal: route discovery message like every other message
+            case DiscoveryMessage::normal:
+            {
+                // closest node? yes-> split to follow successor and predecessor
+                if ( table->is_closest_to(msg->getDestinationNode()) )
+                {
+                    logging_debug("Discovery split:");
+                    if (!table->get_successor()->isUnspecified())
+                    {
+                        OverlayMsg omsg(*msg);
+                        
+                        dmsg.type = DiscoveryMessage::successor;
+                        omsg.set_payload_message(dmsg.serialize());
+
+                        logging_debug("* Routing to successor "
+                                << table->get_successor()->toString() );
+                        send_node( &omsg, *table->get_successor() );
+                    }
+    
+                    // send predecessor message
+                    if (!table->get_predesessor()->isUnspecified())
+                    {
+                        OverlayMsg omsg(*msg);
+                        
+                        dmsg.type = DiscoveryMessage::predecessor;
+                        omsg.set_payload_message(dmsg.serialize());
+
+                        logging_debug("* Routing to predecessor "
+                                << table->get_predesessor()->toString() );
+                        send_node( &omsg, *table->get_predesessor() );
+                    }
+                }
+                // no-> route message
+                else
+                {
+                    baseoverlay.route( msg );
+                }
+                break;
+            }
+    
+            // successor mode: follow the successor until TTL is zero
+            case DiscoveryMessage::successor:
+            case DiscoveryMessage::predecessor:
+            {
+                // reached destination? no->forward!
+                if (msg->getDestinationNode() != nodeid)
+                {
+                    OverlayMsg omsg(*msg);
+                    omsg.setService(OverlayInterface::OVERLAY_SERVICE_ID);
+                    
+                    omsg.set_payload_message(dmsg.serialize());
+                    
+                    baseoverlay.route( &omsg );
+                    break;
+                }
+    
+                // time to live ended? yes-> stop routing
+                if (dmsg.ttl == 0 || dmsg.ttl > 10) break;
+    
+                // decrease time-to-live
+                dmsg.ttl--;
+    
+                const route_item* item = NULL;
+                if (dmsg.type == DiscoveryMessage::successor &&
+                        table->get_successor() != NULL)
+                {
+                    item = table->get(*table->get_successor());
+                }
+                else if (table->get_predesessor() != NULL)
+                {
+                        item = table->get(*table->get_predesessor());
+                }
+                if (item == NULL)
+                    break;
+    
+                logging_debug("Routing discovery message to succ/pred "
+                    << item->id.toString() );
+                OverlayMsg omsg(*msg);
+                omsg.setService(OverlayInterface::OVERLAY_SERVICE_ID);
+                omsg.setDestinationNode(item->id);
+                
+                omsg.set_payload_message(dmsg.serialize());
+                
+                send_node( &omsg, omsg.getDestinationNode() );
+                break;
+            }
+            case DiscoveryMessage::invalid:
+                break;
+    
+            default:
+                break;
+            }
+            // process discovery message ---------------------------- switch end --
+    
+            break;
+        }
+    
+        // leave
+        case typeLeave: {
+            if (link!=LinkID::UNSPECIFIED) {
+                route_item* item = table->get(remote);
+                if (item!=NULL) item->info = LinkID::UNSPECIFIED;
+                table->remove(remote);
+                baseoverlay.dropLink(link);
+            }
+            break;
+        }
+	}
 }
 
Index: source/ariba/overlay/modules/chord/Chord.h
===================================================================
--- source/ariba/overlay/modules/chord/Chord.h	(revision 11885)
+++ source/ariba/overlay/modules/chord/Chord.h	(revision 12060)
@@ -45,4 +45,5 @@
 #include "../OverlayInterface.h"
 #include <vector>
+#include <stdexcept>
 
 class chord_routing_table;
@@ -87,7 +88,10 @@
 		const NodeID& node = NodeID::UNSPECIFIED );
 
-	// helper: sends a message using the "base overlay"
-	seqnum_t send( OverlayMsg* msg, const LinkID& link );
+	// helper: sends a message over a link using the "base overlay"
+	void send( OverlayMsg* msg, const LinkID& link );
 
+	// helper: sends a message to a node using the "base overlay"
+	void send_node( OverlayMsg* message, const NodeID& remote );
+	        
 	// stabilization: sends a discovery message to the specified neighborhood
 	void send_discovery_to( const NodeID& destination, int ttl = 3 );
@@ -105,4 +109,9 @@
 	virtual const LinkID& getNextLinkId( const NodeID& id ) const;
 	
+    /// @see OverlayInterface.h
+    /// NOTE: This implementation excepts num == 2
+    virtual std::vector<const LinkID*> getSortedLinkIdsTowardsNode(
+        const NodeID& id, int num = 0 ) const;
+
 	/// @see OverlayInterface.h
 	virtual const NodeID& getNextNodeId( const NodeID& id ) const;
@@ -138,5 +147,7 @@
 
 	/// @see CommunicationListener.h or @see OverlayInterface.h
-	virtual void onMessage(const DataMessage& msg, const NodeID& remote,
+	virtual void onMessage(OverlayMsg* msg,
+	        reboost::shared_buffer_t sub_msg,
+	        const NodeID& remote,
 			const LinkID& lnk = LinkID::UNSPECIFIED);
 
Index: source/ariba/overlay/modules/chord/detail/chord_routing_table.hpp
===================================================================
--- source/ariba/overlay/modules/chord/detail/chord_routing_table.hpp	(revision 11885)
+++ source/ariba/overlay/modules/chord/detail/chord_routing_table.hpp	(revision 12060)
@@ -96,4 +96,7 @@
 	// the own node id
 	nodeid_t id;
+    
+    // the own node id as routing item
+    item own_id_item;
 
 	// successor and predecessor tables
@@ -168,6 +171,11 @@
 	/// constructs the reactive chord routing table
 	explicit chord_routing_table( const nodeid_t& id, int redundancy = 4 ) :
-		id(id),	succ( redundancy, succ_compare_type(this->id), *this ),
-		pred( redundancy, pred_compare_type(this->id), *this ) {
+		id(id),
+		succ( redundancy, succ_compare_type(this->id), *this ),
+		pred( redundancy, pred_compare_type(this->id), *this )
+    {
+        // init reflexive item
+        own_id_item.id = id;
+        own_id_item.ref_count = 1;
 
 		// create finger tables
@@ -273,16 +281,68 @@
 			}
 		}
+
 		if (best_item != NULL && distance(value, id)<distance(value, best_item->id))
 			return NULL;
 		return best_item;
 	}
+	
+	std::vector<const item*> get_next_2_hops( const nodeid_t& value)
+    {
+        ring_distance distance;
+        item* best_item = &own_id_item;
+        item* second_best_item = NULL;
+        
+        // find best and second best item
+        for (size_t i=0; i<table.size(); i++)
+        {
+            item* curr = &table[i];
+
+            // not not include orphans into routing!
+            if (curr->ref_count==0) continue;
+
+            // check if we found a better item
+            // is best item
+            if ( distance(value, curr->id) < distance(value, best_item->id) )
+            {
+                second_best_item = best_item;
+                best_item = curr;
+            }
+            // is second best item
+            else
+            {
+                if ( second_best_item == NULL )
+                {
+                    second_best_item = curr;
+                    continue;
+                }
+                
+                if ( distance(value, curr->id) < distance(value, second_best_item->id) )
+                {
+                    second_best_item = curr;
+                }
+            }
+        }
+
+        // prepare return vector
+        std::vector<const item*> ret;
+        if ( best_item != NULL )
+        {
+            ret.push_back(best_item);
+        }
+        if ( second_best_item != NULL )
+        {
+            ret.push_back(second_best_item);
+        }
+        
+        return ret;
+    }
 
 	const nodeid_t* get_successor() {
-		if (succ.size()==NULL) return NULL;
+		if (succ.size()==0) return NULL;
 		return &succ.front();
 	}
 
 	const nodeid_t* get_predesessor() {
-		if (pred.size()==NULL) return NULL;
+		if (pred.size()==0) return NULL;
 		return &pred.front();
 	}
Index: source/ariba/overlay/modules/chord/messages/CMakeLists.txt
===================================================================
--- source/ariba/overlay/modules/chord/messages/CMakeLists.txt	(revision 11885)
+++ source/ariba/overlay/modules/chord/messages/CMakeLists.txt	(revision 12060)
@@ -37,5 +37,5 @@
 # [License]
 
-add_headers(Discovery.h)
+#add_headers(Discovery.h)
 
-add_sources(Discovery.cpp)
+#add_sources(Discovery.cpp)
Index: source/ariba/overlay/modules/chord/messages/Discovery.h
===================================================================
--- source/ariba/overlay/modules/chord/messages/Discovery.h	(revision 11885)
+++ source/ariba/overlay/modules/chord/messages/Discovery.h	(revision 12060)
@@ -59,4 +59,5 @@
 using_serialization;
 
+// XXX This whole message is DEPRECATED
 class Discovery : public Message {
 	VSERIALIZEABLE;
Index: source/ariba/overlay/modules/onehop/CMakeLists.txt
===================================================================
--- source/ariba/overlay/modules/onehop/CMakeLists.txt	(revision 11885)
+++ source/ariba/overlay/modules/onehop/CMakeLists.txt	(revision 12060)
@@ -37,7 +37,9 @@
 # [License]
 
-add_headers(OneHop.h)
 
-add_sources(OneHop.cpp)
+## DEPRECATED
+#add_headers(OneHop.h)
 
-add_subdir_sources(messages)
+#add_sources(OneHop.cpp)
+
+#add_subdir_sources(messages)
Index: source/ariba/utility/CMakeLists.txt
===================================================================
--- source/ariba/utility/CMakeLists.txt	(revision 11885)
+++ source/ariba/utility/CMakeLists.txt	(revision 12060)
@@ -45,9 +45,9 @@
 add_subdir_sources(
     addressing
+    addressing2
     bootstrap
     configuration
     internal
     logging
-    measurement
     messages
     misc
Index: source/ariba/utility/addressing/endpoint_set.hpp
===================================================================
--- source/ariba/utility/addressing/endpoint_set.hpp	(revision 11885)
+++ source/ariba/utility/addressing/endpoint_set.hpp	(revision 12060)
@@ -1,4 +1,4 @@
-#ifndef ENDPOINT_SET_HPP_
-#define ENDPOINT_SET_HPP_
+#ifndef ENDPOINT_SET_HPP_DEPRECATED_
+#define ENDPOINT_SET_HPP_DEPRECATED_
 
 #include "addressing.hpp"
Index: source/ariba/utility/addressing/facades/address_v.hpp
===================================================================
--- source/ariba/utility/addressing/facades/address_v.hpp	(revision 11885)
+++ source/ariba/utility/addressing/facades/address_v.hpp	(revision 12060)
@@ -13,4 +13,6 @@
 
 #include "../detail/address_convenience.hpp"
+
+#include <boost/shared_ptr.hpp>
 
 namespace ariba {
@@ -26,4 +28,6 @@
 class address_v: public detail::address_convenience<address_v> {
 public:
+    typedef boost::shared_ptr<address_v> shared_ptr;
+    
 	virtual ~address_v() {}
 	
Index: source/ariba/utility/addressing/ip_address.hpp
===================================================================
--- source/ariba/utility/addressing/ip_address.hpp	(revision 11885)
+++ source/ariba/utility/addressing/ip_address.hpp	(revision 12060)
@@ -1,4 +1,4 @@
-#ifndef IP_ADDRESS_HPP_
-#define IP_ADDRESS_HPP_
+#ifndef IP_ADDRESS_HPP_DEPRECATED_
+#define IP_ADDRESS_HPP_DEPRECATED_
 
 #include <string>
Index: source/ariba/utility/addressing/tcpip_endpoint.hpp
===================================================================
--- source/ariba/utility/addressing/tcpip_endpoint.hpp	(revision 11885)
+++ source/ariba/utility/addressing/tcpip_endpoint.hpp	(revision 12060)
@@ -1,4 +1,4 @@
-#ifndef TCPIP_ENDPOINT_HPP_
-#define TCPIP_ENDPOINT_HPP_
+#ifndef TCPIP_ENDPOINT_HPP_DEPRECATED_
+#define TCPIP_ENDPOINT_HPP_DEPRECATED_
 
 #include<string>
Index: source/ariba/utility/addressing2/CMakeLists.txt
===================================================================
--- source/ariba/utility/addressing2/CMakeLists.txt	(revision 12060)
+++ source/ariba/utility/addressing2/CMakeLists.txt	(revision 12060)
@@ -0,0 +1,48 @@
+# [License]
+# The Ariba-Underlay Copyright
+#
+# Copyright (c) 2008-2012, Institute of Telematics, UniversitÃ€t Karlsruhe (TH)
+#
+# Institute of Telematics
+# UniversitÃ€t Karlsruhe (TH)
+# Zirkel 2, 76128 Karlsruhe
+# Germany
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OF TELEMATICS OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# The views and conclusions contained in the software and documentation
+# are those of the authors and should not be interpreted as representing
+# official policies, either expressed or implied, of the Institute of
+# Telematics.
+# [License]
+
+add_headers(
+    endpoint.hpp
+    endpoint_set.hpp
+    tcpip_endpoint.hpp
+)
+
+add_sources(
+    endpoint_set.cpp
+    tcpip_endpoint.cpp
+)
Index: source/ariba/utility/addressing2/endpoint.hpp
===================================================================
--- source/ariba/utility/addressing2/endpoint.hpp	(revision 12060)
+++ source/ariba/utility/addressing2/endpoint.hpp	(revision 12060)
@@ -0,0 +1,79 @@
+/*
+ * endpoint.h
+ *
+ *  Created on: 26.03.2013
+ *      Author: mario
+ */
+
+#ifndef ENDPOINT_HPP_
+#define ENDPOINT_HPP_
+
+// system
+#include <stdint.h>
+#include <string>
+
+// boost
+#include <boost/shared_ptr.hpp>
+
+namespace ariba {
+namespace addressing2 {
+
+struct endpoint_category
+{
+    enum _ENDPOINT_CATEGORY {
+        INVALID = 0,
+        TCPIP = 1,
+        BLUETOOTH = 2
+    };
+    
+//    static const SEND_PRIORITY_INTERNAL OVERLAY = HIGHEST;
+};
+typedef endpoint_category::_ENDPOINT_CATEGORY ENDPOINT_CATEGORY;
+
+struct endpoint_type
+{
+    enum _ENDPOINT_TYPE {
+        INVALID = 0,
+        TCPIPv4 = 1,
+        TCPIPv6 = 2
+    };
+};
+typedef endpoint_type::_ENDPOINT_TYPE ENDPOINT_TYPE;
+
+
+class endpoint
+{
+public:
+    virtual ~endpoint() {}
+    
+    virtual ENDPOINT_CATEGORY get_category() const = 0;
+    virtual ENDPOINT_TYPE get_type() const = 0;
+    
+    /**
+     * @return Human readable string representation of this endpoint.
+     */
+    virtual std::string to_string() const = 0;
+    
+    /**
+     * Serializes this Â»endpointÂ« into a byte_array.
+     * 
+     * @param buffer: An array >= Â»endpoint::size()Â«
+     * @return Â»endpoint::size()Â«
+     */
+    virtual size_t to_byte_array(uint8_t* buffer) const = 0;
+    
+    /**
+     * @return Number of bytes:
+     *   - read in Â»endpoint::endpoint(const uint8_t* byte_array);Â«
+     *   - to be written in Â»endpoint::to_byte_array(uint8_t* buffer)Â«
+     */
+    virtual int size() const = 0;
+};
+
+typedef boost::shared_ptr<endpoint> EndpointPtr;
+//typedef boost::shared_ptr<const endpoint> const_EndpointPtr;
+
+// NOTE: An endpoint is designed as an unmutable object!
+
+}} /* namespace ariba::addressing2 */
+#endif /* ENDPOINT_HPP_ */
Index: source/ariba/utility/addressing2/endpoint_set.cpp
===================================================================
--- source/ariba/utility/addressing2/endpoint_set.cpp	(revision 12060)
+++ source/ariba/utility/addressing2/endpoint_set.cpp	(revision 12060)
@@ -0,0 +1,344 @@
+/*
+ * endpointset.cpp
+ *
+ *  Created on: 27.03.2013
+ *      Author: mario
+ */
+
+#include "endpoint_set.hpp"
+
+// ariba endpoints
+#include "tcpip_endpoint.hpp"
+
+// boost
+#include <boost/foreach.hpp>
+#include <boost/property_tree/json_parser.hpp>
+
+#include <limits>
+
+namespace ariba {
+namespace addressing2 {
+
+using namespace std;
+using boost::property_tree::ptree;
+
+// TODO maybe this function wants to go in a distinct header..
+template <class T>
+T read_from_byte_array(const uint8_t*& buff, int& read_max)
+{
+    assert ( sizeof(T) <= read_max );
+    
+    const uint8_t* b1 = buff;
+    buff += sizeof(T);
+    read_max -= sizeof(T);
+    
+    return *( reinterpret_cast<const T *>(b1) );
+}
+
+
+/* factories */
+//shared_ptr<endpoint_set> endpoint_set::create_EndpointSet(const std::string & str)
+//{
+//    EndpointSetPtr set(new endpoint_set(str));
+//    
+//    return set;
+//}
+
+shared_ptr<endpoint_set> endpoint_set::create_EndpointSet(const ptree& pt)
+{
+    EndpointSetPtr set(new endpoint_set(pt));
+    
+    return set;
+}
+
+shared_ptr<endpoint_set> endpoint_set::create_EndpointSet()
+{
+    EndpointSetPtr set(new endpoint_set());
+    
+    return set;
+}
+
+
+
+endpoint_set::endpoint_set()
+{
+}
+
+endpoint_set::endpoint_set(const ptree& pt)
+{
+    /* create & add endpoints */
+    BOOST_FOREACH( const ptree::value_type& child, pt )
+    {
+        string cat = child.second.get<string>("category");
+        
+        // TCPIP
+        if ( cat == "TCPIP" )
+        {
+            string addr = child.second.get<string>("addr");
+            int port = child.second.get<int>("port");
+            
+            TcpIP_EndpointPtr endp(new tcpip_endpoint(addr, port));
+            
+            tcpip_endpoints.push_back(endp);
+        }
+        
+        // TODO else if bluetooth
+    }
+}
+
+//endpoint_set::endpoint_set(const string& str)
+//{
+//    // TODO see endpoint_set(const ptree& pt)
+//    
+//    
+//    ptree pt;
+//    
+//    /* parse input string */
+//    // input string format is: JSON
+//    if (str.substr(0, 4) == "JSON")
+//    {
+//        istringstream sstream(str.substr(4, string::npos));
+//        boost::property_tree::json_parser::read_json(sstream, pt);
+//    }
+//    // --- other formats can be supported here (e.g. XML) ---
+//    else
+//    {
+//        throw invalid_argument("Could not parse endpoint_set from string.");
+//    }
+//    
+//
+//    
+//    /* create & add endpoints */
+//    BOOST_FOREACH(const ptree::value_type& child, pt.get_child("endpoint_set"))
+//    {
+//        string cat = child.second.get<string>("category");
+//        
+//        // TCPIP
+//        if ( cat == "TCPIP" )
+//        {
+//            string addr = child.second.get<string>("addr");
+//            int port = child.second.get<int>("port");
+//            
+//            TcpIP_EndpointPtr endp(new tcpip_endpoint(addr, port));
+//            
+//            tcpip_endpoints.push_back(endp);
+//        }
+//        
+//        // TODO else if bluetooth
+//    }
+//}
+
+endpoint_set::~endpoint_set()
+{
+}
+
+void endpoint_set::add_endpoint(EndpointPtr endpoint)
+{
+    switch ( endpoint->get_category() )
+    {
+        case endpoint_category::TCPIP:
+        {
+            // TODO try-catch --> log a warning
+            shared_ptr<tcpip_endpoint> tcpip_endp =
+                    boost::dynamic_pointer_cast<tcpip_endpoint>(endpoint);
+            
+            // no duplicates
+            bool duplicate = false;
+            BOOST_FOREACH(const shared_ptr<tcpip_endpoint>& x, tcpip_endpoints)
+            {
+                if ( tcpip_endp->equals(x) )
+                {
+                    duplicate = true;
+                    break;
+                }
+            }
+
+            if ( ! duplicate )
+            {
+                // * add *
+                tcpip_endpoints.push_back(tcpip_endp);
+            }
+            
+            break;
+        }
+        
+        default:
+        {
+            // TODO log a warning ^^
+            
+            break;
+        }
+    }
+}
+
+void endpoint_set::add_endpoints(const shared_ptr<endpoint_set> endpoints)
+{
+    // TODO bluetooth, etc....
+    
+    BOOST_FOREACH( EndpointPtr endp, endpoints->get_tcpip_endpoints() )
+    {
+        add_endpoint(endp);
+    }
+}
+
+
+const vector<shared_ptr<tcpip_endpoint> >& endpoint_set::get_tcpip_endpoints() const
+{
+    return tcpip_endpoints;
+}
+
+//const vector<shared_ptr<const tcpip_endpoint> > endpoint_set::get_tcpip_endpoints() const
+//{
+//    vector<shared_ptr<const tcpip_endpoint> > ret;
+//    ret.reserve(tcpip_endpoints.size());
+//    
+//    BOOST_FOREACH( const_TcpIP_EndpointPtr address, tcpip_endpoints )
+//    {
+//        ret.push_back(address);
+//    }
+//            
+//    return ret;
+//}
+
+
+string endpoint_set::to_string() const
+{
+    ostringstream out;
+    
+    BOOST_FOREACH( EndpointPtr endp, tcpip_endpoints )
+    {
+        out << endp->to_string() << "; ";
+    }
+    
+    return out.str();
+}
+
+
+/**
+ * Format:
+ * 
+ * | 16-bit: overall size | + ( | 8 bit: type | + | variable length: endpoint | ) * N
+ *  
+ */
+reboost::shared_buffer_t endpoint_set::serialize() const
+{
+    // TODO bluetooth, etc....
+    
+    /* calculate size */
+    // size: two byte length field
+    size_t overall_size = sizeof(uint16_t);
+    
+    BOOST_FOREACH( EndpointPtr endp, tcpip_endpoints )
+    {
+        // size: endpoint + type
+        overall_size += endp->size() + 1;
+    }
+
+    // overall_size value must fit into 16 bits
+    assert ( overall_size <= numeric_limits<uint16_t>::max() );
+    
+    
+    /* serialize */
+    reboost::shared_buffer_t buff(overall_size);
+    uint8_t* buff_ptr = buff.mutable_data();
+    
+    // overall size
+    memcpy( buff_ptr, &overall_size, sizeof(uint16_t) );
+    buff_ptr += sizeof(uint16_t);
+    
+    // tcpip_endpoints
+    BOOST_FOREACH( EndpointPtr endp, tcpip_endpoints )
+    {
+//        // XXX AKTUELL BUG FINDING...
+//        cout << "  - SERIALIZE:  (" << (int) (buff_ptr - buff.mutable_data()) << ")";
+                
+        // type
+        *buff_ptr = static_cast<uint8_t>(endp->get_type());
+        buff_ptr++;
+        
+        // serialize tcpip_endpoint 
+        buff_ptr += endp->to_byte_array(buff_ptr);
+        
+//        // XXX AKTUELL BUG FINDING...
+//        cout << endp->to_string() << " (" << (int) (buff_ptr - buff.mutable_data()) << ")" << endl;
+    }
+    
+    // boundary check
+    assert( buff_ptr <= buff.mutable_data() + buff.size() );
+    
+    return buff;
+}
+
+reboost::shared_buffer_t endpoint_set::deserialize(reboost::shared_buffer_t buff)
+{
+    assert( tcpip_endpoints.size() == 0);
+    
+    const uint8_t* buff_ptr = buff.data(); // NOTE: the data is const, the pointer is not.
+
+    // read overall size (16 bit value)
+    int bytes_left = sizeof(uint16_t);
+    uint16_t overall_size = read_from_byte_array<uint16_t>(buff_ptr, bytes_left);
+    
+    // check claimed overall size
+    if ( overall_size > buff.size() )
+    {
+        // todo throw
+        cout << endl << "FATAL ERROR in Â»endpoint_set::deserializeÂ«: overall_size > buff.size()" << endl;
+        assert ( false );
+    }
+    
+    // calculate bytes to read
+    bytes_left = overall_size - sizeof(uint16_t);
+    
+    
+    // read endpoints
+    while ( bytes_left > 0 )
+    {
+//        // XXX AKTUELL BUG FINDING...
+//        cout << "  - DESERIALIZE:  (" << (int) (buff_ptr - buff.data()) << ")";
+
+        ENDPOINT_TYPE type = static_cast<ENDPOINT_TYPE>(
+                read_from_byte_array<uint8_t>(buff_ptr, bytes_left) );
+        
+        switch (type)
+        {
+            case endpoint_type::TCPIPv4:
+            case endpoint_type::TCPIPv6:
+            {
+                // TODO try catch
+                TcpIP_EndpointPtr endp(new tcpip_endpoint(type, buff_ptr, bytes_left));
+                add_endpoint(endp);
+
+                // move pointers
+                const int bytes_read = endp->size();
+                buff_ptr += bytes_read;
+                bytes_left -= bytes_read;
+
+                
+//                // XXX AKTUELL BUG FINDING...
+//                cout << endp->to_string() << " (" << (int) (buff_ptr - buff.data()) << ")" << endl;
+
+                break;
+            }
+            
+            // TODO case endpoint_type::bluetooth...:
+            
+            default:
+            {
+                // TODO throw
+                cout << endl << "FATAL ERROR in Â»endpoint_set::deserializeÂ«: Unknown type (" << type << ")" << endl;
+                cout << "BUFFER (size = " << buff.size() << "):" << endl;
+                cout << buff << endl << "-------------------------" << endl;
+                assert(false);
+                break;
+            }
+        }
+        
+        assert( bytes_left >= 0 );
+    }
+    
+    // return sub-buffer
+    return buff(overall_size);
+}
+
+}} /* namespace addressing2::ariba */
Index: source/ariba/utility/addressing2/endpoint_set.hpp
===================================================================
--- source/ariba/utility/addressing2/endpoint_set.hpp	(revision 12060)
+++ source/ariba/utility/addressing2/endpoint_set.hpp	(revision 12060)
@@ -0,0 +1,110 @@
+/*
+ * endpoint_set.hpp
+ *
+ *  Created on: 27.03.2013
+ *      Author: mario
+ */
+
+#ifndef ENDPOINT_SET_HPP_
+#define ENDPOINT_SET_HPP_
+
+// ariba
+#include "endpoint.hpp"
+#include "ariba/utility/transport/messages/shared_buffer.hpp"
+
+// boost
+#include <boost/shared_ptr.hpp>
+#include <boost/property_tree/ptree.hpp>
+
+// system
+#include <vector>
+#include <stdexcept>
+
+namespace ariba {
+
+using boost::property_tree::ptree;
+using boost::shared_ptr;
+
+namespace addressing2 {
+
+/// forward declarations
+class tcpip_endpoint;
+
+/**
+ * Holds a number of endpoints. (Usually of one particular node.)
+ */
+class endpoint_set
+{
+public:
+    
+    // factories
+    static shared_ptr<endpoint_set> create_EndpointSet(const boost::property_tree::ptree& pt);
+//    static shared_ptr<endpoint_set> create_EndpointSet(const std::string& str);
+    static shared_ptr<endpoint_set> create_EndpointSet();
+    
+    endpoint_set();
+    
+//    endpoint_set(const std::string& str);
+    endpoint_set(const boost::property_tree::ptree& pt);
+    virtual ~endpoint_set();
+    
+    
+    /**
+     * Adds an endpoint to this set.
+     * 
+     * (Ignores duplicates)
+     */
+    void add_endpoint(EndpointPtr endpoint);
+    
+    /**
+     * Adds all endpoints from the given set to this set.
+     * 
+     * (Ignores duplicates)
+     */
+    void add_endpoints(const boost::shared_ptr<endpoint_set> endpoints);
+    
+    /**
+     * @return Human readable string representation of this endpoint-set.
+     */
+    std::string to_string() const;
+    
+    /**
+     * @return a vector of all tcpip_endpoints in this set
+     */
+    const std::vector<shared_ptr<tcpip_endpoint> >& get_tcpip_endpoints() const;
+    
+    /**
+     * This function serializes this endpoint_set with all its endpoints
+     * into a shared buffer, which then can be sent to another node.
+     * 
+     * @return A byte-representation of this set saved into a shared_buffer.
+     */
+    reboost::shared_buffer_t serialize() const;
+    
+    /**
+     * Recreates an endpoint_set from a shared buffer.
+     * 
+     * ---> Complementary to Â»endpoint_set::serialize_into_shared_buffer()Â«
+     * 
+     * @return remaining sub-buffer
+     */
+    reboost::shared_buffer_t deserialize(reboost::shared_buffer_t buff);
+
+    
+    /**
+     * @return total number of endpoints in this set
+     */
+    int count() const
+    {
+        return tcpip_endpoints.size();
+    }
+    
+private:
+    std::vector<shared_ptr<tcpip_endpoint> > tcpip_endpoints;
+};
+
+typedef boost::shared_ptr<endpoint_set> EndpointSetPtr;
+typedef boost::shared_ptr<const endpoint_set> const_EndpointSetPtr;
+
+}} /* namespace addressing2::ariba */
+#endif /* ENDPOINT_SET_HPP_ */
Index: source/ariba/utility/addressing2/tcpip_endpoint.cpp
===================================================================
--- source/ariba/utility/addressing2/tcpip_endpoint.cpp	(revision 12060)
+++ source/ariba/utility/addressing2/tcpip_endpoint.cpp	(revision 12060)
@@ -0,0 +1,182 @@
+/*
+ * tcpip_endpoint.cpp
+ *
+ *  Created on: 26.03.2013
+ *      Author: mario
+ */
+
+#include "tcpip_endpoint.hpp"
+
+// system
+#include <sstream>
+#include <stdexcept>
+
+using namespace std;
+using namespace boost::asio::ip;
+
+namespace ariba {
+namespace addressing2 {
+
+#define TCPIPv6_SIZE 18
+#define TCPIPv4_SIZE 6
+
+
+/// factories
+TcpIP_EndpointPtr tcpip_endpoint::create_TcpIP_Endpoint(
+        const tcp::endpoint& asio_endpoint)
+{
+    TcpIP_EndpointPtr ptr(new tcpip_endpoint(asio_endpoint));
+    
+    return ptr;
+}
+
+
+/// constructors
+tcpip_endpoint::tcpip_endpoint(const std::string& ip_addr, const int port)
+{
+    address addr = address::from_string(ip_addr);
+    asio_endpoint = tcp::endpoint(addr, static_cast<uint16_t>(port));
+}
+
+tcpip_endpoint::tcpip_endpoint(const ENDPOINT_TYPE type, const uint8_t* const byte_array, const int read_max)
+{
+    // IPv4
+    if ( type == endpoint_type::TCPIPv4 )
+    {
+        // boundary check
+        if ( read_max < TCPIPv4_SIZE )
+            throw invalid_argument("Not enough bytes to read an TCPIPv4 endpoint.");
+        
+        asio_endpoint = tcp::endpoint( address_v4( *((uint32_t*) byte_array) ),
+                                        *((uint16_t*) (byte_array+sizeof(uint32_t))) );
+    }
+    
+    // IPv6
+    else if ( type == endpoint_type::TCPIPv6 )
+    {
+        // boundary check
+        if ( read_max < TCPIPv6_SIZE )
+            throw invalid_argument("Not enough bytes to read an TCPIPv6 endpoint.");
+
+        address_v6::bytes_type bytes_;
+        for (size_t i=0; i<bytes_.size(); i++)
+        {
+            bytes_[i] = byte_array[i];
+        }
+        
+        asio_endpoint = tcp::endpoint( address_v6(bytes_),
+                                        *((uint16_t*) (byte_array+bytes_.size())) );
+    }
+    
+    // Error
+    else
+    {
+        throw invalid_argument("Corrupt data. Can't deserialize endpoint.");
+    }
+}
+
+tcpip_endpoint::tcpip_endpoint(const tcp::endpoint& asio_endpoint)  :
+        asio_endpoint(asio_endpoint)
+{
+}
+
+
+tcpip_endpoint::~tcpip_endpoint()
+{
+}
+
+
+
+ENDPOINT_CATEGORY tcpip_endpoint::get_category() const
+{
+    return endpoint_category::TCPIP;
+}
+
+ENDPOINT_TYPE tcpip_endpoint::get_type() const
+{
+    // IPv4
+    if ( asio_endpoint.address().is_v4() )
+    {
+        return endpoint_type::TCPIPv4;
+    }
+    
+    // IPv6
+    else if ( asio_endpoint.address().is_v6() )
+    {
+        return endpoint_type::TCPIPv6;
+    }
+
+    // Invalid
+    else
+    {
+        return endpoint_type::INVALID;
+    }
+}
+
+
+std::string tcpip_endpoint::to_string() const
+{
+    ostringstream out;
+    
+    out << asio_endpoint;
+    
+    return out.str();
+}
+
+
+
+size_t tcpip_endpoint::to_byte_array(uint8_t* buffer) const
+{
+    // IPv4
+    if ( asio_endpoint.address().is_v4() )
+    {
+        uint32_t ip = asio_endpoint.address().to_v4().to_ulong();
+        uint16_t port = asio_endpoint.port();
+        
+        memcpy(buffer, &ip, sizeof(uint32_t));
+        memcpy(buffer+sizeof(uint32_t), &port, sizeof(uint16_t));
+        
+        return TCPIPv4_SIZE;
+    }
+    
+    // IPv6
+    else
+    {
+        address_v6::bytes_type bytes_ = asio_endpoint.address().to_v6().to_bytes();
+        
+        for (size_t i=0; i<bytes_.size(); i++)
+        {
+            buffer[i] = bytes_[i];
+        }
+        
+        uint16_t port = asio_endpoint.port();
+        memcpy(buffer+bytes_.size(), &port, sizeof(uint16_t));
+        
+        return TCPIPv6_SIZE;
+    }
+
+}
+
+
+int tcpip_endpoint::size() const
+{
+    // IPv4
+    if ( asio_endpoint.protocol() == tcp::v4() )
+        return TCPIPv4_SIZE;
+    
+    // IPv6
+    else
+        return TCPIPv6_SIZE;
+}
+
+const tcp::endpoint& tcpip_endpoint::to_asio() const
+{
+    return asio_endpoint;
+}
+
+bool tcpip_endpoint::equals(const TcpIP_EndpointPtr& rhs) const
+{
+    return asio_endpoint == rhs->asio_endpoint;
+}
+
+}} /* namespace ariba::addressing2 */
Index: source/ariba/utility/addressing2/tcpip_endpoint.hpp
===================================================================
--- source/ariba/utility/addressing2/tcpip_endpoint.hpp	(revision 12060)
+++ source/ariba/utility/addressing2/tcpip_endpoint.hpp	(revision 12060)
@@ -0,0 +1,92 @@
+/*
+ * tcpip_endpoint.h
+ *
+ *  Created on: 26.03.2013
+ *      Author: mario
+ */
+
+#ifndef TCPIP_ENDPOINT_HPP_
+#define TCPIP_ENDPOINT_HPP_
+
+// TODO: maybe move this class ariba/utility/transport.. ?
+
+#include "endpoint.hpp"
+
+// boost
+#include <boost/asio/ip/tcp.hpp>
+#include <boost/shared_ptr.hpp>
+
+using boost::shared_ptr;
+
+namespace ariba {
+namespace addressing2 {
+
+class tcpip_endpoint: public endpoint
+{
+public:
+    /**
+     * Implements Â»endpointÂ«
+     * @see endpoint.h
+     * 
+     * NOTE: An endpoint is designed as an unmutable object!
+     */
+
+    /// factories
+    static boost::shared_ptr<tcpip_endpoint> create_TcpIP_Endpoint(
+            const boost::asio::ip::tcp::endpoint& asio_endpoint);
+    
+    
+    /// constructors
+    
+    /**
+     * Creates a new Â»tcpip_endpointÂ« from a string representation.
+     * ---> NOT complementary to Â»to_string()Â«
+     */
+    tcpip_endpoint(const std::string& ip_addr, const int port);
+    
+    /**
+     * Creates a new Â»tcpip_endpointÂ« from a byte array.
+     * ---> Complementary to Â»to_byte_array()Â«
+     * 
+     * May throw Â»invalid_argumentÂ« exception.
+     */
+    tcpip_endpoint(const ENDPOINT_TYPE type, const uint8_t* const byte_array, const int read_max);
+    
+    /**
+     * Creates a new Â»tcpip_endpointÂ« from an ASIO tcp::endpoint.
+     * ---> Complementary to Â»tcpip_endpoint::to_asio()Â«
+     */
+    tcpip_endpoint(const boost::asio::ip::tcp::endpoint& asio_endpoint);
+    
+    virtual ~tcpip_endpoint();
+    
+    
+    /// from superclass
+    virtual ENDPOINT_CATEGORY get_category() const;
+    virtual ENDPOINT_TYPE get_type() const;
+    virtual std::string to_string() const;
+    virtual size_t to_byte_array(uint8_t* buffer) const;
+    virtual int size() const;
+    
+    
+    /**
+     * @return An equivalent ASIO tcp::endpoint
+     */
+    const boost::asio::ip::tcp::endpoint& to_asio() const;
+    
+    /**
+     * @return Â»trueÂ« if rhs points to the same Address:Port pair,
+     * otherwise returns Â»falseÂ«.  
+     */
+    bool equals(const shared_ptr<tcpip_endpoint>& rhs) const;
+    
+    
+private:
+    boost::asio::ip::tcp::endpoint asio_endpoint;
+};
+
+typedef boost::shared_ptr<tcpip_endpoint> TcpIP_EndpointPtr;
+//typedef boost::shared_ptr<const tcpip_endpoint> const_TcpIP_EndpointPtr;
+
+}} /* namespace ariba::addressing2 */
+#endif /* TCPIP_ENDPOINT_HPP_ */
Index: source/ariba/utility/bootstrap/modules/periodicbroadcast/PeriodicBroadcast.h
===================================================================
--- source/ariba/utility/bootstrap/modules/periodicbroadcast/PeriodicBroadcast.h	(revision 11885)
+++ source/ariba/utility/bootstrap/modules/periodicbroadcast/PeriodicBroadcast.h	(revision 12060)
@@ -40,21 +40,28 @@
 #define __PERIODIC_BROADCAST_H
 
+// ariba
 #include "ariba/config.h"
-
+#include "ariba/utility/bootstrap/modules/BootstrapModule.h"
+#include "ariba/utility/logging/Logging.h"
+#include "ariba/utility/system/Timer.h"
+
+// ariba messages
+#include "PeriodicBroadcastMessage.h"
+
+// (ariba) link-local
+#include "ariba/utility/transport/StreamTransport/StreamTransport.hpp"
+
+// system
 #include <map>
 #include <string>
 #include <ctime>
 #include <iostream>
+
+// boost
 #include <boost/asio.hpp>
 #include <boost/foreach.hpp>
 #include <boost/thread/mutex.hpp>
 #include <boost/thread/thread.hpp>
-#include "ariba/utility/bootstrap/modules/BootstrapModule.h"
-#include "ariba/utility/logging/Logging.h"
-#include "ariba/utility/system/Timer.h"
-#include "PeriodicBroadcastMessage.h"
-
-//link-local
-#include "ariba/utility/transport/tcpip/tcpip.hpp"
+
 
 using std::map;
@@ -301,5 +308,5 @@
 				
 				// include all link-local interfaces
-				vector<uint64_t> scope_ids = ariba::transport::tcpip::get_interface_scope_ids();
+				vector<uint64_t> scope_ids = ariba::transport::get_interface_scope_ids();
 				
 				BOOST_FOREACH ( uint64_t id, scope_ids )
Index: source/ariba/utility/logging/Logging.h
===================================================================
--- source/ariba/utility/logging/Logging.h	(revision 11885)
+++ source/ariba/utility/logging/Logging.h	(revision 12060)
@@ -97,4 +97,5 @@
 
   static int __loglevel__ = 2; //default is info
+//  static int __loglevel__ = 1; // XXX use higher log level
 
   #define logging_trace(x)  {                                   logging_stdout(x);                }
Index: source/ariba/utility/messages.h
===================================================================
--- source/ariba/utility/messages.h	(revision 11885)
+++ source/ariba/utility/messages.h	(revision 12060)
@@ -40,10 +40,13 @@
 #define MESSAGES_H_
 
+// TODO wÃŒrde sagen das brauchen wir nicht mehr
+//   ---> ÃŒberall dieses include rausnehmen und ggf  #include "messages/Message.h"   einfÃŒgen..
+
 #include "messages/Message.h"
-#include "messages/MessageSender.h"
-#include "messages/MessageReceiver.h"
-#include "messages/MessageUtilities.h"
-#include "messages/MessageProvider.h"
-#include "messages/TextMessage.h"
+//#include "messages/MessageSender.h"  // TODO wird das noch genutzt..? Wenn nein, sollte es weg!
+//#include "messages/MessageReceiver.h"
+//#include "messages/MessageUtilities.h"
+////#include "messages/MessageProvider.h"  // DEPRECATED
+//#include "messages/TextMessage.h"
 
 #endif /* MESSAGES_H_ */
Index: source/ariba/utility/messages/Message.cpp
===================================================================
--- source/ariba/utility/messages/Message.cpp	(revision 11885)
+++ source/ariba/utility/messages/Message.cpp	(revision 12060)
@@ -41,4 +41,6 @@
 #include "ariba/utility/serialization/DataStream.hpp"
 
+#include "ariba/utility/logging/Logging.h"
+
 NAMESPACE_BEGIN
 
@@ -80,15 +82,59 @@
 }
 
+
+reboost::message_t Message::wrap_up_for_sending()
+{
+    assert( ! wrapped_up );
+    wrapped_up = true;
+    
+    //// Adapt to new message system ////
+    Data data = data_serialize(this, DEFAULT_V);
+    reboost::shared_buffer_t buf(data.getBuffer(), data.getLength() / 8);
+
+    newstyle_payload.push_front(buf);
+    
+    return newstyle_payload;
+}
+
+reboost::shared_buffer_t Message::serialize_into_shared_buffer()
+{
+    assert ( newstyle_payload.length() == 0 );
+    
+    //// Adapt to new message system ////
+    Data data = data_serialize(this, DEFAULT_V);
+    reboost::shared_buffer_t buf(data.getBuffer(), data.getLength() / 8);
+    
+    return buf;
+}
+
+
+reboost::shared_buffer_t Message::deserialize_from_shared_buffer(reboost::shared_buffer_t buff)
+{
+    // NOTE: legacy payload is not allowed when using shared buffers
+    this->legacy_payload_disabled = true;
+    
+    assert( buff.size() > 0 );
+    
+    // const_cast is necessary here, but without legacy payload we should be save here (more or less)
+    Data dat(const_cast<uint8_t*>(buff.data()), buff.size() * 8);
+    
+    size_t len = this->SERIALIZATION_METHOD_NAME(DESERIALIZE, dat) / 8;
+
+    // return remaining sub-buffer
+    return buff(len);
+}
+
+
+
 NAMESPACE_END
 
 std::ostream& operator<<(std::ostream& stream, const ariba::utility::Message& msg ) {
 	using_serialization;
-	stream << "msg(type=" << typeid(msg).name();
+	stream << "msg(type=" << typeid(msg).name() << ",";
 	stream << "len=" << (data_length(&msg)/8) << ",";
 	Data data = data_serialize(&msg);
-	stream << ",data=" << data;
+	stream << "data=" << data;
 	data.release();
 	stream << ")";
 	return stream;
 }
-
Index: source/ariba/utility/messages/Message.h
===================================================================
--- source/ariba/utility/messages/Message.h	(revision 11885)
+++ source/ariba/utility/messages/Message.h	(revision 12060)
@@ -62,4 +62,8 @@
 #include "ariba/utility/serialization.h"
 
+// reboost messages
+#include "ariba/utility/transport/messages/message.hpp"
+
+
 std::ostream& operator<<(std::ostream& stream, const ariba::utility::Message& msg );
 
@@ -82,10 +86,12 @@
 	friend std::ostream& ::operator<<(std::ostream& stream, const ariba::utility::Message& msg );
 
-	// root binary data
-	shared_array<uint8_t> root;
-
 	// payload
+	bool legacy_payload_disabled;
 	bool releasePayload;
 	Data payload; //< messages binary data
+	
+	// XXX testing...
+	reboost::message_t newstyle_payload;
+	bool wrapped_up;
 
 	// addresses and control info
@@ -98,5 +104,6 @@
 	 */
 	inline Message() :
-		root(), releasePayload(true), payload(), srcAddr(NULL),destAddr(NULL) {
+	    legacy_payload_disabled(false), releasePayload(true), payload(),
+	    newstyle_payload(), wrapped_up(false), srcAddr(NULL),destAddr(NULL) {
 	}
 
@@ -106,5 +113,6 @@
 	 */
 	explicit inline Message( const Data& data ) :
-		releasePayload(true), srcAddr(NULL),destAddr(NULL) {
+        legacy_payload_disabled(false), releasePayload(true),
+        newstyle_payload(), wrapped_up(false), srcAddr(NULL),destAddr(NULL) {  // FIXME newstyle_payload..?
 		this->payload = data.clone();
 //		this->root = shared_array<uint8_t>((uint8_t*)data.getBuffer());
@@ -225,4 +233,37 @@
 		return decapsulate<T>();
 	}
+	
+	
+	// XXX testing
+	void set_payload_message(reboost::message_t msg)
+	{
+	    newstyle_payload = msg;
+	}
+	
+	void append_buffer(reboost::shared_buffer_t buff)
+	{
+	    newstyle_payload.push_back(buff);
+	}
+	
+	
+	// XXX testing... packs this message into the payload message (do not use twice!!)
+	virtual reboost::message_t wrap_up_for_sending();
+	
+	
+	/**
+	 * Uses the old serialization system to serialize itself into a (new style) shared buffer.
+	 */
+	virtual reboost::shared_buffer_t serialize_into_shared_buffer();
+	
+	/*
+	 * XXX experimental
+	 * 
+	 * Uses the old serialization system to deserialize itself out of a (new style) shared buffer.
+	 * @return remaining sub-buffer (the "payload")
+	 * 
+	 * Note: This is some kind of a hack! handle with care.
+	 */
+	virtual reboost::shared_buffer_t deserialize_from_shared_buffer(reboost::shared_buffer_t buff);
+	
 
 protected:
@@ -262,5 +303,8 @@
 	 * @return A explicit payload serializer
 	 */
-	finline PayloadSerializer Payload( size_t length = ~0 ) {
+	finline PayloadSerializer Payload( size_t length = ~0 )
+	{
+//	    assert( ! legacy_payload_disabled );  // FIXME aktuell
+	    
 		return PayloadSerializer( this, length );
 	}
Index: source/ariba/utility/messages/MessageProvider.cpp
===================================================================
--- source/ariba/utility/messages/MessageProvider.cpp	(revision 11885)
+++ source/ariba/utility/messages/MessageProvider.cpp	(revision 12060)
@@ -37,32 +37,32 @@
 // [License]
 
-#include "MessageProvider.h"
-
-NAMESPACE_BEGIN
-
-MessageProvider::MessageProvider() {
-}
-
-MessageProvider::~MessageProvider() {
-}
-
-bool MessageProvider::sendMessageToReceivers( const Message* message ) {
-	bool sent =  false;
-	for (size_t i=0; i<receivers.size(); i++)
-		if (receivers[i]->receiveMessage(message, LinkID::UNSPECIFIED, NodeID::UNSPECIFIED)) sent = true;
-	return sent;
-}
-
-void MessageProvider::addMessageReceiver( MessageReceiver* receiver ) {
-	receivers.push_back(receiver);
-}
-
-void MessageProvider::removeMessageReceiver( MessageReceiver* receiver ) {
-	for (size_t i=0; i<receivers.size(); i++)
-		if (receivers[i]==receiver) {
-			receivers.erase( receivers.begin()+i );
-			break;
-		}
-}
-
-NAMESPACE_END
+//#include "MessageProvider.h"
+//
+//NAMESPACE_BEGIN
+//
+//MessageProvider::MessageProvider() {
+//}
+//
+//MessageProvider::~MessageProvider() {
+//}
+//
+//bool MessageProvider::sendMessageToReceivers( const Message* message ) {
+//	bool sent =  false;
+//	for (size_t i=0; i<receivers.size(); i++)
+//		if (receivers[i]->receiveMessage(message, LinkID::UNSPECIFIED, NodeID::UNSPECIFIED)) sent = true;
+//	return sent;
+//}
+//
+//void MessageProvider::addMessageReceiver( MessageReceiver* receiver ) {
+//	receivers.push_back(receiver);
+//}
+//
+//void MessageProvider::removeMessageReceiver( MessageReceiver* receiver ) {
+//	for (size_t i=0; i<receivers.size(); i++)
+//		if (receivers[i]==receiver) {
+//			receivers.erase( receivers.begin()+i );
+//			break;
+//		}
+//}
+//
+//NAMESPACE_END
Index: source/ariba/utility/messages/MessageProvider.h
===================================================================
--- source/ariba/utility/messages/MessageProvider.h	(revision 11885)
+++ source/ariba/utility/messages/MessageProvider.h	(revision 12060)
@@ -1,2 +1,4 @@
+// XXX DEPRECATED
+
 // [License]
 // The Ariba-Underlay Copyright
@@ -37,60 +39,62 @@
 // [License]
 
+// XXX DEPRECATED
+
 #ifndef MESSAGEPROVIDER_H_
 #define MESSAGEPROVIDER_H_
 
-#include "_namespace.h"
-#include "MessageReceiver.h"
-#include "ariba/utility/types/LinkID.h"
-#include "ariba/utility/types/NodeID.h"
-#include <vector>
-
-using std::vector;
-using ariba::utility::LinkID;
-using ariba::utility::NodeID;
-
-NAMESPACE_BEGIN
-
-
-/**
- * This class defines an interface for message providers.
- * Implementing classes must allow receivers to register themselves.
- *
- * @author Sebastian Mies
- */
-class MessageProvider {
-private:
-	vector<MessageReceiver*> receivers;
-
-protected:
-	bool sendMessageToReceivers( const Message* message );
-
-public:
-	/**
-	 * Constructor.
-	 */
-	MessageProvider();
-
-	/**
-	 * Destructor.
-	 */
-	~MessageProvider();
-
-	/**
-	 * Adds a message receiver.
-	 *
-	 * @param receiver The receiver.
-	 */
-	void addMessageReceiver( MessageReceiver* receiver );
-
-	/**
-	 * Removes a message receiver.
-	 *
-	 * @param receiver The receiver.
-	 */
-	void removeMessageReceiver( MessageReceiver* receiver );
-};
-
-NAMESPACE_END
+//#include "_namespace.h"
+//#include "MessageReceiver.h"
+//#include "ariba/utility/types/LinkID.h"
+//#include "ariba/utility/types/NodeID.h"
+//#include <vector>
+//
+//using std::vector;
+//using ariba::utility::LinkID;
+//using ariba::utility::NodeID;
+//
+//NAMESPACE_BEGIN
+//
+//
+///**
+// * This class defines an interface for message providers.
+// * Implementing classes must allow receivers to register themselves.
+// *
+// * @author Sebastian Mies
+// */
+//class MessageProvider {
+//private:
+//	vector<MessageReceiver*> receivers;
+//
+//protected:
+//	bool sendMessageToReceivers( const Message* message );
+//
+//public:
+//	/**
+//	 * Constructor.
+//	 */
+//	MessageProvider();
+//
+//	/**
+//	 * Destructor.
+//	 */
+//	~MessageProvider();
+//
+//	/**
+//	 * Adds a message receiver.
+//	 *
+//	 * @param receiver The receiver.
+//	 */
+//	void addMessageReceiver( MessageReceiver* receiver );
+//
+//	/**
+//	 * Removes a message receiver.
+//	 *
+//	 * @param receiver The receiver.
+//	 */
+//	void removeMessageReceiver( MessageReceiver* receiver );
+//};
+//
+//NAMESPACE_END
 
 #endif /* MESSAGEPROVIDER_H_ */
Index: source/ariba/utility/messages/MessageReceiver.cpp
===================================================================
--- source/ariba/utility/messages/MessageReceiver.cpp	(revision 11885)
+++ source/ariba/utility/messages/MessageReceiver.cpp	(revision 12060)
@@ -49,8 +49,8 @@
 }
 
-bool MessageReceiver::receiveMessage( const Message* message, const LinkID& link, const NodeID& node ) {
-	//std::cout << "UNIMPLEMENTED MessageReceiver got Message:" << (Message*)message << std::endl;
-	return false;
-}
+//bool MessageReceiver::receiveMessage( reboost::shared_buffer_t message, const LinkID& link, const NodeID& node ) {
+//	//std::cout << "UNIMPLEMENTED MessageReceiver got Message:" << (Message*)message << std::endl;
+//	return false;
+//}
 
 NAMESPACE_END
Index: source/ariba/utility/messages/MessageReceiver.h
===================================================================
--- source/ariba/utility/messages/MessageReceiver.h	(revision 11885)
+++ source/ariba/utility/messages/MessageReceiver.h	(revision 12060)
@@ -40,5 +40,7 @@
 #define MESSAGERECEIVER_H__
 
-#include "ariba/utility/messages/Message.h"
+//#include "ariba/utility/messages/Message.h"
+// reboost messages
+#include "ariba/utility/transport/messages/message.hpp"
 #include "ariba/utility/types/LinkID.h"
 #include "ariba/utility/types/NodeID.h"
@@ -73,5 +75,8 @@
 	 * @return True, when the message has been accepted.
 	 */
-	virtual bool receiveMessage( const Message* message, const LinkID& link, const NodeID& node );
+	virtual bool receiveMessage( reboost::shared_buffer_t message,
+	        const LinkID& link,
+	        const NodeID& node,
+	        bool bypass_overlay ) = 0;
 };
 
Index: source/ariba/utility/misc/Demultiplexer.hpp
===================================================================
--- source/ariba/utility/misc/Demultiplexer.hpp	(revision 11885)
+++ source/ariba/utility/misc/Demultiplexer.hpp	(revision 12060)
@@ -136,5 +136,5 @@
 
 		SERVICE_LISTENER_MAP_CITERATOR it = mapServiceListener.find( id );
-		if( it == mapServiceListener.end() ) 	return NULL;
+		if( it == mapServiceListener.end() ) 	return 0;
 		else					return it->second;
 	}
Index: source/ariba/utility/system/StartupWrapper.cpp
===================================================================
--- source/ariba/utility/system/StartupWrapper.cpp	(revision 11885)
+++ source/ariba/utility/system/StartupWrapper.cpp	(revision 12060)
@@ -36,4 +36,6 @@
 // Telematics.
 // [License]
+
+// XXX NOTE: Use this class with caution! Config support is outdated.
 
 #include "StartupWrapper.h"
Index: source/ariba/utility/system/StartupWrapper.h
===================================================================
--- source/ariba/utility/system/StartupWrapper.h	(revision 11885)
+++ source/ariba/utility/system/StartupWrapper.h	(revision 12060)
@@ -36,4 +36,6 @@
 // Telematics.
 // [License]
+
+// XXX NOTE: Use this class with caution! Config support is outdated.
 
 #ifndef __STARTUP_WRAPPER_H
Index: source/ariba/utility/system/SystemQueue.cpp
===================================================================
--- source/ariba/utility/system/SystemQueue.cpp	(revision 11885)
+++ source/ariba/utility/system/SystemQueue.cpp	(revision 12060)
@@ -69,4 +69,16 @@
 }
 
+// maps to function call internally to the Event-system
+void SystemQueue::scheduleCall( const boost::function0<void>& function, uint32_t delay)
+{
+    // copy function object
+    boost::function0<void>* function_ptr = new boost::function0<void>();
+    (*function_ptr) = function; 
+
+    // schedule special call-event
+    scheduleEvent( SystemEvent(&internal_function_caller, SystemEventType::DEFAULT, function_ptr), delay );
+
+}
+
 #ifdef UNDERLAY_OMNET
 void SystemQueue::handleMessage(cMessage* msg){
Index: source/ariba/utility/system/SystemQueue.h
===================================================================
--- source/ariba/utility/system/SystemQueue.h	(revision 11885)
+++ source/ariba/utility/system/SystemQueue.h	(revision 12060)
@@ -60,4 +60,7 @@
 #endif
 
+#include <boost/function.hpp>
+
+
 using std::vector;
 using boost::posix_time::ptime;
@@ -108,4 +111,13 @@
 	 */
 	void scheduleEvent( const SystemEvent& event, uint32_t delay = 0 );
+	
+	/**
+	 * This method schedules a function call in the SystemQueue.
+	 * (Like scheduleEvent, but to be used with boost::bind.)
+	 * 
+	 * @param function: The function to be called [void function()]
+	 * @param The delay in milli-seconds
+	 */
+	void scheduleCall( const boost::function0<void>& function, uint32_t delay = 0 );
 
 	/**
@@ -170,4 +182,6 @@
 #endif
 
+	
+	
 private:
 
@@ -235,5 +249,22 @@
 	volatile bool systemQueueRunning;
 #endif
-
+	
+	
+private:
+    /**
+     * This inner class handles the function-call events.
+     * @see SystemQueue::scheduleCall
+     */
+    class FunctionCaller  :  public SystemEventListener
+    {
+        void handleSystemEvent(const SystemEvent& event)
+        {
+            boost::function0<void>* function_ptr = event.getData< boost::function0<void> >();
+            (*function_ptr)();
+            delete function_ptr;
+        }
+    };
+
+    FunctionCaller internal_function_caller;
 }; // class SystemQueue
 
Index: source/ariba/utility/transport/CMakeLists.txt
===================================================================
--- source/ariba/utility/transport/CMakeLists.txt	(revision 11885)
+++ source/ariba/utility/transport/CMakeLists.txt	(revision 12060)
@@ -38,12 +38,8 @@
 
 add_headers(
-    test_transport.hpp
-    transport_connection.hpp
-    transport.hpp
-    transport_listener.hpp
     transport_peer.cpp
     transport_peer.hpp
-    transport_protocol.hpp
     )
 
-add_subdir_sources(asio messages rfcomm tcpip)
+add_subdir_sources(asio messages rfcomm StreamTransport)
+
Index: source/ariba/utility/transport/StreamTransport/CMakeLists.txt
===================================================================
--- source/ariba/utility/transport/StreamTransport/CMakeLists.txt	(revision 12060)
+++ source/ariba/utility/transport/StreamTransport/CMakeLists.txt	(revision 12060)
@@ -0,0 +1,42 @@
+# [License]
+# The Ariba-Underlay Copyright
+#
+# Copyright (c) 2008-2012, Institute of Telematics, UniversitÃ€t Karlsruhe (TH)
+#
+# Institute of Telematics
+# UniversitÃ€t Karlsruhe (TH)
+# Zirkel 2, 76128 Karlsruhe
+# Germany
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OF TELEMATICS OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# The views and conclusions contained in the software and documentation
+# are those of the authors and should not be interpreted as representing
+# official policies, either expressed or implied, of the Institute of
+# Telematics.
+# [License]
+
+add_headers(StreamTransport.hpp)
+
+add_sources(StreamTransport.cpp)
+
Index: source/ariba/utility/transport/StreamTransport/StreamTransport.cpp
===================================================================
--- source/ariba/utility/transport/StreamTransport/StreamTransport.cpp	(revision 12060)
+++ source/ariba/utility/transport/StreamTransport/StreamTransport.cpp	(revision 12060)
@@ -0,0 +1,814 @@
+#include "StreamTransport.hpp"
+
+// ariba
+#include "ariba/utility/addressing2/tcpip_endpoint.hpp"
+
+// boost-adaption
+#include "ariba/utility/transport/rfcomm/bluetooth_rfcomm.hpp"
+
+// boost
+#include <boost/foreach.hpp>
+#include <boost/array.hpp>
+#include <boost/asio/ip/address.hpp>
+
+// interface discovery for link-local destinations (tcp-only)
+#include <ifaddrs.h>
+
+
+namespace ariba {
+namespace transport {
+
+//use_logging_cpp(StreamTransport<T>)
+
+#ifdef HAVE_LIBBLUETOOTH
+    using boost::asio::bluetooth::rfcomm;
+#endif /* HAVE_LIBBLUETOOTH */
+
+using namespace ariba::addressing2;
+using ariba::utility::LinkID;
+
+using boost::asio::ip::tcp;
+using boost::asio::ip::address_v6;
+using boost::shared_ptr;
+
+typedef boost::mutex::scoped_lock unique_lock;
+
+
+template <class T>
+StreamTransport<T>::StreamTransport( const typename T::endpoint& endp )  :
+        listener(NULL),
+        acceptor(u_io_service.get_asio_io_service(), endp)
+{
+}
+
+template <class T>
+StreamTransport<T>::~StreamTransport(){}
+
+template <class T>
+void StreamTransport<T>::start()
+{
+    // open server socket
+    accept();
+    
+    u_io_service.start();
+}
+
+
+template <class T>
+void StreamTransport<T>::stop()
+{
+    acceptor.close();
+    
+    u_io_service.stop();
+}
+
+
+/* see header file for comments */
+template <class T>
+void StreamTransport<T>::send(
+        const typename T::endpoint& dest_addr,
+        reboost::message_t message,
+        uint8_t priority)
+{
+    ConnPtr conn;
+    bool need_to_connect = false;
+    
+    {
+        unique_lock lock(connections_lock);
+        
+        // try to find existing connection to this endpoint 
+        typename ConnectionMap::iterator it = connections.find(dest_addr);
+        
+        // BRANCH: create new connection
+        if (it == connections.end())
+        {
+            ConnPtr tmp_ptr(
+                    new StreamConnection(
+                            u_io_service.get_asio_io_service(),
+                            this->shared_from_this() )
+                    );
+            conn = tmp_ptr;
+
+            // save partner endpoint
+            conn->partner_endpoint = dest_addr;
+            
+            // Note: starting the send is the obligation of the connect_handler
+            // (avoids trying to send while not connected yet)
+            conn->sending = true;
+            need_to_connect = true;
+            
+            typename ConnectionMap::value_type item(dest_addr, conn);
+            connections.insert(item);
+            
+        }
+        // BRANCH: use existing connection
+        else
+        {
+            conn = it->second;
+        }
+    }
+    
+    
+    // * the actual send *
+    conn->enqueue_for_sending(message, priority);
+    
+    // if new connection connect to the other party
+    if ( need_to_connect )
+    {
+        conn->sock.async_connect(
+                dest_addr,
+                boost::bind(
+                        &StreamConnection::async_connect_handler,
+                        conn,
+                        boost::asio::placeholders::error));
+    }
+}
+
+
+// TODO is this a private function? ... and still needed?
+/* see header file for comments */
+template <class T>
+void StreamTransport<T>::send(
+        const EndpointPtr remote,
+        reboost::message_t message,
+        uint8_t priority)
+{
+    if ( remote->get_category() == endpoint_category::TCPIP )
+    {
+        const addressing2::tcpip_endpoint* endp =
+                static_cast<const addressing2::tcpip_endpoint*>(remote.get());
+        
+        send(endp->to_asio(), message, priority);
+    }
+    
+    // else
+    // TODO what now?
+}
+
+
+template <class T>
+void StreamTransport<T>::register_listener( transport_listener* listener )
+{
+    this->listener = listener;
+}
+
+
+// XXX DEPRECATED
+template <class T>
+void StreamTransport<T>::terminate( const EndpointPtr remote )
+{
+    if ( remote->get_category() == endpoint_category::TCPIP )
+    {
+        const addressing2::tcpip_endpoint* endp =
+                static_cast<const addressing2::tcpip_endpoint*>(remote.get());
+
+        
+        this->terminate(endp->to_asio());
+    }
+}
+
+template <class T>
+void StreamTransport<T>::terminate( const typename T::endpoint& remote )
+{
+    ConnPtr conn;
+    
+    // find and forget connection
+    {
+        unique_lock lock(connections_lock);
+        
+        typename ConnectionMap::iterator it = connections.find(remote);
+        if (it == connections.end())
+        {
+            return;
+        }
+        
+        conn = it->second;
+
+        // prevent upper layers from using this link
+        conn->valid = false;
+
+        connections.erase(it);
+    }
+    
+    // XXX aktuell
+//     cout << "/// MARIO: TCP/IP TERMINATE: " << conn->partner_endpoint << endl;
+    
+    // notify higher layers
+    if ( listener )
+    {
+        listener->connection_terminated(conn);
+    }
+
+    
+    // XXX debug aktuell
+//    cout << "/// MARIO Open connections:" << endl;
+//    for ( typename ConnectionMap::iterator it = connections.begin(); it != connections.end(); ++it )
+//    {
+//        cout << "  CONNECTION: " << it->second->local_endpoint << " <---> " << it->second->partner_endpoint << endl;
+//        cout << "    used by: " << endl;
+//        
+//        int usecount = 0;
+//        ConnPtr xx;
+//        std::vector<LinkID*> links = it->second->get_communication_links();
+//        for ( std::vector<LinkID*>::iterator it2 = links.begin(); it2 != links.end(); ++it2 )
+//        {
+//            cout << "      - " << *it2 << endl;
+//            usecount++;
+//        }
+//        if ( usecount == 0 )
+//        {
+//            cout << "      ---> NOBODY !!" << endl;
+//        }
+//    }
+//    cout << "/// -------" << endl;
+
+
+    // close connection
+    boost::system::error_code ec;
+    conn->sock.shutdown(T::socket::shutdown_both, ec);
+    conn->sock.close(ec);
+}
+
+
+/* private */
+template <class T>
+void StreamTransport<T>::accept()
+{
+    // create new connection object
+    ConnPtr conn(
+            new StreamConnection(
+                    u_io_service.get_asio_io_service(),
+                    this->shared_from_this()
+            )
+    );
+    
+    // wait for incoming connection
+    acceptor.async_accept(
+            conn->sock,
+            boost::bind(&self::async_accept_handler,
+                    this->shared_from_this(),
+                    conn,
+                    boost::asio::placeholders::error)
+    );
+}
+
+template <class T>
+void StreamTransport<T>::async_accept_handler(ConnPtr conn, const error_code& error)
+{
+    if ( ! error )
+    {
+        // save partner endpoint
+        conn->partner_endpoint = conn->sock.remote_endpoint();
+        
+        {
+            unique_lock lock(connections_lock);
+            
+            typename ConnectionMap::value_type item(conn->sock.remote_endpoint(), conn);
+            connections.insert(item);
+        }
+        
+        // read
+        conn->listen();
+    }
+    
+    // accept further connections
+    accept();
+}
+
+
+
+/*------------------
+ | specializations |
+ ------------------*/
+/* TCP */
+template <>
+void StreamTransport<tcp>::send(
+        const addressing2::const_EndpointSetPtr endpoints,
+        reboost::message_t message,
+        uint8_t priority )
+{
+    // network interfaces scope_ids, for link-local connections (lazy initialization)
+    vector<uint64_t> scope_ids;
+    
+    // send a message to each combination of address-address and port
+    BOOST_FOREACH( const TcpIP_EndpointPtr address, endpoints->get_tcpip_endpoints() )
+//    vector<TcpIP_EndpointPtr> endpoint_vec = endpoints->get_tcpip_endpoints();
+//    for ( vector<TcpIP_EndpointPtr>::iterator it = endpoint_vec.begin(); it != endpoint_vec.end(); ++it )
+    {
+        tcp::endpoint endp = address->to_asio();
+        
+        // special treatment for link local addresses
+        //   ---> send over all (suitable) interfaces
+        if ( endp.address().is_v6() )
+        {
+            boost::asio::ip::address_v6 v6_addr = endp.address().to_v6();
+            
+            if ( v6_addr.is_link_local() )
+            {
+                // initialize scope_ids
+                if ( scope_ids.size() == 0 )
+                    scope_ids = get_interface_scope_ids();
+                
+                BOOST_FOREACH ( uint64_t id, scope_ids )
+                {                        
+                    v6_addr.scope_id(id);
+                    endp.address(v6_addr);
+
+//                    logging_debug("------> SEND TO (link-local): " << endp);
+                    // * send *
+                    send(endp, message, priority);
+                }
+            }
+            
+            continue;
+        }
+        
+        // * send *
+        send(endp, message, priority);
+    }
+}
+
+
+/* RFCOMM */
+#ifdef HAVE_LIBBLUETOOTH
+
+// TODO
+
+//    template <>
+//    void StreamTransport<rfcomm>::send(
+//            const endpoint_set& endpoints,
+//            reboost::message_t message,
+//            uint8_t priority )
+//    {
+//        // send a message to each combination of address-address and port
+//        BOOST_FOREACH( const mac_address mac, endpoints.bluetooth ) {
+//            BOOST_FOREACH( const rfcomm_channel_address channel, endpoints.rfcomm ) {
+//                rfcomm::endpoint endp(mac.bluetooth(), channel.value());
+//                
+//                // * send *
+//                send(endp, message, priority);
+//            }
+//        }
+//    }
+
+#endif /* HAVE_LIBBLUETOOTH */
+
+
+
+/*****************
+ ** inner class **
+ *****************/
+
+template <class T>
+StreamTransport<T>::StreamConnection::StreamConnection(boost::asio::io_service & io_service, StreamTransportPtr parent)  :
+        sock(io_service),
+        valid(true),
+        parent(parent),
+        out_queues(8), //TODO How much priorities shall we have?
+        sending(false)
+{
+        header.length = 0;
+}
+
+/*-------------------------------------------
+ | implement transport_connection interface |
+ -------------------------------------------*/
+template <class T>
+bool StreamTransport<T>::StreamConnection::send(
+        reboost::message_t message,
+        uint8_t priority)
+{
+    if ( ! valid )
+    {
+        // XXX aktuell
+//         cout << "/// MARIO: USED INVALID LINK: " << this->partner_endpoint << endl;
+
+        return false;
+    }
+    
+    // * enqueue data *
+    enqueue_for_sending(message, priority);
+    
+    return true;
+}
+
+
+template <class T>
+EndpointPtr StreamTransport<T>::StreamConnection::getLocalEndpoint()
+{
+    EndpointPtr ret(new addressing2::tcpip_endpoint(local_endpoint));
+    
+    return ret;
+}
+
+
+template <class T>
+EndpointPtr StreamTransport<T>::StreamConnection::getRemoteEndpoint()
+{
+    EndpointPtr ret(new addressing2::tcpip_endpoint(partner_endpoint));
+    
+    return ret;
+}
+
+template <class T>
+void StreamTransport<T>::StreamConnection::register_communication_link(LinkID* link)
+{
+    if ( ! link )
+        return;
+    
+    // add link
+    communication_links.push_back(link);
+}
+
+template <class T>
+void StreamTransport<T>::StreamConnection::unregister_communication_link(LinkID* link)
+{
+    if ( ! link )
+        return;
+
+    
+    // remove link
+    {
+        std::vector<LinkID*>::iterator it = communication_links.begin();
+        
+        while ( it != communication_links.end() )
+        {
+            if ( (*it) == link )
+            {
+                it = communication_links.erase(it);
+            }
+            else
+            {
+                ++it;
+            }
+        }
+    }
+    
+    // this connection is no longer used by any link
+    if ( communication_links.empty() )
+    {
+        //XXX
+//         cout << "communication_links.empty() " << getLocalEndpoint()->to_string() << " - " << getRemoteEndpoint()->to_string() << endl;
+        
+        // terminate connection
+        this->terminate();  // TODO aktuell
+        
+        /*
+         *  TODO racecondition:
+         *  When receiving a link request, the connection could closed
+         *  before the request is handled.
+         *  
+         *  ---> Maybe wait a timeout before actually terminate the connection.
+         *  (e.g. record last-used time:
+         *      if last used > timeout and communication_links.empty()
+         *      then terminate the connection)  
+         */
+    }
+}
+
+template <class T>
+std::vector<LinkID*> StreamTransport<T>::StreamConnection::get_communication_links()
+{
+    return communication_links;
+}
+
+
+template <class T>
+void StreamTransport<T>::StreamConnection::terminate()
+{
+    parent->terminate(partner_endpoint);
+}
+
+
+/*------------------------------
+ | things we defined ourselves |
+ ------------------------------*/
+template <class T>
+void StreamTransport<T>::StreamConnection::async_connect_handler(const error_code& error)
+{
+    if (error)
+    {
+        parent->terminate(partner_endpoint);
+
+        return;
+    }
+    
+    // save local endpoint
+    local_endpoint = sock.local_endpoint();
+    
+    // Note: sending has to be true at this point
+    send_next_package();
+    
+    listen();
+}
+
+
+template <class T>
+void StreamTransport<T>::StreamConnection::listen()
+{
+    boost::asio::async_read(
+            this->sock,
+            boost::asio::mutable_buffers_1(&this->header, sizeof(header_t)),
+            boost::bind(
+                    &StreamTransport<T>::StreamConnection::async_read_header_handler,
+                    this->shared_from_this(),
+                    boost::asio::placeholders::error,
+                    boost::asio::placeholders::bytes_transferred
+            )
+    );
+}
+
+
+template <class T>
+void StreamTransport<T>::StreamConnection::async_read_header_handler(const error_code& error, size_t bytes_transferred)
+{
+    if (error)
+    {
+        parent->terminate(partner_endpoint);
+
+        return;
+    }
+    
+    // sanity checks
+    //   NOTE: max size 8k (may be changed later..)
+    if ( header.length == 0 || header.length > 8192 )
+    {
+        parent->terminate(partner_endpoint);
+    }
+
+    
+    // new buffer for the new packet
+    buffy = shared_buffer_t(header.length);
+
+    // * read data *
+    boost::asio::async_read(
+            this->sock,
+            boost::asio::buffer(buffy.mutable_data(), buffy.size()),
+            boost::bind(
+                    &StreamTransport<T>::StreamConnection::async_read_data_handler,
+                    this->shared_from_this(),
+                    boost::asio::placeholders::error,
+                    boost::asio::placeholders::bytes_transferred
+            )
+    );
+}
+
+template <class T>
+void StreamTransport<T>::StreamConnection::async_read_data_handler(
+        const error_code& error, size_t bytes_transferred)
+{
+    if (error)
+    {
+        parent->terminate(partner_endpoint);
+
+        return;
+    }
+    
+    if ( parent->listener )
+        parent->listener->receive_message(this->shared_from_this(), buffy);
+
+    buffy = shared_buffer_t();
+    listen();
+}
+
+/* see header file for comments */
+template <class T>
+void StreamTransport<T>::StreamConnection::async_write_handler(reboost::shared_buffer_t packet, const error_code& error, size_t bytes_transferred)
+{
+    if ( error )
+    {        
+        // remove this connection
+        parent->terminate(partner_endpoint); 
+
+        return;
+    }
+    
+    send_next_package();
+}
+
+
+
+template <class T>
+void StreamTransport<T>::StreamConnection::enqueue_for_sending(Packet packet, uint8_t priority)
+{
+    bool restart_sending = false;
+    
+    // enqueue packet  [locked]
+    {
+        unique_lock(out_queues_lock);
+        
+        assert( priority < out_queues.size() );
+        out_queues[priority].push(packet);
+        
+        if ( ! sending )
+        {
+            restart_sending = true;
+            sending = true;
+        }
+    }
+    
+    // if sending was stopped, we have to restart it here
+    if ( restart_sending )
+    {
+        send_next_package();
+    }
+}
+
+/* see header file for comments */
+template <class T>
+void StreamTransport<T>::StreamConnection::send_next_package()
+{
+    Packet packet;
+    bool found = false;
+
+    // find packet with highest priority  [locked]
+    {
+        unique_lock(out_queues_lock);
+        
+        for ( vector<OutQueue>::iterator it = out_queues.begin();
+                it != out_queues.end(); it++ )
+        {
+            if ( !it->empty() )
+            {
+                packet = it->front();
+                it->pop();
+                found = true;
+                
+                break;
+            }
+        }
+        
+        // no packets waiting --> stop sending
+        if ( ! found )
+        {
+            sending = false;
+        }
+    }
+    
+    // * send *
+    if ( found )
+    {
+        reboost::shared_buffer_t header_buf(sizeof(header_t));
+        header_t* header = (header_t*)(header_buf.mutable_data());
+        header->length = packet.size();
+        
+        packet.push_front(header_buf);
+        
+        // "convert" message to asio buffer sequence
+        vector<boost::asio::const_buffer> send_sequence(packet.length());
+        for ( int i=0; i < packet.length(); i++ )
+        {
+            shared_buffer_t b = packet.at(i);
+            send_sequence.push_back(boost::asio::buffer(b.data(), b.size()));
+        }
+        
+        // * async write *
+        boost::asio::async_write(
+                this->sock,
+                send_sequence,
+                boost::bind(
+                        &StreamTransport<T>::StreamConnection::async_write_handler,
+                        this->shared_from_this(),
+                        packet,  // makes sure our shared pointer lives long enough ;-)
+                        boost::asio::placeholders::error,
+                        boost::asio::placeholders::bytes_transferred)
+        );
+    }
+}
+/*********************
+ ** [ inner class ] **
+ *********************/
+
+
+
+// explicitly tell the compiler to create a Â»tcpÂ« (and Â»rfcommÂ«) specialization
+//   --> (needed since hpp and cpp are separated) 
+template class StreamTransport<boost::asio::ip::tcp>;
+
+#ifdef HAVE_LIBBLUETOOTH
+    template class StreamTransport<rfcomm>;
+#endif /* HAVE_LIBBLUETOOTH */
+
+
+
+/////////////////////////////////////////////////////////////////////////////////////
+    
+
+// XXX testing
+///** 
+// * Conversion between ASIO Adresses and ARIBA adresses
+// */
+///* TCP */
+//template <>
+//inline typename tcp::endpoint convert_address<tcp>( const address_v* address )
+//{
+//    tcpip_endpoint endpoint = *address;
+//    
+//    return typename tcp::endpoint(
+//        endpoint.address().asio(), endpoint.port().value()
+//    );
+//}
+//
+//template <>
+//inline EndpointPtr convert_address<tcp>(const typename tcp::endpoint& endpoint)
+//{
+//    ip_address address;
+//    address.asio(endpoint.address());
+//    tcp_port_address port;
+//    port.value(endpoint.port());
+//    
+////    new tcpip_endpoint(address, port);
+//    tcpip_endpoint xx;
+//    address_vf yy;
+//    address_v* zz = yy->clone();
+//    address_v::shared_ptr endp(zz); // XXX
+//    
+//    return endp; 
+//}
+//
+///* RFCOMM */
+//#ifdef HAVE_LIBBLUETOOTH
+//    template <>
+//    inline typename rfcomm::endpoint convert_address<rfcomm>( const address_v* address )
+//    {
+//        rfcomm_endpoint endpoint = *address;
+//        
+//        return rfcomm::endpoint(
+//            endpoint.mac().bluetooth(), endpoint.channel().value()
+//        );
+//    }
+//    
+//    template <>
+//    inline address_v::shared_ptr convert_address<rfcomm>(const typename rfcomm::endpoint& endpoint)
+//    {
+//        mac_address mac;
+//        mac.bluetooth(endpoint.address());
+//        rfcomm_channel_address channel;
+//        channel.value(endpoint.channel());
+//        
+//        address_v::shared_ptr endp((ariba::addressing::address_v*) new rfcomm_endpoint(mac, channel));
+//        
+//        return endp; 
+//    }
+//#endif /* HAVE_LIBBLUETOOTH */
+
+
+    
+/////////////////////////////////////////////////////////////////////////////////////
+    
+
+/*
+ *  Get Ethernet scope ids (for link-local)
+ */
+vector<uint64_t> get_interface_scope_ids()
+{
+    vector<uint64_t> ret;
+    
+    struct ifaddrs* ifaceBuffer = NULL;
+    void*           tmpAddrPtr  = NULL;
+    
+    int ok = getifaddrs( &ifaceBuffer );
+    if( ok != 0 ) return ret;
+
+    for( struct ifaddrs* i=ifaceBuffer; i != NULL; i=i->ifa_next ) {
+
+        // ignore devices that are disabled or have no ip
+        if(i == NULL) continue;
+        struct sockaddr* addr = i->ifa_addr;
+        if (addr==NULL) continue;
+
+        // only use ethX and wlanX devices
+        string device = string(i->ifa_name);
+        if ( (device.find("eth") == string::npos) &&
+              (device.find("wlan")  == string::npos) /* &&
+              (device.find("lo")  == string::npos) XXX */ )
+        {
+            continue;
+        }
+
+        // only use interfaces with ipv6 link-local addresses 
+        if (addr->sa_family == AF_INET6)
+        {
+            // convert address
+            // TODO should be possible without detour over strings
+            char straddr[INET6_ADDRSTRLEN];
+            tmpAddrPtr= &((struct sockaddr_in6*)addr)->sin6_addr;
+            inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) );
+
+            address_v6 v6addr = address_v6::from_string(straddr);
+            if ( v6addr.is_link_local() )
+            {
+                // * append the scope_id to the return vector *
+                ret.push_back(if_nametoindex(i->ifa_name));
+            }
+
+        }
+    }
+
+    freeifaddrs(ifaceBuffer);
+    
+    return ret;
+}
+
+
+}} // namespace ariba::transport
Index: source/ariba/utility/transport/StreamTransport/StreamTransport.hpp
===================================================================
--- source/ariba/utility/transport/StreamTransport/StreamTransport.hpp	(revision 12060)
+++ source/ariba/utility/transport/StreamTransport/StreamTransport.hpp	(revision 12060)
@@ -0,0 +1,227 @@
+#ifndef STREAM_TRANSPORT_HPP_
+#define STREAM_TRANSPORT_HPP_
+
+// ariba
+#include "ariba/utility/transport/asio/unique_io_service.h"
+#include "ariba/utility/transport/messages/buffers.hpp"
+//#include "ariba/utility/logging/Logging.h"
+#include "ariba/utility/addressing2/endpoint.hpp"
+
+// ariba (transport) interfaces
+#include "ariba/utility/transport/interfaces/transport_connection.hpp"
+#include "ariba/utility/transport/interfaces/transport_protocol.hpp"
+#include "ariba/utility/transport/interfaces/transport_listener.hpp"
+
+// system
+#include <queue>
+
+// boost
+#include <boost/asio.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/enable_shared_from_this.hpp>
+
+
+namespace ariba {
+namespace transport {
+
+using namespace std;
+using boost::shared_ptr;
+using ariba::transport::detail::unique_io_service;
+using boost::system::error_code;
+using reboost::shared_buffer_t;
+using reboost::message_t;
+
+template <class T>
+class StreamTransport :
+    public transport_protocol,
+    public boost::enable_shared_from_this<StreamTransport<T> >
+{
+    typedef StreamTransport<T> self;
+    typedef shared_ptr<self> StreamTransportPtr;
+//use_logging_h(StreamTransport<T>)
+
+    
+    
+    
+private:
+    
+/*****************
+ ** inner class **
+ *****************/
+    class StreamConnection :
+        public transport_connection,
+        public boost::enable_shared_from_this<StreamConnection>
+    {
+    public:
+        typedef reboost::message_t Packet;
+        typedef std::queue<Packet> OutQueue;
+        
+        struct header_t
+        {
+            uint16_t length;
+        } __attribute__((packed));
+            
+        StreamConnection(boost::asio::io_service& io_service, StreamTransportPtr parent);
+        
+        virtual ~StreamConnection() {}
+        
+        /// Inherited from transport_connection
+        // Thread: ARIBA
+        virtual bool send(reboost::message_t message, uint8_t priority = 0);
+        // Thread: ARIBA
+        virtual ariba::addressing2::EndpointPtr getLocalEndpoint();
+        // Thread: ARIBA
+        virtual ariba::addressing2::EndpointPtr getRemoteEndpoint();
+        // Thread: ARIBA
+        virtual void register_communication_link(ariba::utility::LinkID* link);
+        // Thread: ARIBA
+        virtual void unregister_communication_link(ariba::utility::LinkID* link);
+        // Thread: ARIBA
+        virtual std::vector<ariba::utility::LinkID*> get_communication_links();
+        
+        // Thread: BOTH
+        virtual void terminate();
+        
+        void listen();
+        
+        void async_connect_handler(const error_code& error);
+        
+        void async_read_header_handler(const error_code& error, size_t bytes_transferred);
+        void async_read_data_handler(const error_code& error, size_t bytes_transferred);
+        
+        /*
+         * is called from asio when write operation "returns",
+         * calls private function `send_next_package()`
+         */
+        void async_write_handler(
+                reboost::shared_buffer_t packet,
+                const error_code& error,
+                size_t bytes_transferred);
+
+        
+        void enqueue_for_sending(Packet packet, uint8_t priority);
+        
+    private:
+        /*
+         * is called from `send` or `async_write_handler` to begin/keep sending
+         * sends the next message with the highest priority in this connection
+         */
+        void send_next_package();
+
+    public:
+        typename T::socket sock;
+        bool valid;
+        StreamTransportPtr parent;
+        
+        typename T::endpoint partner_endpoint;
+        typename T::endpoint local_endpoint;
+//        address_v* remote;
+//        address_v* local;
+        
+        vector<OutQueue> out_queues;     // to be locked with out_queues_lock 
+        boost::mutex out_queues_lock;
+        
+        bool sending;       // to be locked with out_queues_lock
+        
+        header_t header;
+        shared_buffer_t buffy;
+        
+    private:
+        std::vector<ariba::utility::LinkID*> communication_links;
+    };
+    typedef boost::shared_ptr<StreamConnection> ConnPtr;
+    typedef std::map<typename T::endpoint, ConnPtr> ConnectionMap;
+/*********************
+ ** [ inner class ] **
+ *********************/
+
+    
+    
+    
+public:
+	StreamTransport( const typename T::endpoint& endp );
+	virtual ~StreamTransport();
+	virtual void start();
+	virtual void stop();
+	
+	/**
+     * enqueues message for sending
+     * create new connection if necessary
+     * starts sending mechanism (if not already running)
+     */
+    void send(
+            const typename T::endpoint&,
+            reboost::message_t message,
+            uint8_t priority = 0 );
+	
+	/**
+	 * Converts address_v to tcp::endpoint and calls the real send() function
+	 */
+	virtual void send(
+	        const addressing2::EndpointPtr remote,
+	        reboost::message_t message,
+	        uint8_t priority = 0 );
+	
+	/**
+	 * calls send for each destination endpoint in `endpoints` 
+	 */
+	virtual void send(
+	        const addressing2::const_EndpointSetPtr endpoints,
+	        reboost::message_t message,
+	        uint8_t priority = 0 );
+	
+	// XXX DEPRECATED
+	virtual void terminate( addressing2::EndpointPtr remote );
+	
+	virtual void terminate( const typename T::endpoint& remote );
+	virtual void register_listener( transport_listener* listener );
+
+private:
+	void accept();
+	void async_accept_handler(ConnPtr conn, const error_code& error);
+	
+private:
+	transport_listener* listener;
+	unique_io_service u_io_service;
+	typename T::acceptor acceptor;
+	
+	ConnectionMap connections;
+	boost::mutex connections_lock;
+};
+
+
+// aliases
+//typedef StreamTransport<boost::asio::ip::tcp> tcpip;
+//#ifdef HAVE_LIBBLUETOOTH
+//    typedef StreamTransport<boost::asio::bluetooth::rfcomm> rfcomm_transport;
+//#endif /* HAVE_LIBBLUETOOTH */
+
+
+// XXX testing TODO natÃŒrlich brauchen wir das noch... oO
+///** 
+// * Conversion between ASIO Adresses and ARIBA adresses
+// */
+//template <class T>
+//typename T::endpoint convert_address(const address_v* endpoint);
+//
+//template <class T>
+//address_v::shared_ptr convert_address(const typename T::endpoint& endpoint);
+
+
+
+/**
+ *  returns a vector of (interesting) network interfaces
+ *  
+ *  [NOTE: The current implementation returns the scope_ids of
+ *  all ethX and wlanX network interfaces, to be used for
+ *  connections to link-local ipv6 addresses.]
+ *  
+ *  TODO move to ariba/communication/networkinfo/AddressDiscovery ??
+ *  
+ */
+vector<uint64_t> get_interface_scope_ids();
+
+
+}} // namespace ariba::transport
+
+#endif /* STREAM_TRANSPORT_HPP_ */
Index: source/ariba/utility/transport/interfaces/CMakeLists.txt
===================================================================
--- source/ariba/utility/transport/interfaces/CMakeLists.txt	(revision 12060)
+++ source/ariba/utility/transport/interfaces/CMakeLists.txt	(revision 12060)
@@ -0,0 +1,45 @@
+# [License]
+# The Ariba-Underlay Copyright
+#
+# Copyright (c) 2008-2012, Institute of Telematics, UniversitÃ€t Karlsruhe (TH)
+#
+# Institute of Telematics
+# UniversitÃ€t Karlsruhe (TH)
+# Zirkel 2, 76128 Karlsruhe
+# Germany
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OF TELEMATICS OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# The views and conclusions contained in the software and documentation
+# are those of the authors and should not be interpreted as representing
+# official policies, either expressed or implied, of the Institute of
+# Telematics.
+# [License]
+
+add_headers(
+    transport_connection.hpp
+    transport_listener.hpp
+    transport_protocol.hpp
+)
+
+#add_sources()
Index: source/ariba/utility/transport/interfaces/transport_connection.hpp
===================================================================
--- source/ariba/utility/transport/interfaces/transport_connection.hpp	(revision 12060)
+++ source/ariba/utility/transport/interfaces/transport_connection.hpp	(revision 12060)
@@ -0,0 +1,60 @@
+#ifndef TRANSPORT_CONNECTION_HPP
+#define TRANSPORT_CONNECTION_HPP
+
+// ariba
+#include "ariba/utility/transport/messages/message.hpp"
+#include "ariba/utility/addressing2/endpoint.hpp"
+
+#include <vector>
+#include <boost/shared_ptr.hpp>
+
+namespace ariba {
+
+// forward declaration
+namespace utility {
+    class LinkID;
+}
+
+
+namespace transport {
+
+class transport_connection
+{
+public:
+    typedef boost::shared_ptr<transport_connection> sptr;
+    
+    /// Allow deleting implementing classes by pointer
+    virtual ~transport_connection() {}
+    
+    virtual bool send(reboost::message_t message, uint8_t priority = 1) = 0;
+    
+    virtual ariba::addressing2::EndpointPtr getLocalEndpoint() = 0;
+    virtual ariba::addressing2::EndpointPtr getRemoteEndpoint() = 0;
+
+    
+    /**
+     * Tells this transport_connection, that it's used by the given
+     * communication link.
+     */
+    virtual void register_communication_link(ariba::utility::LinkID* link) = 0;
+
+    /**
+     * Tells this transport_connection, that it's no longer used by the given
+     * communication link.
+     * 
+     * A transport_connection may terminate itself, when it's no longer used by
+     * any communication link.
+     */
+    virtual void unregister_communication_link(ariba::utility::LinkID* link) = 0;
+    
+    /**
+     * @return A vector of all registered communication links.
+     */
+    virtual std::vector<ariba::utility::LinkID*> get_communication_links() = 0;
+    
+    virtual void terminate() = 0;
+};
+
+} /* namespace transport */
+} /* namespace ariba */
+#endif /* TRANSPORT_CONNECTION_HPP */
Index: source/ariba/utility/transport/interfaces/transport_listener.hpp
===================================================================
--- source/ariba/utility/transport/interfaces/transport_listener.hpp	(revision 12060)
+++ source/ariba/utility/transport/interfaces/transport_listener.hpp	(revision 12060)
@@ -0,0 +1,39 @@
+// transport_listener.hpp, created on 01.07.2009 by Sebastian Mies
+
+#ifndef TRANSPORT_LISTENER_HPP
+#define TRANSPORT_LISTENER_HPP
+
+// ariba
+#include "ariba/utility/transport/messages/buffers.hpp"
+
+// ariba interfaces
+#include "transport_connection.hpp"
+
+// namespace ariba::transport
+namespace ariba {
+namespace transport {
+
+/**
+ * TODO: Doc
+ *
+ * @author Sebastian Mies <mies@tm.uka.de>
+ */
+class transport_listener {
+public:
+    /// Allow deleting implementing classes by pointer
+    virtual ~transport_listener() {}
+    
+	/// called when a message is received
+	virtual void receive_message(
+        transport_connection::sptr connection,
+		reboost::shared_buffer_t msg
+	) = 0;
+	
+	/// called when a connection is terminated (e.g. TCP close)
+	virtual void connection_terminated(transport_connection::sptr connection) = 0;
+};
+
+}} // namespace ariba::transport
+
+
+#endif /* TRANSPORT_LISTENER_HPP */
Index: source/ariba/utility/transport/interfaces/transport_protocol.hpp
===================================================================
--- source/ariba/utility/transport/interfaces/transport_protocol.hpp	(revision 12060)
+++ source/ariba/utility/transport/interfaces/transport_protocol.hpp	(revision 12060)
@@ -0,0 +1,56 @@
+#ifndef TRANSPORT_PROTOCOL_HPP_
+#define TRANSPORT_PROTOCOL_HPP_
+
+// ariba
+#include "ariba/utility/addressing2/endpoint_set.hpp"
+#include "ariba/utility/transport/messages/message.hpp"
+
+// ariba interfaces
+#include "transport_listener.hpp"
+
+// namespace ariba::transport
+namespace ariba {
+namespace transport {
+
+struct system_priority {
+    enum SEND_PRIORITY_INTERNAL {
+        HIGHEST = 0,
+        HIGH = 1,
+        ON_IDLE = 7
+    };
+    
+    static const SEND_PRIORITY_INTERNAL OVERLAY = HIGHEST;
+};
+
+
+
+/**
+ * TODO: Doc
+ *
+ * @author Sebastian Mies <mies@tm.uka.de>, Mario Hock
+ */
+class transport_protocol {
+public:
+    /// Allow deleting implementing classes by pointer
+    virtual ~transport_protocol() {}
+    
+	virtual void start() = 0;
+	virtual void stop() = 0;
+	
+	/**
+	 * @returns whether this connection is assumed to be valid 
+	 */
+	virtual void send(
+	        const addressing2::const_EndpointSetPtr endpoints,
+	        reboost::message_t message,
+	        uint8_t priority = system_priority::HIGH) = 0;
+	
+	/// @deprecated: Use terminate() from transport_connection instead
+//	virtual void terminate( const address_v* remote ) = 0;
+	
+	virtual void register_listener( transport_listener* listener ) = 0;
+};
+
+}} // namespace ariba::transport
+
+#endif /* TRANSPORT_PROTOCOL_HPP_ */
Index: source/ariba/utility/transport/messages/message.cpp
===================================================================
--- source/ariba/utility/transport/messages/message.cpp	(revision 11885)
+++ source/ariba/utility/transport/messages/message.cpp	(revision 12060)
@@ -24,5 +24,5 @@
 	os << "message({size=" << m.size() << ",buffers=" << (int) m.length()
 			<< ",hash=" << m.hash() << "},";
-	m.foreach(ts);
+	m.msg_foreach(ts);
 	os << ")";
 	return os;
Index: source/ariba/utility/transport/messages/message.hpp
===================================================================
--- source/ariba/utility/transport/messages/message.hpp	(revision 11885)
+++ source/ariba/utility/transport/messages/message.hpp	(revision 12060)
@@ -17,8 +17,11 @@
 
 /// message size type
-typedef signed char mlength_t;
+//typedef signed char mlength_t;  // <--- don't do this!!
+//typedef size_t mlength_t;
+typedef int mlength_t;  // signed int seems necessary
 
 /// maximum number of buffers per message (default is 8)
 const mlength_t message_max_buffers = (1L << 3);
+//const mlength_t message_max_buffers = (1L << 4);
 
 //! A Copy-on-Write Message with Shared Buffers.
@@ -70,6 +73,8 @@
 	/// Copy message
 	inline message_t(const message_t& msg) :
-		imsg(msg.imsg) {
-		imsg->owner = NULL;
+		imsg(msg.imsg)
+	{
+	    if ( imsg )
+	        imsg->owner = NULL;
 	}
 
@@ -142,4 +147,7 @@
 	/// Returns the number of buffers inside this message.
 	inline mlength_t length() const {
+	    if ( ! imsg )
+	        return 0;
+	    
 		return (imsg->length);
 	}
@@ -167,5 +175,5 @@
 	/// Iterates over a partial set of buffers.
 	template<typename T>
-	inline void foreach(const T& work, size_t index_ = 0, size_t size_ = 0) const {
+	inline void msg_foreach(const T& work, size_t index_ = 0, size_t size_ = 0) const {
 		T op = work;
 		if (size_ == 0) size_ = size() - index_;
@@ -192,5 +200,5 @@
 	inline void read(boctet_t* mem, size_t idx = 0, size_t size_ = 0) const {
 		struct read_buffer rb = { mem };
-		foreach(rb, idx, size_);
+		msg_foreach(rb, idx, size_);
 	}
 
@@ -198,5 +206,5 @@
 	inline void write(const boctet_t* mem, size_t idx = 0, size_t size_ = 0) {
 		struct write_buffer wb = { mem };
-		foreach(wb, idx, size_);
+		msg_foreach(wb, idx, size_);
 	}
 
@@ -227,5 +235,5 @@
 		message_t m;
 		struct sub_message sm = { &m };
-		foreach(sm, index, size);
+		msg_foreach(sm, index, size);
 		return m;
 	}
Index: source/ariba/utility/transport/messages/shared_buffer.hpp
===================================================================
--- source/ariba/utility/transport/messages/shared_buffer.hpp	(revision 11885)
+++ source/ariba/utility/transport/messages/shared_buffer.hpp	(revision 12060)
@@ -9,4 +9,5 @@
 
 #include <cstring>
+#include <string>
 #include <boost/shared_ptr.hpp>
 
@@ -18,5 +19,19 @@
 #include "buffer.hpp"
 
+#include <stdexcept> 
+
 namespace reboost {
+
+class illegal_sub_buffer: public std::runtime_error
+{
+public:
+    /** Takes a character string describing the error.  */
+    explicit illegal_sub_buffer(const std::string& __arg)  :
+        std::runtime_error(__arg)
+    {
+    }
+    
+    virtual ~illegal_sub_buffer() throw() {}
+};
 
 /**
@@ -104,8 +119,13 @@
 		parent(new deleteable_buffer(buffer, size))
 	{
+	}
+
+//    /// XXX debug... copy!
+//	/// create shared buffer from buffer
+//	inline shared_buffer_t(const char* buffer, bsize_t size) :
+//		buffer_t(), parent(new deleteable_buffer(size)) {
 //		memcpy(parent->mutable_data(), buffer, parent->size());
-//		data(parent->mutable_data());
-//		this->size(parent->size());
-	}
+//		data(parent->mutable_data()); this->size(parent->size());
+//	}
 
 	/// clone data from a normal buffer
@@ -129,5 +149,21 @@
 
 	/// return sub-buffer.
-	inline self operator()(bsize_t index, bsize_t size = 0) const {
+	inline self operator()(bsize_t index, bsize_t size = 0) const
+	{
+	    // special cases
+	    if ( index + size > size_ )
+	    {
+	        // empty sub-buffer
+            if ( index == size_ )
+            {
+                self n;
+                return n;
+            }
+         
+            // ERROR: index out of bounds
+            throw illegal_sub_buffer("Index or size out of bounds in shared_buffer"); 
+	    }
+
+	    // regular case
 		self n(*this);
 		n.data_ += index;
Index: source/ariba/utility/transport/rfcomm/CMakeLists.txt
===================================================================
--- source/ariba/utility/transport/rfcomm/CMakeLists.txt	(revision 11885)
+++ source/ariba/utility/transport/rfcomm/CMakeLists.txt	(revision 12060)
@@ -40,6 +40,6 @@
     bluetooth_endpoint.hpp
     bluetooth_rfcomm.hpp
-    rfcomm_transport.hpp
     )
 
-add_sources(rfcomm_transport.cpp)
+#add_sources()
+
Index: source/ariba/utility/transport/rfcomm/rfcomm_transport.cpp
===================================================================
--- source/ariba/utility/transport/rfcomm/rfcomm_transport.cpp	(revision 11885)
+++ 	(revision )
@@ -1,464 +1,0 @@
-#include "rfcomm_transport.hpp"
-
-#ifdef HAVE_LIBBLUETOOTH
-#include <boost/array.hpp>
-
-namespace ariba {
-namespace transport {
-
-use_logging_cpp(rfcomm_transport)
-
-using namespace ariba::addressing;
-
-typedef boost::mutex::scoped_lock unique_lock;
-
-/* constructor */
-rfcomm_transport::rfcomm_transport( const rfcomm_transport::rfcomm::endpoint& endp )  :
-        listener(NULL),
-        acceptor(u_io_service.get_asio_io_service(), endp)
-{
-}
-
-rfcomm_transport::~rfcomm_transport(){}
-
-void rfcomm_transport::start()
-{
-    // open server socket
-    accept();
-    
-    u_io_service.start();
-}
-
-
-void rfcomm_transport::stop()
-{
-    acceptor.close();
-    
-    u_io_service.stop();
-}
-
-
-/* see header file for comments */
-void rfcomm_transport::send(
-        const rfcomm::endpoint& dest_addr,
-        reboost::message_t message,
-        uint8_t priority)
-{
-    ConnPtr conn;
-    bool need_to_connect = false;
-    
-    {
-        unique_lock lock(connections_lock);
-        
-        ConnectionMap::iterator it = connections.find(dest_addr);
-        if (it == connections.end())
-        {
-            ConnPtr tmp_ptr(
-                    new rfcomm_connection(
-                            u_io_service.get_asio_io_service(),
-                            shared_from_this() )
-                    );
-            conn = tmp_ptr;
-            
-            conn->partner = dest_addr;
-            conn->remote = convert_address(dest_addr);
-            
-            // Note: starting the send is the obligation of the connect_handler
-            // (avoids trying to send while not connected yet)
-            conn->sending =  true;
-            need_to_connect = true;
-            
-            ConnectionMap::value_type item(dest_addr, conn);
-            connections.insert(item);
-            
-        } else {
-            conn = it->second;
-        }
-    }
-    
-    
-    // * the actual send *
-    conn->enqueue_for_sending(message, priority);
-    
-    // if new connection connect to the other party
-    if ( need_to_connect )
-    {
-        conn->sock.async_connect(
-                dest_addr,
-                boost::bind(
-                        &rfcomm_connection::async_connect_handler,
-                        conn,
-                        boost::asio::placeholders::error));
-    }
-}
-
-
-/* see header file for comments */
-void rfcomm_transport::send(
-        const address_v* remote,
-        reboost::message_t message,
-        uint8_t priority)
-{
-    send(convert_address(remote), message, priority);
-}
-
-
-/* see header file for comments */
-void rfcomm_transport::send(
-        const endpoint_set& endpoints,
-        reboost::message_t message,
-        uint8_t priority )
-{
-    // send a message to each combination of address-address and port
-    BOOST_FOREACH( const mac_address mac, endpoints.bluetooth ) {
-        BOOST_FOREACH( const rfcomm_channel_address channel, endpoints.rfcomm ) {
-            rfcomm::endpoint endp(mac.bluetooth(), channel.value());
-            
-            // * send *
-            send(endp, message, priority);
-        }
-    }
-}
-
-
-void rfcomm_transport::register_listener( transport_listener* listener )
-{
-    this->listener = listener;
-}
-
-
-void rfcomm_transport::terminate( const address_v* remote )
-{
-    terminate(convert_address(remote));
-}
-
-void rfcomm_transport::terminate( const rfcomm::endpoint& remote )
-{
-    ConnPtr conn;
-    
-    // find and forget connection
-    {
-        unique_lock lock(connections_lock);
-        
-        ConnectionMap::iterator it = connections.find(remote);
-        if (it == connections.end())
-        {
-            return;
-        }
-        
-        conn = it->second;
-        
-        connections.erase(it);
-    }
-
-    // close connection
-    boost::system::error_code ec;
-    conn->sock.shutdown(tcp::socket::shutdown_both, ec);
-    conn->sock.close(ec);
-}
-
-
-/* private */
-void rfcomm_transport::accept()
-{
-    // create new connection object
-    ConnPtr conn(
-            new rfcomm_connection(
-                    u_io_service.get_asio_io_service(),
-                    shared_from_this()
-            )
-    );
-    
-    // wait for incoming connection
-    acceptor.async_accept(
-            conn->sock,
-            boost::bind(&self::async_accept_handler,
-                    this->shared_from_this(),
-                    conn,
-                    boost::asio::placeholders::error)
-    );
-}
-
-void rfcomm_transport::async_accept_handler(ConnPtr conn, const error_code& error)
-{
-    if ( ! error )
-    {
-        conn->partner = conn->sock.remote_endpoint();
-        conn->remote = convert_address(conn->partner);
-        conn->local = convert_address(conn->sock.local_endpoint());
-        
-        {
-            unique_lock lock(connections_lock);
-            
-            ConnectionMap::value_type item(conn->sock.remote_endpoint(), conn);
-            connections.insert(item);
-        }
-        
-        // read
-        conn->listen();
-    }
-    
-    // accept further connections
-    accept();
-}
-
-inline rfcomm_transport::rfcomm::endpoint 
-rfcomm_transport::convert_address( const address_v* address )
-{
-    rfcomm_endpoint endpoint = *address;
-    
-    return rfcomm::endpoint(
-        endpoint.mac().bluetooth(), endpoint.channel().value()
-    );
-}
-
-
-inline rfcomm_endpoint rfcomm_transport::convert_address(const rfcomm::endpoint& endpoint)
-{
-    mac_address mac;
-    mac.bluetooth(endpoint.address());
-    rfcomm_channel_address channel;
-    channel.value(endpoint.channel());
-    return rfcomm_endpoint(mac, channel);
-}
-
-
-/*****************
- ** inner class **
- *****************/
-
-rfcomm_transport::rfcomm_connection::rfcomm_connection(
-    boost::asio::io_service & io_service,
-    rfcomm_transport::sptr parent)  :
-        sock(io_service),
-        valid(true),
-        parent(parent),
-        out_queues(8), //TODO How much priorities shall we have?
-        sending(false)
-{
-        header.length = 0;
-        header.prot = 0;
-}
-
-/*-------------------------------------------
- | implement transport_connection interface |
- -------------------------------------------*/
-void rfcomm_transport::rfcomm_connection::send(
-        reboost::message_t message,
-        uint8_t priority)
-{
-    enqueue_for_sending(message, priority);
-}
-
-
-address_vf rfcomm_transport::rfcomm_connection::getLocalEndpoint()
-{
-    return local;
-}
-
-
-address_vf rfcomm_transport::rfcomm_connection::getRemoteEndpoint()
-{
-    return remote;
-}
-
-
-void rfcomm_transport::rfcomm_connection::terminate()
-{
-    parent->terminate(partner);
-}
-
-
-/*------------------------------
- | things we defined ourselves |
- ------------------------------*/
-void rfcomm_transport::rfcomm_connection::async_connect_handler(const error_code& error)
-{
-    if (error)
-    {
-        parent->terminate(partner);
-
-        return;
-    }
-    
-    // save address in ariba format
-    local = parent->convert_address(sock.local_endpoint());
-    
-    // Note: sending has to be true at this point
-    send_next_package();
-    
-    listen();
-}
-
-
-void rfcomm_transport::rfcomm_connection::listen()
-{
-    boost::asio::async_read(
-            this->sock,
-            boost::asio::mutable_buffers_1(&this->header, sizeof(header_t)),
-            boost::bind(
-                    &rfcomm_transport::rfcomm_connection::async_read_header_handler,
-                    this->shared_from_this(),
-                    boost::asio::placeholders::error,
-                    boost::asio::placeholders::bytes_transferred
-            )
-    );
-}
-
-
-void rfcomm_transport::rfcomm_connection::async_read_header_handler(const error_code& error, size_t bytes_transferred)
-{
-    if (error)
-    {
-        parent->terminate(partner);
-
-        return;
-    }
-
-    // convert byte order
-    header.length = ntohl(header.length);
-    header.length -= 2;  // XXX protlib
-    
-    assert(header.length > 0);
-    
-    // new buffer for the new packet
-    buffy = shared_buffer_t(header.length);
-
-    // * read data *
-    boost::asio::async_read(
-            this->sock,
-            boost::asio::buffer(buffy.mutable_data(), buffy.size()),
-            boost::bind(
-                    &rfcomm_transport::rfcomm_connection::async_read_data_handler,
-                    this->shared_from_this(),
-                    boost::asio::placeholders::error,
-                    boost::asio::placeholders::bytes_transferred
-            )
-    );
-}
-
-void rfcomm_transport::rfcomm_connection::async_read_data_handler(
-        const error_code& error, size_t bytes_transferred)
-{
-    if (error)
-    {
-        parent->terminate(partner);
-
-        return;
-    }
-    
-    message_t msg;
-    msg.push_back(buffy);
-    buffy = shared_buffer_t();
-
-    if ( parent->listener )
-        parent->listener->receive_message(shared_from_this(), msg);
-    
-    listen();
-}
-
-/* see header file for comments */
-void rfcomm_transport::rfcomm_connection::async_write_handler(reboost::shared_buffer_t packet, const error_code& error, size_t bytes_transferred)
-{
-    if ( error )
-    {        
-        // remove this connection
-        parent->terminate(partner); 
-
-        return;
-    }
-    
-    send_next_package();
-}
-
-
-
-void rfcomm_transport::rfcomm_connection::enqueue_for_sending(Packet packet, uint8_t priority)
-{
-    bool restart_sending = false;
-    
-    // enqueue packet  [locked]
-    {
-        unique_lock(out_queues_lock);
-        
-        assert( priority < out_queues.size() );
-        out_queues[priority].push(packet);
-        
-        if ( ! sending )
-        {
-            restart_sending = true;
-            sending = true;
-        }
-    }
-    
-    // if sending was stopped, we have to restart it here
-    if ( restart_sending )
-    {
-        send_next_package();
-    }
-}
-
-/* see header file for comments */
-void rfcomm_transport::rfcomm_connection::send_next_package()
-{
-    Packet packet;
-    bool found = false;
-
-    // find packet with highest priority  [locked]
-    {
-        unique_lock(out_queues_lock);
-        
-        for ( vector<OutQueue>::iterator it = out_queues.begin();
-                it != out_queues.end(); it++ )
-        {
-            if ( !it->empty() )
-            {
-                packet = it->front();
-                it->pop();
-                found = true;
-                
-                break;
-            }
-        }
-        
-        // no packets waiting --> stop sending
-        if ( ! found )
-        {
-            sending = false;
-        }
-    }
-    
-    // * send *
-    if ( found )
-    {
-        reboost::shared_buffer_t header_buf(sizeof(header_t));
-        header_t* header = (header_t*)(header_buf.mutable_data());
-        header->length = htonl(packet.size()+2);  // XXX protlib
-        
-        packet.push_front(header_buf);
-        
-        // "convert" message to asio buffer sequence
-        vector<boost::asio::const_buffer> send_sequence(packet.length());
-        for ( int i=0; i < packet.length(); i++ )
-        {
-            shared_buffer_t b = packet.at(i);
-            send_sequence.push_back(boost::asio::buffer(b.data(), b.size()));
-        }
-        
-        // * async write *
-        boost::asio::async_write(
-                this->sock,
-                send_sequence,
-                boost::bind(
-                        &rfcomm_transport::rfcomm_connection::async_write_handler,
-                        this->shared_from_this(),
-                        packet,  // makes sure our shared pointer lives long enough ;-)
-                        boost::asio::placeholders::error,
-                        boost::asio::placeholders::bytes_transferred)
-        );
-    }
-}
-
-}} // namespace ariba::transport
-
-#endif /* HAVE_LIBBLUETOOTH */
Index: source/ariba/utility/transport/rfcomm/rfcomm_transport.hpp
===================================================================
--- source/ariba/utility/transport/rfcomm/rfcomm_transport.hpp	(revision 11885)
+++ 	(revision )
@@ -1,170 +1,0 @@
-#include "ariba/config.h"
-
-#ifdef HAVE_LIBBLUETOOTH
-
-#ifndef RFCOMM_TRANSPORT_HPP_
-#define RFCOMM_TRANSPORT_HPP_
-
-#include "ariba/utility/transport/transport.hpp"
-#include "ariba/utility/transport/asio/unique_io_service.h"
-#include "ariba/utility/transport/transport_connection.hpp"
-#include "ariba/utility/addressing/rfcomm_endpoint.hpp"
-#include <boost/asio.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
-#include <queue>
-#include "ariba/utility/transport/messages/buffers.hpp"
-#include "ariba/utility/logging/Logging.h"
-#include "bluetooth_rfcomm.hpp"
-
-namespace ariba {
-namespace transport {
-
-using namespace std;
-using ariba::transport::detail::unique_io_service;
-using ariba::addressing::rfcomm_endpoint;
-using boost::system::error_code;
-using reboost::shared_buffer_t;
-using reboost::message_t;
-
-
-class rfcomm_transport :
-    public transport_protocol,
-    public boost::enable_shared_from_this<rfcomm_transport>
-{
-public:
-	typedef boost::shared_ptr<rfcomm_transport> sptr;
-
-private:
-    typedef rfcomm_transport self;
-    typedef boost::asio::bluetooth::rfcomm rfcomm;
-    use_logging_h(rfcomm_transport)
-
-    class rfcomm_connection :
-        public transport_connection,
-        public boost::enable_shared_from_this<rfcomm_connection>
-    {
-    public:
-        typedef reboost::message_t Packet;
-        typedef std::queue<Packet> OutQueue;
-        
-        struct header_t
-        {
-            uint32_t length;
-            uint16_t prot;  // XXX protlib
-        } __attribute__((packed));
-            
-        rfcomm_connection(boost::asio::io_service& io_service,
-                rfcomm_transport::sptr parent);
-        
-        /// Inherited from transport_connection
-        virtual void send(reboost::message_t message, uint8_t priority = 0);
-        virtual address_vf getLocalEndpoint();
-        virtual address_vf getRemoteEndpoint();
-        virtual void terminate();
-        
-        void listen();
-        
-        void async_connect_handler(const error_code& error);
-        
-        void async_read_header_handler(const error_code& error, size_t bytes_transferred);
-        void async_read_data_handler(const error_code& error, size_t bytes_transferred);
-        
-        /*
-         * is called from asio when write operation "returns",
-         * calls private function `send_next_package()`
-         */
-        void async_write_handler(
-                reboost::shared_buffer_t packet,
-                const error_code& error,
-                size_t bytes_transferred);
-
-        
-        void enqueue_for_sending(Packet packet, uint8_t priority);
-        
-    private:
-        /*
-         * is called from `send` or `async_write_handler` to begin/keep sending
-         * sends the next message with the highest priority in this connection
-         */
-        void send_next_package();
-
-
-    public:
-        rfcomm::socket sock;
-        bool valid;
-        rfcomm_transport::sptr parent;
-        
-        rfcomm::endpoint partner;
-        rfcomm_endpoint remote;
-        rfcomm_endpoint local;
-        
-        vector<OutQueue> out_queues;     // to be locked with out_queues_lock 
-        boost::mutex out_queues_lock;
-        
-        bool sending;       // to be locked with out_queues_lock
-        
-        header_t header;
-        shared_buffer_t buffy;
-    };
-    typedef boost::shared_ptr<rfcomm_connection> ConnPtr;
-    typedef std::map<rfcomm::endpoint, ConnPtr> ConnectionMap;
-    
-public:
-    /* constructor */
-	rfcomm_transport( const rfcomm::endpoint& endp );
-	virtual ~rfcomm_transport();
-	
-	virtual void start();
-	virtual void stop();
-	
-	/**
-     * enqueues message for sending
-     * create new connection if necessary
-     * starts sending mechanism (if not already running)
-     */
-    void send(
-            const rfcomm::endpoint&,
-            reboost::message_t message,
-            uint8_t priority = 0 );
-	
-	/**
-	 * Converts address_v to rfcomm::endpoint and calls the real send() function
-	 */
-	virtual void send(
-	        const address_v* remote,
-	        reboost::message_t message,
-	        uint8_t priority = 0 );
-	
-	/**
-	 * calls send for each destination endpoint in `endpoint_set& endpoints` 
-	 */
-	virtual void send(
-	        const endpoint_set& endpoints,
-	        reboost::message_t message,
-	        uint8_t priority = 0 );
-	
-	virtual void terminate( const address_v* remote );
-	virtual void terminate( const rfcomm::endpoint& remote );
-	virtual void register_listener( transport_listener* listener );
-
-	
-private:
-	void accept();
-	void async_accept_handler(ConnPtr conn, const error_code& error);
-	rfcomm::endpoint convert_address(const address_v* endpoint);
-	rfcomm_endpoint convert_address(const rfcomm::endpoint& endpoint);
-	
-private:
-	transport_listener* listener;
-	unique_io_service u_io_service;
-	rfcomm::acceptor acceptor;
-	
-	ConnectionMap connections;
-	boost::mutex connections_lock;
-};
-
-}} // namespace ariba::transport
-
-#endif /* RFCOMM_TRANSPORT_HPP_ */
-#endif /* HAVE_LIBBLUETOOTH */
Index: source/ariba/utility/transport/test_transport.hpp
===================================================================
--- source/ariba/utility/transport/test_transport.hpp	(revision 11885)
+++ 	(revision )
@@ -1,82 +1,0 @@
-// test_transport.hpp, created on 01.07.2009 by Sebastian Mies
-
-#ifndef TEST_TRANSPORT_HPP_
-#define TEST_TRANSPORT_HPP_
-
-#include "transport_peer.hpp"
-#include "transport_listener.hpp"
-
-#include "rfcomm/rfcomm.hpp"
-
-#include <iostream>
-#include <string>
-#include <sys/types.h>
-#include <unistd.h>
-
-namespace ariba {
-namespace transport {
-namespace detail {
-
-using namespace std;
-using namespace ariba::transport;
-using namespace ariba::addressing;
-
-class listener : public transport_listener {
-public:
-	virtual void receive_message(
-		transport_protocol* transport,
-		const address_vf local, const address_vf remote,
-		const uint8_t* data, size_t size
-	) {
-		cout << "transport_listener: " << endl;
-		cout << "received message data='" << data << "' local=" << local->to_string() << " remote=" << remote->to_string() << endl;
-	}
-};
-
-void test_transport_process( endpoint_set& local, endpoint_set& remote ) {
-	cout << "started " << local.to_string() << endl;
-	transport_peer* peer = new transport_peer( local );
-	peer->register_listener( new listener() );
-	peer->start();
-	peer->send( remote, (uint8_t*)"Hello!", 7 );
-	getchar();
-}
-
-/**
- * TODO: Doc
- *
- * @author Sebastian Mies <mies@tm.uka.de>
- */
-void tcp_test() {
-
-	endpoint_set local  = string("tcp{5001};ip{127.0.0.1 | 2001:638:204:6:216:d3ff:fece:1070}");
-	endpoint_set remote = string("tcp{5002};ip{127.0.0.1 | 2001:638:204:6:216:d3ff:fece:1070}");
-
-	pid_t pID = fork();
-	if (pID < 0) {
-		cerr << "Failed to fork" << endl;
-	} else
-	if (pID == 0) {
-		test_transport_process(local,remote);
-	} else {
-		getchar();
-		test_transport_process(remote,local);
-	}
-	getchar();
-}
-
-void bluetooth_test( string& endp_str ) {
-	cout << endp_str << endl;
-	rfcomm* rfc = new rfcomm( 3 );
-	rfc->register_listener( new listener() );
-	rfc->start();
-	if (endp_str.size()!=0) {
-		rfcomm_endpoint endp = endp_str;
-		rfc->send( endp, (uint8_t*)"Hello!", 7 );
-	}
-	getchar();
-}
-
-}}} // namespace ariba::transport::detail
-
-#endif /* TEST_TRANSPORT_HPP_ */
Index: source/ariba/utility/transport/transport.hpp
===================================================================
--- source/ariba/utility/transport/transport.hpp	(revision 11885)
+++ 	(revision )
@@ -1,15 +1,0 @@
-#ifndef TRANSPORT_HPP_
-#define TRANSPORT_HPP_
-
-// abstract classes
-#include "transport_protocol.hpp"
-#include "transport_listener.hpp"
-
-// transport protocol implementations
-#include "tcpip/tcpip.hpp"
-#include "rfcomm/rfcomm_transport.hpp"
-
-// common transport peer using all known protocols
-#include "transport_peer.hpp"
-
-#endif /* TRANSPORT_HPP_ */
Index: source/ariba/utility/transport/transport_connection.hpp
===================================================================
--- source/ariba/utility/transport/transport_connection.hpp	(revision 11885)
+++ 	(revision )
@@ -1,32 +1,0 @@
-
-#ifndef TRANSPORT_CONNECTION_HPP_
-#define TRANSPORT_CONNECTION_HPP_
-
-#include "ariba/utility/addressing/addressing.hpp"
-#include "ariba/utility/transport/messages/message.hpp"
-#include <boost/shared_ptr.hpp>
-
-using ariba::addressing::address_vf;
-
-namespace ariba {
-namespace transport {
-
-class transport_connection
-{
-public:
-    typedef boost::shared_ptr<transport_connection> sptr;
-    
-    /// Allow deleting implementing classes by pointer
-    virtual ~transport_connection() {}
-    
-    virtual void send(reboost::message_t message, uint8_t priority = 0) = 0;
-    
-    virtual address_vf getLocalEndpoint() = 0;
-    virtual address_vf getRemoteEndpoint() = 0;
-    
-    virtual void terminate() = 0;
-};
-
-} /* namespace transport */
-} /* namespace ariba */
-#endif /* TRANSPORT_CONNECTION_HPP_ */
Index: source/ariba/utility/transport/transport_listener.hpp
===================================================================
--- source/ariba/utility/transport/transport_listener.hpp	(revision 11885)
+++ 	(revision )
@@ -1,38 +1,0 @@
-// transport_listener.hpp, created on 01.07.2009 by Sebastian Mies
-
-#ifndef TRANSPORT_LISTENER_HPP_
-#define TRANSPORT_LISTENER_HPP_
-
-#include "ariba/utility/addressing/addressing.hpp"
-#include "ariba/utility/transport/messages/buffers.hpp"
-#include "ariba/utility/transport/transport_connection.hpp"
-
-// namespace ariba::transport
-namespace ariba {
-namespace transport {
-
-using namespace ariba::addressing;
-
-/**
- * TODO: Doc
- *
- * @author Sebastian Mies <mies@tm.uka.de>
- */
-class transport_listener {
-public:
-    /// Allow deleting implementing classes by pointer
-    virtual ~transport_listener() {}
-    
-	/// called when a message is received
-	virtual void receive_message(
-        transport_connection::sptr connection,
-		reboost::message_t msg
-	) {
-		std::cout << "transport_listener: not implemented" << std::endl;
-	}
-};
-
-}} // namespace ariba::transport
-
-
-#endif /* TRANSPORT_LISTENER_HPP_ */
Index: source/ariba/utility/transport/transport_peer.cpp
===================================================================
--- source/ariba/utility/transport/transport_peer.cpp	(revision 11885)
+++ source/ariba/utility/transport/transport_peer.cpp	(revision 12060)
@@ -1,15 +1,11 @@
-
-#include "ariba/config.h"
 #include "transport_peer.hpp"
-#include "transport.hpp"
-#include <boost/asio/ip/tcp.hpp>
+
+// ariba
+#include "StreamTransport/StreamTransport.hpp"
+#include "ariba/utility/addressing2/tcpip_endpoint.hpp"
+
+// boost
 #include <boost/asio/error.hpp>
 #include <boost/foreach.hpp>
-
-#ifdef ECLIPSE_PARSER
-    #define foreach(a, b) for(a : b)
-#else
-    #define foreach(a, b) BOOST_FOREACH(a, b)
-#endif
 
 // namespace ariba::transport
@@ -17,5 +13,5 @@
 namespace transport {
 
-using namespace ariba::addressing;
+using namespace addressing2;
 using boost::asio::ip::tcp;
 
@@ -26,74 +22,136 @@
 use_logging_cpp(transport_peer);
 
-transport_peer::transport_peer( endpoint_set& local_set ) : local(local_set) {
-    
-    // setup tcp transports
-    foreach(tcp_port_address port, local.tcp) {
+transport_peer::transport_peer()  :
+        local(new addressing2::endpoint_set())
+{
+}
+
+EndpointSetPtr transport_peer::add_listenOn_endpoints(EndpointSetPtr endpoints)
+{
+    // TCP Endpoints
+    BOOST_FOREACH( shared_ptr<tcpip_endpoint> endp, endpoints->get_tcpip_endpoints() )
+    {
+        // automatic port detection
+        bool port_detection = false;
+        uint16_t try_port = 41322;
         
-        if (local.ip.size() > 0) {
-            foreach(ip_address ip_addr, local.ip) {
-                
-                tcp::endpoint endp(ip_addr.asio(), port.asio());
-                create_service(endp);
-            }
-        } else {
-            tcp::endpoint endp_v6(tcp::v6(), port.asio());
-            tcp::endpoint endp_v4(tcp::v4(), port.asio());
-            
-            create_service(endp_v6);
-            create_service(endp_v4);
+        tcp::endpoint asio_endp = endp->to_asio();
+        if ( asio_endp.port() == 0 )
+        {
+            port_detection = true;
         }
         
-    }
-    
+        
+        // create new server socket
+        do
+        {
+            try
+            {
+                // automatic port detection
+                if ( port_detection )
+                {
+                    asio_endp.port(try_port);
+                    endp = tcpip_endpoint::create_TcpIP_Endpoint(asio_endp);
+                }
+                
+                TransportProtocolPtr tmp_ptr(new StreamTransport<tcp>(endp->to_asio()));
+                transport_streams.push_back(tmp_ptr);
+                logging_info("Listening on IP/TCP " << endp->to_string());
+                
+                local->add_endpoint(endp);
+                port_detection = false;
+            }
+            
+            catch (boost::system::system_error& e)
+            {
+                // address in use
+                if (e.code() == boost::asio::error::address_in_use)
+                {
+                    // BRANCH: automatic port detection
+                    if ( port_detection )
+                    {
+                        // give up ?
+                        if ( try_port > 41422 )
+                        {
+                            logging_warn("[WARN] Unable to find free port. Giving up. :-( Last try was: "
+                                << endp->to_string() << ". Endpoint will be ignored!");
+    
+                            port_detection = false;
+                        }
+                        else
+                        {
+                            // try next port
+                            try_port++;
+                        }
+                    }
+                    // BRANCH: explicit given port --> error
+                    else
+                    {
+                        logging_warn("[WARN] Address already in use: "
+                            << endp->to_string() << ". Endpoint will be ignored!");
+                    }
+                }
+    
+                // Rethrow
+                else
+                {
+                    throw;
+                }
+            }
+        } while ( port_detection );
+    }
+    
+    // TODO Bluetooth Endpoints
 	#ifdef HAVE_LIBBLUETOOTH
-    foreach(rfcomm_channel_address channel, local.rfcomm) {
-    	if (local.bluetooth.size() > 0) {
-    		foreach(mac_address mac, local.bluetooth) {
-    			rfcomm::endpoint endp(mac.bluetooth(), channel.value());
-    			create_service(endp);
-    		}
-    	} else {
-    		rfcomm::endpoint endp(channel.value());
-    		create_service(endp);
-    	}
-    }
+//    foreach(rfcomm_channel_address channel, local.rfcomm) {
+//    	if (local.bluetooth.size() > 0) {
+//    		foreach(mac_address mac, local.bluetooth) {
+//    			rfcomm::endpoint endp(mac.bluetooth(), channel.value());
+//    			create_service(endp);
+//    		}
+//    	} else {
+//    		rfcomm::endpoint endp(channel.value());
+//    		create_service(endp);
+//    	}
+//    }
 	#endif
-}
-
-void transport_peer::create_service(tcp::endpoint endp) {
-    try {
-        TcpIpPtr tmp_ptr(new tcpip(endp));
-        tcps.push_back(tmp_ptr);
-        logging_info("Listening on IP/TCP " << endp);
-        
-    } catch (boost::system::system_error& e) {
-        if (e.code() == boost::asio::error::address_in_use) {
-            logging_warn("[WARN] Address already in use: "
-                    << endp << ". Endpoint will be ignored!");
-        } else {
-            // Rethrow
-            throw;
-        }
-    }
-}
+    
+    return local;
+}
+
+//void transport_peer::create_service(tcp::endpoint endp) {
+//    try {
+//        TransportProtocolPtr tmp_ptr(new StreamTransport<tcp>(endp));
+//        tcps.push_back(tmp_ptr);
+//        logging_info("Listening on IP/TCP " << endp);
+//        
+//    } catch (boost::system::system_error& e) {
+//        if (e.code() == boost::asio::error::address_in_use) {
+//            logging_warn("[WARN] Address already in use: "
+//                    << endp << ". Endpoint will be ignored!");
+//        } else {
+//            // Rethrow
+//            throw;
+//        }
+//    }
+//}
 
 #ifdef HAVE_LIBBLUETOOTH
-void transport_peer::create_service(rfcomm::endpoint endp) {
-    try {
-        rfcomm_transport::sptr tmp_ptr(new rfcomm_transport(endp));
-        rfcomms.push_back(tmp_ptr);
-        logging_info("Listening on bluetooth/RFCOMM " << endp);
-        
-    } catch (boost::system::system_error& e) {
-        if (e.code() == boost::asio::error::address_in_use) {
-            logging_warn("[WARN] Address already in use: "
-                    << endp << ". Endpoint will be ignored!");
-        } else {
-            // Rethrow
-            throw;
-        }
-    }
-}
+//void transport_peer::create_service(rfcomm::endpoint endp) {
+//    try {
+//        TransportProtocolPtr tmp_ptr(new StreamTransport<rfcomm>(endp));
+//        rfcomms.push_back(tmp_ptr);
+//        logging_info("Listening on bluetooth/RFCOMM " << endp);
+//        
+//    } catch (boost::system::system_error& e) {
+//        if (e.code() == boost::asio::error::address_in_use) {
+//            logging_warn("[WARN] Address already in use: "
+//                    << endp << ". Endpoint will be ignored!");
+//        } else {
+//            // Rethrow
+//            throw;
+//        }
+//    }
+//}
 #endif
 
@@ -101,71 +159,55 @@
 }
 
-void transport_peer::start() {
-    foreach(TcpIpPtr tcp, tcps) {
-        tcp->start();
-    }
-    
-#ifdef HAVE_LIBBLUETOOTH
-    foreach(rfcomm_transport::sptr x, rfcomms) {
-    	x->start();
-    }
-#endif
-}
-
-void transport_peer::stop() {
-    foreach(TcpIpPtr tcp, tcps) {
-        tcp->stop();
-    }
-    
-#ifdef HAVE_LIBBLUETOOTH
-	foreach(rfcomm_transport::sptr x, rfcomms) {
-		x->stop();
-	}
-#endif
+void transport_peer::start()
+{
+    BOOST_FOREACH(TransportProtocolPtr stream, transport_streams)
+    {
+        stream->start();
+    }
+}
+
+void transport_peer::stop()
+{
+    BOOST_FOREACH(TransportProtocolPtr stream, transport_streams)
+    {
+        stream->stop();
+    }
 }
 
 
 void transport_peer::send(
-        const endpoint_set& endpoints,
+        const const_EndpointSetPtr endpoints,
         reboost::message_t message,
         uint8_t priority)
 {
-    foreach(TcpIpPtr tcp, tcps) {
-        tcp->send(endpoints, message, priority);
-    }
-    
-#ifdef HAVE_LIBBLUETOOTH
-    foreach(rfcomm_transport::sptr x, rfcomms) {
-		x->send(endpoints, message, priority);
-	}
-#endif
-}
-
-void transport_peer::terminate( const address_v* remote ) {
-	if (remote->instanceof<tcpip_endpoint>())// TODO direkt auf der richtigen verbindung
-	{
-	    foreach(TcpIpPtr tcp, tcps) {
-	        tcp->terminate(remote);
-	    }
-	}
-#ifdef HAVE_LIBBLUETOOTH
-	if (remote->instanceof<rfcomm_endpoint>()) {
-		foreach(rfcomm_transport::sptr x, rfcomms) {
-			x->terminate(remote);
-		}
-	}
-#endif
-}
-
-void transport_peer::register_listener( transport_listener* listener ) {
-    foreach(TcpIpPtr tcp, tcps) {
-        tcp->register_listener(listener);
-    }
-    
-#ifdef HAVE_LIBBLUETOOTH
-    foreach(rfcomm_transport::sptr x, rfcomms) {
-    	x->register_listener(listener);
-    }
-#endif
+    BOOST_FOREACH(TransportProtocolPtr stream, transport_streams)
+    {
+        stream->send(endpoints, message, priority);
+    }
+}
+
+// XXX DEPRECATED
+//void transport_peer::terminate( const address_v* remote ) {
+//	if (remote->instanceof<tcpip_endpoint>())// TODO direkt auf der richtigen verbindung
+//	{
+//	    foreach(TransportProtocolPtr tcp, tcps) {
+//	        tcp->terminate(remote);
+//	    }
+//	}
+//#ifdef HAVE_LIBBLUETOOTH
+//	if (remote->instanceof<rfcomm_endpoint>()) {
+//		foreach(TransportProtocolPtr x, rfcomms) {
+//			x->terminate(remote);
+//		}
+//	}
+//#endif
+//}
+
+void transport_peer::register_listener( transport_listener* listener )
+{
+    BOOST_FOREACH(TransportProtocolPtr stream, transport_streams)
+    {
+        stream->register_listener(listener);
+    }
 }
 
Index: source/ariba/utility/transport/transport_peer.hpp
===================================================================
--- source/ariba/utility/transport/transport_peer.hpp	(revision 11885)
+++ source/ariba/utility/transport/transport_peer.hpp	(revision 12060)
@@ -2,10 +2,17 @@
 #define TRANSPORT_PEER_HPP_
 
+// ariba
 #include "ariba/config.h"
 #include "ariba/utility/logging/Logging.h"
-#include "transport_protocol.hpp"
-#include "ariba/utility/addressing/endpoint_set.hpp"
+#include "ariba/utility/addressing2/endpoint_set.hpp"
+
+// ariba interfaces
+#include "interfaces/transport_protocol.hpp"
+
+// boost
 #include <boost/shared_ptr.hpp>
-#include "rfcomm/bluetooth_rfcomm.hpp"
+
+// boost-adaption
+//#include "rfcomm/bluetooth_rfcomm.hpp"
 
 
@@ -14,23 +21,26 @@
 namespace transport {
 
-using namespace ariba::addressing;
-
-class tcpip;
-
-#ifdef HAVE_LIBBLUETOOTH
-class rfcomm_transport;
-#endif
-
 /**
- * TODO: Doc
+ * This class allocates implementations of various transport
+ * protocols and can send messages to an entire set of endpoints
  *
- * @author Sebastian Mies <mies@tm.uka.de>
+ * @author Sebastian Mies <mies@tm.uka.de>, Mario Hock
  */
-/// this transport peer allocates implementations of various transport
-/// protocols and can send messages to an entire set of endpoints
-class transport_peer : public transport_protocol {
+class transport_peer :
+    public transport_protocol
+{
 	use_logging_h(transport_peer);
+	typedef boost::shared_ptr<transport_protocol> TransportProtocolPtr;
+	
 public:
-	transport_peer( endpoint_set& local_set );
+	transport_peer();
+	
+	/**
+	 * Adds endpoints on which ariba should listen ("server"-sockets)
+	 * 
+	 * @return An endpoint_set holding all active endpoints ariba is listening on.   
+	 */
+	addressing2::EndpointSetPtr add_listenOn_endpoints(addressing2::EndpointSetPtr endpoints);
+	
 	virtual ~transport_peer();
 	virtual void start();
@@ -38,24 +48,14 @@
 	
 	virtual void send(
-	        const endpoint_set& endpoints,
+	        const addressing2::const_EndpointSetPtr endpoints,
 	        reboost::message_t message,
-	        uint8_t priority = 0);
-	
-	/// @deprecated: Use terminate() from transport_connection instead
-	virtual void terminate( const address_v* remote );
-	
+	        uint8_t priority = system_priority::OVERLAY);
+		
 	virtual void register_listener( transport_listener* listener );
 
+	
 private:
-	void create_service(tcp::endpoint endp);
-#ifdef HAVE_LIBBLUETOOTH
-	void create_service(boost::asio::bluetooth::rfcomm::endpoint endp);
-#endif
-	
-	endpoint_set&  local;
-	std::vector< boost::shared_ptr<tcpip> > tcps;
-#ifdef HAVE_LIBBLUETOOTH
-	std::vector< boost::shared_ptr<rfcomm_transport> > rfcomms;
-#endif
+	addressing2::EndpointSetPtr local;
+	std::vector<TransportProtocolPtr> transport_streams;
 };
 
Index: source/ariba/utility/transport/transport_protocol.hpp
===================================================================
--- source/ariba/utility/transport/transport_protocol.hpp	(revision 11885)
+++ 	(revision )
@@ -1,40 +1,0 @@
-#ifndef TRANSPORT_PROTOCOL_HPP_
-#define TRANSPORT_PROTOCOL_HPP_
-
-#include "ariba/utility/addressing/addressing.hpp"
-#include "ariba/utility/transport/transport_listener.hpp"
-#include "ariba/utility/transport/messages/message.hpp"
-
-// namespace ariba::transport
-namespace ariba {
-namespace transport {
-
-using namespace ariba::addressing;
-
-/**
- * TODO: Doc
- *
- * @author Sebastian Mies <mies@tm.uka.de>
- */
-class transport_protocol {
-public:
-    /// Allow deleting implementing classes by pointer
-    virtual ~transport_protocol() {}
-    
-	virtual void start() = 0;
-	virtual void stop() = 0;
-	
-	virtual void send(
-	        const endpoint_set& endpoints,
-	        reboost::message_t message,
-	        uint8_t priority = 0) = 0;
-	
-	/// @deprecated: Use terminate() from transport_connection instead
-	virtual void terminate( const address_v* remote ) = 0;
-	
-	virtual void register_listener( transport_listener* listener ) = 0;
-};
-
-}} // namespace ariba::transport
-
-#endif /* TRANSPORT_PROTOCOL_HPP_ */
Index: source/ariba/utility/types/Identifier.h
===================================================================
--- source/ariba/utility/types/Identifier.h	(revision 11885)
+++ source/ariba/utility/types/Identifier.h	(revision 12060)
@@ -50,4 +50,7 @@
 #include "ariba/utility/serialization.h"
 
+// XXX EXPERIMENTAL
+#include "ariba/utility/transport/messages/shared_buffer.hpp"
+
 /**< maximum length of the key */
 #define MAX_KEYLENGTH 192
@@ -69,4 +72,24 @@
 	use_logging_h( Identifier );
 public:
+	
+	// XXX EXPERIMENTAL
+	reboost::shared_buffer_t serialize() const
+	{
+	    Data data = data_serialize(this, DEFAULT_V);
+	    reboost::shared_buffer_t buf(data.getBuffer(), data.getLength() / 8);
+	    
+	    return buf;
+	}
+	
+	reboost::shared_buffer_t deserialize(reboost::shared_buffer_t buff)
+	{
+	    Data dat(const_cast<uint8_t*>(buff.data()), buff.size() * 8);
+	    
+	    size_t len = this->SERIALIZATION_METHOD_NAME(DESERIALIZE, dat) / 8;
+
+	    // return remaining sub-buffer
+	    return buff(len);
+	}
+	
 
 	//-------------------------------------------------------------------------
Index: source/ariba/utility/types/OverlayParameterSet.h
===================================================================
--- source/ariba/utility/types/OverlayParameterSet.h	(revision 11885)
+++ source/ariba/utility/types/OverlayParameterSet.h	(revision 12060)
@@ -53,5 +53,5 @@
 
 	typedef enum _OverlayStructure {
-		OverlayStructureOneHop   = 0,
+		OverlayStructureOneHop   = 0,   // DEPRECATED, DO NOT USE
 		OverlayStructureChord    = 1,
 	} OverlayStructure;
Index: source/ariba/utility/types/ServiceID.cpp
===================================================================
--- source/ariba/utility/types/ServiceID.cpp	(revision 11885)
+++ source/ariba/utility/types/ServiceID.cpp	(revision 12060)
@@ -76,5 +76,9 @@
 }
 
-string ServiceID::toString() const {
+string ServiceID::toString() const
+{
+    if ( *this == ServiceID::UNSPECIFIED )
+        return "UNSPEC";
+    
 	return ariba::utility::Helper::ultos( id );
 }
