ソースを参照

the huge commit

Julius Pfrommer 9 年 前
コミット
5ef0e58383
共有67 個のファイルを変更した2211 個の追加3504 個の削除を含む
  1. 18 20
      CMakeLists.txt
  2. 2 3
      examples/logger_stdout.c
  3. 3 1
      examples/logger_stdout.h
  4. 0 514
      examples/networklayer.c
  5. 0 67
      examples/networklayer.h
  6. 324 0
      examples/networklayer_tcp.c
  7. 20 0
      examples/networklayer_tcp.h
  8. 16 39
      examples/opcuaServer.c
  9. 0 0
      src/ongoing/ua_namespace_xml.c
  10. 0 0
      src/ongoing/ua_namespace_xml.h
  11. 0 0
      src/ongoing/ua_types_encoding_json.c
  12. 0 0
      src/ongoing/ua_types_encoding_json.h
  13. 0 0
      src/ongoing/ua_types_encoding_xml.c
  14. 0 0
      src/ongoing/ua_types_encoding_xml.h
  15. 0 0
      src/ongoing/ua_xml.c
  16. 0 0
      src/ongoing/ua_xml.h
  17. 0 567
      src/server/ua_application.c
  18. 0 14
      src/server/ua_application.h
  19. 0 139
      src/server/ua_channel_manager.c
  20. 0 17
      src/server/ua_channel_manager.h
  21. 17 18
      src/server/ua_namespace.c
  22. 20 17
      src/server/ua_namespace.h
  23. 27 29
      src/server/ua_namespace_concurrent.c
  24. 139 0
      src/server/ua_securechannel_manager.c
  25. 24 0
      src/server/ua_securechannel_manager.h
  26. 576 0
      src/server/ua_server.c
  27. 26 11
      src/server/ua_server.h
  28. 322 0
      src/server/ua_server_binary.c
  29. 47 35
      src/server/ua_services.h
  30. 33 31
      src/server/ua_services_attribute.c
  31. 10 19
      src/server/ua_services_discovery.c
  32. 1 1
      src/server/ua_services_internal.h
  33. 3 1
      src/server/ua_services_monitoreditems.c
  34. 29 17
      src/server/ua_services_nodemanagement.c
  35. 14 19
      src/server/ua_services_securechannel.c
  36. 17 20
      src/server/ua_services_session.c
  37. 9 9
      src/server/ua_services_subscription.c
  38. 50 39
      src/server/ua_services_view.c
  39. 49 63
      src/server/ua_session_manager.c
  40. 16 19
      src/server/ua_session_manager.h
  41. 0 65
      src/server/ua_transport_connection_manager.c
  42. 0 14
      src/server/ua_transport_connection_manager.h
  43. 0 382
      src/ua_channel.c
  44. 0 65
      src/ua_channel.h
  45. 44 0
      src/ua_connection.c
  46. 56 0
      src/ua_connection.h
  47. 63 0
      src/ua_securechannel.c
  48. 42 0
      src/ua_securechannel.h
  49. 23 112
      src/ua_session.c
  50. 22 114
      src/ua_session.h
  51. 7 8
      src/ua_transport.c
  52. 1 16
      src/ua_transport.h
  53. 0 181
      src/ua_transport_binary.c
  54. 0 41
      src/ua_transport_binary.h
  55. 0 376
      src/ua_transport_binary_secure.c
  56. 0 22
      src/ua_transport_binary_secure.h
  57. 0 143
      src/ua_transport_connection.c
  58. 0 39
      src/ua_transport_connection.h
  59. 0 2
      src/ua_types.c
  60. 1 3
      src/ua_types.h
  61. 0 23
      src/util/ua_list.h
  62. 17 28
      src/util/ua_log.h
  63. 8 0
      src/util/ua_util.h
  64. 1 0
      tests/check_builtin.c
  65. 87 87
      tests/check_namespace.c
  66. 4 14
      tests/check_services_view.c
  67. 23 40
      tests/check_stack.c

+ 18 - 20
CMakeLists.txt

@@ -7,8 +7,6 @@ set(open62541_VERSION_MINOR 1)
 
 # main sources of libopen62541
 include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src")
-include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src/server")
-include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src/util")
 file(GLOB_RECURSE headers "${CMAKE_CURRENT_SOURCE_DIR}/src/*.h")
 file(GLOB generated_headers "${PROJECT_BINARY_DIR}/src_generated/*.h")
 set(lib_sources src/ua_types.c
@@ -16,11 +14,18 @@ set(lib_sources src/ua_types.c
                 ${PROJECT_BINARY_DIR}/src_generated/ua_types_generated.c
                 ${PROJECT_BINARY_DIR}/src_generated/ua_namespace_0.c
                 src/ua_transport.c
-                src/ua_transport_binary.c
-                src/ua_transport_binary_secure.c
-                src/ua_channel.c
+				src/ua_connection.c
+                src/ua_securechannel.c
                 src/ua_session.c
-                src/ua_transport_connection.c
+                src/util/ua_util.c
+                src/util/ua_list.c
+                src/util/ua_indexedList.c
+                src/util/ua_base64.c
+                src/server/ua_namespace.c
+                src/server/ua_server.c
+                src/server/ua_securechannel_manager.c
+                src/server/ua_session_manager.c
+                src/server/ua_server_binary.c
                 src/server/ua_services_attribute.c
                 src/server/ua_services_session.c
                 src/server/ua_services_discovery.c
@@ -29,15 +34,6 @@ set(lib_sources src/ua_types.c
                 src/server/ua_services_view.c
                 src/server/ua_services_subscription.c
                 src/server/ua_services_monitoreditems.c
-                src/server/ua_channel_manager.c
-                src/server/ua_session_manager.c
-                src/server/ua_transport_connection_manager.c
-                src/server/ua_server.c
-                src/server/ua_application.c
-                src/util/ua_util.c
-                src/util/ua_list.c
-                src/util/ua_indexedList.c
-                src/util/ua_base64.c
                 ${headers}
                 ${generated_headers})
 
@@ -77,9 +73,10 @@ if(ENABLE_XML_ENCODING)
     else(EXPAT_FOUND)
         message(FATAL_ERROR "Expat library not found.")
     endif(EXPAT_FOUND)
-    list(APPEND lib_sources src/ua_types_encoding_xml.c
-                            src/server/ua_namespace_xml.c
-                            src/ua_xml.c)
+	include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src/ongoing")
+    list(APPEND lib_sources src/ongoing/ua_types_encoding_xml.c
+                            src/ongoing/ua_namespace_xml.c
+                            src/ongoing/ua_xml.c)
     list(APPEND generate_src_options "--with-xml")
 endif(ENABLE_XML_ENCODING)
 
@@ -87,7 +84,8 @@ endif(ENABLE_XML_ENCODING)
 option(ENABLE_JSON_ENCODING "Enable JSON-encoding of the UA types" OFF)
 if(ENABLE_JSON_ENCODING)
     MATH(EXPR UA_ENCODING_AMOUNT "${UA_ENCODING_AMOUNT}+1")
-    list(APPEND lib_sources src/ua_types_encoding_json.c)
+	include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src/ongoing")
+    list(APPEND lib_sources src/ongoing/ua_types_encoding_json.c)
     list(APPEND generate_src_options "--with-json")
 endif(ENABLE_JSON_ENCODING)
 
@@ -135,7 +133,7 @@ add_custom_command(OUTPUT ${PROJECT_BINARY_DIR}/src_generated/ua_namespace_0.c
 # build example server
 add_executable(exampleServer examples/opcuaServer.c
                              examples/logger_stdout.c
-                             examples/networklayer.c)
+                             examples/networklayer_tcp.c)
 target_link_libraries(exampleServer open62541)
 if(WIN32)
     target_link_libraries(exampleServer ws2_32)

+ 2 - 3
examples/logger_stdout.c

@@ -2,7 +2,6 @@
 #include <stdarg.h>
 
 #include "logger_stdout.h"
-#include "ua_log.h"
 #include "ua_types.h"
 
 void print_time() {
@@ -32,8 +31,8 @@ LOG_FUNCTION(warning)
 LOG_FUNCTION(error)
 LOG_FUNCTION(fatal)
 
-void Logger_Stdout_init(void *config) {
-	logger = (UA_Logger){
+void Logger_Stdout_init(UA_Logger *logger) {
+	*logger = (UA_Logger){
 		.log_trace = log_trace,
 		.log_debug = log_debug,
 		.log_info = log_info,

+ 3 - 1
examples/logger_stdout.h

@@ -1,7 +1,9 @@
 #ifndef LOGGER_STDOUT_H_
 #define LOGGER_STDOUT_H_
 
+#include "util/ua_log.h"
+
 /** Initialises the logger for the current thread. */
-void Logger_Stdout_init(void *config);
+void Logger_Stdout_init(UA_Logger *logger);
 
 #endif /* LOGGER_STDOUT_H_ */

+ 0 - 514
examples/networklayer.c

@@ -1,514 +0,0 @@
-#include "networklayer.h"
-#include "ua_transport_connection.h"
-
-#ifdef WIN32
-#include <sys/types.h>
-#include <Windows.h>
-#include <ws2tcpip.h>
-#define CLOSESOCKET(S) closesocket(S)
-#define IOCTLSOCKET ioctlsocket
-#else
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <sys/socketvar.h>
-#include <unistd.h> // read, write, close
-#define CLOSESOCKET(S) close(S)
-#define IOCTLSOCKET ioctl
-#endif /* WIN32 */
-
-#include <stdlib.h> // exit
-#include <errno.h> // errno, EINTR
-
-#include <memory.h> // memset
-#include <fcntl.h> // fcntl
-
-#ifdef ENABLE_MULTITHREADING
-#include <pthread.h>
-#endif
-
-static UA_Server *global_server; // this is bad!!!!
-
-NL_Description NL_Description_TcpBinary  = {
-	NL_UA_ENCODING_BINARY,
-	NL_CONNECTIONTYPE_TCPV4,
-	NL_MAXCONNECTIONS_DEFAULT,
-	{0,8192,8192,16384,1}
-};
-
-/* If we do not have multitasking, we implement a dispatcher-Pattern. All Connections
- * are collected in a list. From this list a fd_set is prepared and select then waits
- * for activities. We then iterate over the list, check if we've got some activites
- * and call the corresponding callback (reader, listener).
- */
-#ifndef ENABLE_MULTITHREADING
-_Bool NL_ConnectionComparer(void *p1, void* p2) {
-	NL_Connection* c1 = (NL_Connection*) p1;
-	NL_Connection* c2 = (NL_Connection*) p2;
-
-	return (c1->connectionHandle == c2->connectionHandle);
-
-}
-
-int NL_TCP_SetNonBlocking(int sock) {
-#ifdef WIN32
-	u_long iMode = 1;
-	int opts = IOCTLSOCKET(sock, FIONBIO, &iMode);
-	if (opts != NO_ERROR){
-		printf("ioctlsocket failed with error: %ld\n", opts);
-		return - 1;
-	}
-#else
-	int opts = fcntl(sock,F_GETFL);
-	if (opts < 0) {
-		perror("fcntl(F_GETFL)");
-		return -1;
-	}
-	opts = (opts | O_NONBLOCK);
-	if (fcntl(sock,F_SETFL,opts) < 0) {
-		perror("fcntl(F_SETFL)");
-		return -1;
-	}
-#endif
-	return 0;
-}
-
-void NL_Connection_printf(void* payload) {
-  NL_Connection* c = (NL_Connection*) payload;
-  printf("ListElement connectionHandle = %d\n",c->connectionHandle);
-}
-void NL_addHandleToSet(UA_Int32 handle, NL_data* nl) {
-	FD_SET(handle, &(nl->readerHandles));
-#ifdef WIN32
-	// int err = WSAGetLastError();
-#endif
-	nl->maxReaderHandle = (handle > nl->maxReaderHandle) ? handle : nl->maxReaderHandle;
-}
-void NL_setFdSet(void* payload) {
-  NL_Connection* c = (NL_Connection*) payload;
-  NL_addHandleToSet(c->connectionHandle, c->networkLayer);
-}
-void NL_checkFdSet(void* payload) {
-  NL_Connection* c = (NL_Connection*) payload;
-  if (FD_ISSET(c->connectionHandle, &(c->networkLayer->readerHandles))) {
-	  c->reader((void*)c);
-  }
-}
-
-#if 0 
-char _str_error[256];
-char* strerror(int errno) {
-	FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
-		NULL, errno,
-		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-		&_str_error[0], 256, NULL);
-	return &_str_error[0];
-}
-#endif
-
-UA_Int32 NL_msgLoop(NL_data* nl, struct timeval *tv, UA_Server *server, UA_Int32(*worker)(void*), void *arg, UA_Boolean *running) {
-	UA_Int32 result;
-	UA_Int32 err;
-	global_server = server;
-	while (*running) {
-		// determine the largest handle
-		nl->maxReaderHandle = 0;
-		UA_list_iteratePayload(&(nl->connections),NL_setFdSet);
-		DBG_VERBOSE(printf("\n------------\nUA_Stack_msgLoop - maxHandle=%d\n", nl->maxReaderHandle));
-
-		// copy tv, some unixes do overwrite and return the remaining time
-		// FIXME: actually we might want to do this ourselves to call the
-		// worker on a more regular cyclic basis
-		struct timeval tmptv;
-		memcpy(&tmptv,tv,sizeof(struct timeval));
-
-		// and wait
-		DBG_VERBOSE(printf("UA_Stack_msgLoop - enter select sec=%d,usec=%d\n",(UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
-		result = select(nl->maxReaderHandle + 1, &(nl->readerHandles), UA_NULL, UA_NULL, &tmptv);
-		DBG_VERBOSE(printf("UA_Stack_msgLoop - leave select result=%d,sec=%d,usec=%d\n",result, (UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
-
-		// handle timeout (winsock: result=0, unix: result=0,errno=0||EAGAIN) 
-		// and errors (winsock: result=SOCKET_ERROR (-1), unix: result = 0)
-		if (result <= 0) {
-#ifdef WIN32
-			err = (result == SOCKET_ERROR) ? WSAGetLastError() : 0;
-#else
-			err = errno;
-#endif
-			switch (err) {
-				// handle known errors
-#ifdef WIN32
-			case WSANOTINITIALISED:
-			case WSAEFAULT:
-			case WSAENETDOWN:
-			case WSAEINVAL:
-			case WSAEINTR:
-			case WSAEINPROGRESS:
-			case WSAENOTSOCK:
-#else
-			case EBADF:
-			case EINTR:
-			case EINVAL:
-#endif
-				// FIXME: handle errors
-				printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", result, errno, strerror(errno));
-				break;
-			// otherwise we've got a timeout and call the worker
-#ifndef WIN32
-	        case EAGAIN:
-#endif
-			default:
-					DBG_VERBOSE(printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", result, errno, strerror(errno)));
-					worker(arg);
-			}
-		} else { // activity on listener or client ports
-			DBG_VERBOSE(printf("UA_Stack_msgLoop - activities on %d handles\n",result));
-			UA_list_iteratePayload(&(nl->connections),NL_checkFdSet);
-			// FIXME: Thought it would be a conceptional flaw to call the worker
-			// here. However, there is no guarantee that the timeout would be
-			// triggered, so we call it in this branch as well.
-			worker(arg);
-		}
-	}
-#ifdef WIN32
-	// finally we should clean up the winsock.dll
-	WSACleanup();
-#endif
-	return UA_SUCCESS;
-}
-#endif /* ENABLE_MULTITHREADING */
-
-
-/** the tcp reader function */
-void* NL_TCP_reader(NL_Connection *c) {
-
-	UA_ByteString readBuffer;
-
-	TL_Buffer localBuffers;
-	UA_Int32 connectionState;
-
-	UA_TL_Connection_getLocalConfig(c->connection, &localBuffers);
-	UA_alloc((void**)&(readBuffer.data),localBuffers.recvBufferSize);
-
-	UA_TL_Connection_getState(c->connection, &connectionState);
-	if (connectionState  != CONNECTIONSTATE_CLOSE) {
-		DBG_VERBOSE(printf("NL_TCP_reader - enter read\n"));
-
-#ifdef WIN32
-		readBuffer.length = recv(c->connectionHandle, (char *)readBuffer.data, localBuffers.recvBufferSize, 0);
-#else
-		readBuffer.length = read(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize);
-#endif
-		DBG_VERBOSE(printf("NL_TCP_reader - leave read\n"));
-
-		DBG_VERBOSE(printf("NL_TCP_reader - src={%*.s}, ",c->connection.remoteEndpointUrl.length,c->connection.remoteEndpointUrl.data));
-		DBG(UA_ByteString_printx("NL_TCP_reader - received=",&readBuffer));
-
-		if (errno != 0) {
-			perror("NL_TCP_reader - ERROR reading from socket1");
-			UA_TL_Connection_setState(c->connection, CONNECTIONSTATE_CLOSE);
-		} else if (readBuffer.length  > 0) {
-#ifdef DEBUG
-#include "ua_transport_binary_secure.h"
-			UA_UInt32 pos = 0;
-			UA_OPCUATcpMessageHeader header;
-			UA_OPCUATcpMessageHeader_decodeBinary(&readBuffer, &pos, &header);
-			pos = 24;
-			if(header.messageType == UA_MESSAGETYPE_MSG)
-			{
-				UA_NodeId serviceRequestType;
-				UA_NodeId_decodeBinary(&readBuffer, &pos,&serviceRequestType);
-				UA_NodeId_printf("NL_TCP_reader - Service Type\n",&serviceRequestType);
-			}
-#endif
-			TL_Process((c->connection),global_server, &readBuffer);
-		} else {
-			perror("NL_TCP_reader - ERROR reading from socket");
-			UA_TL_Connection_setState(c->connection, CONNECTIONSTATE_CLOSE);
-		}
-	}
-
-	UA_TL_Connection_getState(c->connection, &connectionState);
-	DBG_VERBOSE(printf("NL_TCP_reader - connectionState=%d\n",connectionState));
-	if (connectionState == CONNECTIONSTATE_CLOSE) {
-		// set connection's state to CONNECTIONSTATE_CLOSED and call callback to actually close
-		UA_TL_Connection_close(c->connection);
-#ifndef ENABLE_MULTITHREADING
-		DBG_VERBOSE(printf("NL_TCP_reader - search element to remove\n"));
-		UA_list_Element* lec = UA_list_search(&(c->networkLayer->connections),NL_ConnectionComparer,c);
-		DBG_VERBOSE(printf("NL_TCP_reader - remove connection for handle=%d\n",((NL_Connection*)lec->payload)->connection.connectionHandle));
-		UA_list_removeElement(lec,UA_NULL);
-		DBG_VERBOSE(UA_list_iteratePayload(&(c->networkLayer->connections),NL_Connection_printf));
-		UA_free(c);
-#endif
-	}
-	UA_ByteString_deleteMembers(&readBuffer);
-	return UA_NULL;
-}
-
-#ifdef ENABLE_MULTITHREADING
-/** the tcp reader thread */
-void* NL_TCP_readerThread(NL_Connection *c) {
-	// just loop, NL_TCP_Reader will call the stack
-	UA_Int32 connectionState;
-	do {
-		NL_TCP_reader(c);
-		UA_TL_Connection_getState(c->connection, &connectionState);
-	} while (connectionState != CONNECTIONSTATE_CLOSED);
-	// clean up
-	UA_free(c);
-	pthread_exit(UA_NULL);
-}
-#endif
-
-/** write message provided in the gather buffers to a tcp transport layer connection */
-UA_Int32 NL_TCP_writer(UA_Int32 connectionHandle, UA_ByteString const * const * gather_buf, UA_UInt32 gather_len) {
-
-	UA_UInt32 total_len = 0;
-#ifdef WIN32
-	WSABUF *buf = malloc(gather_len * sizeof(WSABUF));
-	int result = 0;
-	for (UA_UInt32 i = 0; i<gather_len; i++) {
-		buf[i].buf = (char*)gather_buf[i]->data;
-		buf[i].len = gather_buf[i]->length;
-		total_len += gather_buf[i]->length;
-		//		DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
-		//		DBG(UA_ByteString_printx("=", gather_buf[i]));
-	}
-#else
-	struct iovec iov[gather_len];
-	for(UA_UInt32 i=0;i<gather_len;i++) {
-		iov[i].iov_base = gather_buf[i]->data;
-		iov[i].iov_len = gather_buf[i]->length;
-		total_len += gather_buf[i]->length;
-//		DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
-//		DBG(UA_ByteString_printx("=", gather_buf[i]));
-	}
-	struct msghdr message;
-	message.msg_name = UA_NULL;
-	message.msg_namelen = 0;
-	message.msg_iov = iov;
-	message.msg_iovlen = gather_len;
-	message.msg_control = UA_NULL;
-	message.msg_controllen = 0;
-	message.msg_flags = 0;
-#endif
-
-
-	UA_UInt32 nWritten = 0;
-#ifdef WIN32
-	while (nWritten < total_len) {
-		UA_UInt32 n=0;
-		do {
-			DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
-
-			//result = WSASendMsg(connectionHandle,&message,0,&n,UA_NULL,UA_NULL);
-			result = WSASend(connectionHandle, buf, gather_len , (LPDWORD)&n, 0, NULL, NULL);
-			if(result != 0)
-				printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
-			DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
-		} while (errno == EINTR);
-		nWritten += n;
-#else
-	while (nWritten < total_len) {
-		UA_Int32 n=0;
-		do {
-			DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
-			n = sendmsg(connectionHandle, &message, 0);
-			DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
-		} while (n == -1L && errno == EINTR);
-
-		if (n >= 0) {
-			nWritten += n;
-			break;
-			// TODO: handle incompletely send messages
-		} else {
-			// TODO: error handling
-			break;
-		}
-#endif
-	}
-#ifdef WIN32
-	free(buf);
-#endif
-	return UA_SUCCESS;
-}
-//callback function which is called when the UA_TL_Connection_close() function is initiated
-UA_Int32 NL_Connection_close(UA_TL_Connection *connection)
-{
-	NL_Connection *networkLayerData = UA_NULL;
-	UA_TL_Connection_getNetworkLayerData(connection, (void**)&networkLayerData);
-	if(networkLayerData != UA_NULL){
-		DBG_VERBOSE(printf("NL_Connection_close - enter shutdown\n"));
-		shutdown(networkLayerData->connectionHandle,2);
-		DBG_VERBOSE(printf("NL_Connection_close - enter close\n"));
-		CLOSESOCKET(networkLayerData->connectionHandle);
-		FD_CLR(networkLayerData->connectionHandle, &networkLayerData->networkLayer->readerHandles);
-		DBG_VERBOSE(printf("NL_Connection_close - leave close\n"));
-		return UA_SUCCESS;
-	}
-    DBG_VERBOSE(printf("NL_Connection_close - ERROR: connection object invalid \n"));
-	return UA_ERROR;
-}
-void* NL_Connection_init(NL_Connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_Reader reader, TL_Writer writer)
-{
-	UA_TL_Connection *connection = UA_NULL;
-	//create new connection object
-	UA_TL_Connection_new(&connection, tld->tld->localConf, writer, NL_Connection_close,connectionHandle,c);
-
-	c->connection = connection;
-	c->connectionHandle = connectionHandle;
-	// network layer
-	c->reader = reader;
-#ifdef MULTITHREADING
-	c->readerThreadHandle = -1;
-#endif
-	c->networkLayer = tld;
-	return UA_NULL;
-}
-
-/** the tcp accept routine */
-void* NL_TCP_accept(NL_Connection* c) {
-	NL_data* tld = c->networkLayer;
-
-	if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
-		// accept only if not max number of connections exceeded
-		struct sockaddr_in cli_addr;
-		socklen_t cli_len = sizeof(cli_addr);
-		DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
-		int newsockfd = accept(c->connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
-		DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
-		if (newsockfd < 0) {
-			DBG_ERR(printf("TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
-			perror("ERROR on accept");
-		} else {
-			DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
-			NL_Connection* cclient;
-			UA_Int32 retval = UA_SUCCESS;
-			retval |= UA_alloc((void**)&cclient,sizeof(NL_Connection));
-			NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, (TL_Writer) NL_TCP_writer);
-#ifdef ENABLE_MULTITHREADING
-			pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_readerThread, (void*) cclient);
-#else
-			UA_list_addPayloadToBack(&(tld->connections),cclient);
-			NL_TCP_SetNonBlocking(cclient->connectionHandle);
-#endif
-		}
-	} else {
-		// no action necessary to reject connection
-	}
-	return UA_NULL;
-}
-
-#ifdef ENABLE_MULTITHREADING
-void* NL_TCP_listenThread(NL_Connection* c) {
-	NL_data* tld = c->networkLayer;
-
-	DBG_VERBOSE(printf("NL_TCP_listenThread - enter listen\n"));
-	int retval = listen(c->connectionHandle, tld->tld->maxConnections);
-	DBG_VERBOSE(printf("NL_TCP_listenThread - leave listen, retval=%d\n", retval));
-	if (retval < 0) {
-		// TODO: Error handling
-		perror("NL_TCP_listen");
-		DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n", retval, errno, strerror(errno)));
-	} else {
-		do {
-			NL_TCP_accept(c);
-		}
-	} while (UA_TRUE);
-	UA_free(c);
-	pthread_exit(UA_NULL);
-}
-#endif
-
-
-UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
-	UA_Int32 retval = UA_SUCCESS;
-	// socket variables
-#ifdef WIN32
-	unsigned int newsockfd;
-#else
-	int newsockfd;
-#endif
-
-	struct sockaddr_in serv_addr;
-
-
-	// create socket for listening to incoming connections
-#ifdef WIN32
-	WORD wVersionRequested;
-	WSADATA wsaData;
-
-	/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
-	wVersionRequested = MAKEWORD(2, 2);
-
-	WSAStartup(wVersionRequested, &wsaData);
-	newsockfd = socket(PF_INET, SOCK_STREAM,0);
-	if (newsockfd == INVALID_SOCKET){
-		//UA_Int32 lasterror = WSAGetLastError();
-		printf("ERROR opening socket, code: %d\n",WSAGetLastError());
-#else
-	newsockfd = socket(PF_INET, SOCK_STREAM, 0);
-	if (newsockfd < 0) {
-#endif
-		perror("ERROR opening socket");
-		retval = UA_ERROR;
-	}
-	else {
-		// set port number, options and bind
-		memset((void *)&serv_addr, sizeof(serv_addr), 1);
-		serv_addr.sin_family = AF_INET;
-		serv_addr.sin_addr.s_addr = INADDR_ANY;
-		serv_addr.sin_port = htons(port);
-
-		int  optval = 1;
-
-		if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
-			perror("setsockopt");
-			close(newsockfd);
-			retval = UA_ERROR;
-		}
-		else {
-			// bind to port
-			if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
-				perror("ERROR on binding");
-				close(newsockfd);
-				retval = UA_ERROR;
-			}
-			else {
-				UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
-			}
-//#ifdef WIN32
-		}
-//#endif
-	}
-	// finally
-	if (retval == UA_SUCCESS) {
-		DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
-		NL_Connection* c;
-		UA_Int32 retval = UA_SUCCESS;
-		retval |= UA_alloc((void**)&c,sizeof(NL_Connection));
-		NL_Connection_init(c, tld, newsockfd, NL_TCP_accept, (TL_Writer) NL_TCP_writer);
-#ifdef MULTITHREADING
-		pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listenThread, (void*) c);
-#else
-		UA_list_addPayloadToBack(&(tld->connections),c);
-		NL_TCP_SetNonBlocking(c->connectionHandle);
-		listen(c->connectionHandle, tld->tld->maxConnections);
-#endif
-	}
-	return retval;
-}
-
-
-/** checks arguments and dispatches to worker or refuses to init */
-NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port) {
-	NL_data* nl = UA_NULL;
-	if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
-		UA_alloc((void**)&nl, sizeof(NL_data));
-		nl->tld = tlDesc;
-		FD_ZERO(&(nl->readerHandles));
-		UA_list_init(&(nl->connections));
-		NL_TCP_init(nl, port);
-	}
-	return nl;
-}

+ 0 - 67
examples/networklayer.h

@@ -1,67 +0,0 @@
-#ifndef NETWORKLAYER_H_
-#define NETWORKLAYER_H_
-
-#include "ua_types.h"
-#include "ua_transport.h"
-#include "ua_transport_binary.h"
-#include "util/ua_list.h"
-
-#ifdef MULTITHREADING
-#include <pthread.h> // pthreadcreate, pthread_t
-#endif
-
-// fd_set, FD_ZERO, FD_SET
-#ifdef WIN32
-#include <winsock2.h>
-#else
-#include <sys/select.h> 
-#endif
-
-#define NL_MAXCONNECTIONS_DEFAULT 10
-
-enum NL_UA_ENCODING_enum {
-	NL_UA_ENCODING_BINARY = 0,
-	NL_UA_ENCODING_XML = 1,
-};
-
-enum NL_CONNECTIONTYPE_enum {
-	NL_CONNECTIONTYPE_TCPV4 = 0,
-	NL_CONNECTIONTYPE_TCPV6 = 1,
-};
-
-typedef struct NL_Description {
-	UA_Int32 encoding;
-	UA_Int32 connectionType;
-	UA_Int32 maxConnections;
-	TL_Buffer localConf;
-} NL_Description;
-
-extern NL_Description NL_Description_TcpBinary;
-
-typedef struct NL_data {
-	NL_Description* tld;
-	UA_String endpointUrl;
-	UA_list_List connections;
-	fd_set readerHandles;
-	int maxReaderHandle;
-} NL_data;
-
-struct NL_Connection;
-typedef void* (*NL_Reader)(struct NL_Connection *c);
-typedef struct NL_Connection {
-	UA_TL_Connection *connection;
-	UA_Int32 state;
-	UA_UInt32 connectionHandle;
-	NL_Reader reader;
-#ifdef MULTITHREADING
-	pthread_t readerThreadHandle;
-#endif
-	NL_data* networkLayer;
-} NL_Connection;
-
-NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port);
-UA_Int32 NL_Connection_close(UA_TL_Connection *connection);
-UA_Int32 NL_msgLoop(NL_data* nl, struct timeval *tv, UA_Server *server, UA_Int32(*worker)(void*), void *arg, UA_Boolean *running);
-UA_Int32 NL_TCP_writer(UA_Int32 connectionHandle, UA_ByteString const * const * gather_buf, UA_UInt32 gather_len);
-
-#endif /* NETWORKLAYER_H_ */

+ 324 - 0
examples/networklayer_tcp.c

@@ -0,0 +1,324 @@
+#ifdef WIN32
+#include <winsock2.h>
+#include <sys/types.h>
+#include <Windows.h>
+#include <ws2tcpip.h>
+#define CLOSESOCKET(S) closesocket(S)
+#define IOCTLSOCKET ioctlsocket
+#else
+#include <sys/select.h> 
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <sys/socketvar.h>
+#include <unistd.h> // read, write, close
+#define CLOSESOCKET(S) close(S)
+#define IOCTLSOCKET ioctl
+#endif /* WIN32 */
+
+#include <stdlib.h> // exit
+#include <errno.h> // errno, EINTR
+#include <memory.h> // memset
+#include <fcntl.h> // fcntl
+
+#include "networklayer_tcp.h"
+#include "ua_transport.h"
+
+typedef struct TCPConnection {
+	UA_Int32 sockfd;
+	UA_Connection connection;
+} TCPConnection;
+
+struct NetworklayerTCP {
+	UA_ConnectionConfig localConf;
+	UA_UInt32 port;
+	fd_set fdset;
+	UA_Int32 serversockfd;
+	UA_Int32 highestfd;
+	UA_UInt32 connectionsSize;
+	TCPConnection *connections;
+};
+
+/** This structure is stored in the UA_Connection for callbacks into the
+	network layer. */
+typedef struct TCPConnectionHandle {
+	UA_Int32 sockfd;
+	NetworklayerTCP *layer;
+} TCPConnectionHandle;
+
+UA_Int32 NetworklayerTCP_new(NetworklayerTCP **newlayer, UA_ConnectionConfig localConf,
+							 UA_UInt32 port) {
+	UA_alloc((void**)newlayer, sizeof(NetworklayerTCP));
+	(*newlayer)->localConf = localConf;
+	(*newlayer)->port = port;
+	(*newlayer)->connectionsSize = 0;
+	(*newlayer)->connections = UA_NULL;
+	return UA_SUCCESS;
+}
+
+// copy the array of connections, but _loose_ one. This does not close the
+// actual socket.
+UA_Int32 NetworklayerTCP_remove(NetworklayerTCP *layer, UA_Int32 sockfd) {
+	UA_UInt32 index;
+	for(index = 0;index < layer->connectionsSize;index++) {
+		if(layer->connections[index].sockfd == sockfd)
+			break;
+	}
+	UA_Connection_deleteMembers(&layer->connections[index].connection);
+
+	TCPConnection *newconnections;
+	UA_alloc((void**)&newconnections, sizeof(TCPConnection) * (layer->connectionsSize-1));
+	UA_memcpy(newconnections, &layer->connections, sizeof(TCPConnection) * index);
+	UA_memcpy(&newconnections[index], &layer->connections[index+1],
+			  sizeof(TCPConnection) * (layer->connectionsSize - index - 1));
+	layer->connections = newconnections;
+	layer->connectionsSize--;
+	return UA_SUCCESS;
+}
+
+void NetworklayerTCP_delete(NetworklayerTCP *layer) {
+	for(UA_UInt32 index = 0;index < layer->connectionsSize;index++) {
+		shutdown(layer->connections[index].sockfd, 2);
+		CLOSESOCKET(layer->connections[index].sockfd);
+	}
+	UA_free(layer->connections);
+	UA_free(layer);
+}
+
+/** Callback function */
+void closeHandle(TCPConnectionHandle *handle) {
+	shutdown(handle->sockfd,2);
+	CLOSESOCKET(handle->sockfd);
+	NetworklayerTCP_remove(handle->layer, handle->sockfd);
+}
+
+/** Callback function */
+UA_Int32 writeHandle(TCPConnectionHandle *handle, UA_ByteStringArray gather_buf) {
+	UA_UInt32 total_len = 0;
+	UA_UInt32 nWritten = 0;
+#ifdef WIN32
+	LPWSABUF buf = malloc(gather_buf.stringsSize * sizeof(WSABUF));
+	int result = 0;
+	for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
+		buf[i].buf = gather_buf.strings[i].data;
+		buf[i].len = gather_buf.strings[i].length;
+		total_len += gather_buf.strings[i].length;
+	}
+	while (nWritten < total_len) {
+		UA_UInt32 n=0;
+		do {
+			result = WSASend(handle->sockfd, buf, gather_len , (LPDWORD)&n, 0, NULL, NULL);
+			if(result != 0)
+				printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
+		} while (errno == EINTR);
+		nWritten += n;
+	}
+	free(buf);
+#else
+	struct iovec iov[gather_buf.stringsSize];
+	for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
+		iov[i].iov_base = gather_buf.strings[i].data;
+		iov[i].iov_len = gather_buf.strings[i].length;
+		total_len += gather_buf.strings[i].length;
+	}
+	struct msghdr message = {.msg_name = UA_NULL, .msg_namelen = 0, .msg_iov = iov,
+							 .msg_iovlen = gather_buf.stringsSize, .msg_control = UA_NULL,
+							 .msg_controllen = 0, .msg_flags = 0};
+	while (nWritten < total_len) {
+		UA_Int32 n = 0;
+		do {
+			n = sendmsg(handle->sockfd, &message, 0);
+		} while (n == -1L && errno == EINTR);
+
+		if (n >= 0) {
+			nWritten += n;
+			break;
+			// TODO: handle incompletely send messages
+		} else {
+			// TODO: error handling
+			break;
+		}
+	}
+#endif
+	return UA_SUCCESS;
+}
+
+UA_Int32 NetworklayerTCP_add(NetworklayerTCP *layer, UA_Int32 newsockfd) {
+	layer->connections = realloc(layer->connections,
+								 sizeof(TCPConnection) * layer->connectionsSize);
+	TCPConnection *newconnection = &layer->connections[layer->connectionsSize];
+	newconnection->sockfd = newsockfd;
+	layer->connectionsSize++;
+
+	struct TCPConnectionHandle *callbackhandle;
+	UA_alloc((void**)&callbackhandle, sizeof(struct TCPConnectionHandle));
+	callbackhandle->layer = layer;
+	callbackhandle->sockfd = newsockfd;
+	UA_Connection_init(&newconnection->connection, layer->localConf, callbackhandle,
+					   (UA_Int32 (*)(void*))closeHandle,
+					   (UA_Int32 (*)(void*, UA_ByteStringArray*))writeHandle);
+	return UA_SUCCESS;
+}
+
+UA_Int32 setNonBlocking(int sockid) {
+#ifdef WIN32
+	u_long iMode = 1;
+	int opts = IOCTLSOCKET(sockid, FIONBIO, &iMode);
+	if (opts != NO_ERROR){
+		printf("ioctlsocket failed with error: %ld\n", opts);
+		return - 1;
+	}
+	return 0;
+#else
+	int opts = fcntl(sockid,F_GETFL);
+	if (opts < 0) {
+		perror("fcntl(F_GETFL)");
+		return -1;
+	}
+	opts = (opts | O_NONBLOCK);
+	if (fcntl(sockid,F_SETFL,opts) < 0) {
+		perror("fcntl(F_SETFL)");
+		return -1;
+	}
+	return 0;
+#endif
+}
+
+void readConnection(NetworklayerTCP *layer, UA_Server *server, TCPConnection *entry) {
+	UA_ByteString readBuffer;
+	UA_alloc((void**)&readBuffer.data, layer->localConf.recvBufferSize);
+#ifdef WIN32
+	readBuffer.length = recv(entry->sockfd, (char *)readBuffer.data,
+							 layer->localConf.recvBufferSize, 0);
+#else
+	readBuffer.length = read(entry->sockfd, readBuffer.data, layer->localConf.recvBufferSize);
+#endif
+	if (errno != 0) {
+		shutdown(entry->sockfd,2);
+		CLOSESOCKET(entry->sockfd);
+		NetworklayerTCP_remove(layer, entry->sockfd);
+	} else {
+		UA_Server_processBinaryMessage(server, &entry->connection, &readBuffer);
+	}
+	UA_ByteString_deleteMembers(&readBuffer);
+}
+
+void worksocks(NetworklayerTCP *layer, UA_Server *server, UA_UInt32 workamount) {
+	// accept new connections
+	if(FD_ISSET(layer->serversockfd,&layer->fdset)) {
+		struct sockaddr_in cli_addr;
+		socklen_t cli_len = sizeof(cli_addr);
+		int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
+		if (newsockfd >= 0) {
+			setNonBlocking(newsockfd);
+			NetworklayerTCP_add(layer, newsockfd);
+		}
+		workamount--;
+	}
+
+	// read from established sockets
+	for(UA_UInt32 i=0;i<layer->connectionsSize && workamount > 0;i++) {
+		if(FD_ISSET(layer->connections[i].sockfd, &layer->fdset)) {
+			readConnection(layer, server, &layer->connections[i]);
+			workamount--;
+		}
+	}
+}
+
+// after every select, reset the set of sockets we want to listen on
+void setFDSet(NetworklayerTCP *layer) {
+	FD_ZERO(&layer->fdset);
+	FD_SET(layer->serversockfd, &layer->fdset);
+	layer->highestfd = layer->serversockfd;
+	for(UA_UInt32 i=0;i<layer->connectionsSize;i++) {
+		FD_SET(layer->connections[i].sockfd, &layer->fdset);
+		if(layer->connections[i].sockfd > layer->highestfd)
+			layer->highestfd = layer->connections[i].sockfd;
+	}
+}
+
+UA_Int32 NetworkLayerTCP_run(NetworklayerTCP *layer, UA_Server *server, struct timeval tv,
+							   void(*worker)(UA_Server*), UA_Boolean *running) {
+	struct sockaddr_in serv_addr;
+	//UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
+
+#ifdef WIN32
+	unsigned int newsockfd;
+	WORD wVersionRequested;
+	WSADATA wsaData;
+	wVersionRequested = MAKEWORD(2, 2);
+	WSAStartup(wVersionRequested, &wsaData);
+	newsockfd = socket(PF_INET, SOCK_STREAM,0);
+	if (newsockfd == INVALID_SOCKET) {
+		printf("ERROR opening socket, code: %d\n", WSAGetLastError());
+		return UA_ERROR;
+	}
+#else
+	int newsockfd;
+	newsockfd = socket(PF_INET, SOCK_STREAM, 0);
+	if (newsockfd < 0) {
+		perror("ERROR opening socket");
+		return UA_ERROR;
+	} 
+#endif
+	memset((void *)&serv_addr, sizeof(serv_addr), 1);
+	serv_addr.sin_family = AF_INET;
+	serv_addr.sin_addr.s_addr = INADDR_ANY;
+	serv_addr.sin_port = htons(layer->port);
+
+	int optval = 1;
+	if(setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval,
+				  sizeof(optval)) == -1) {
+		perror("setsockopt");
+		close(newsockfd);
+		return UA_ERROR;
+	}
+		
+	if(bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
+		perror("binding");
+		close(newsockfd);
+		return UA_ERROR;
+	}
+
+#define MAXBACKLOG 10
+	setNonBlocking(newsockfd);
+	listen(newsockfd, MAXBACKLOG);
+
+	while (*running) {
+		setFDSet(layer);
+		struct timeval tmptv = tv;
+		UA_Int32 resultsize = select(layer->highestfd, &layer->fdset, UA_NULL, UA_NULL, &tmptv);
+		if (resultsize <= 0) {
+#ifdef WIN32
+			UA_Int32 err = (result == SOCKET_ERROR) ? WSAGetLastError() : 0;
+			switch (err) {
+			case WSANOTINITIALISED:
+			case WSAEFAULT:
+			case WSAENETDOWN:
+			case WSAEINVAL:
+			case WSAEINTR:
+			case WSAEINPROGRESS:
+			case WSAENOTSOCK:
+#else
+			UA_Int32 err = errno;
+			switch (err) {
+			case EBADF:
+			case EINTR:
+			case EINVAL:
+#endif
+				// todo: handle errors
+				printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", resultsize, errno, strerror(errno));
+				break;
+			default:
+				// timeout
+				worker(server);
+			}
+		} else { // activity on listener or client socket
+			worksocks(layer, server, resultsize);
+			worker(server);
+		}
+	}
+#ifdef WIN32
+	WSACleanup();
+#endif
+	return UA_SUCCESS;
+}

+ 20 - 0
examples/networklayer_tcp.h

@@ -0,0 +1,20 @@
+#ifndef NETWORKLAYERTCP_H_
+#define NETWORKLAYERTCP_H_
+
+#include <time.h>
+#include "server/ua_server.h"
+
+struct NetworklayerTCP;
+typedef struct NetworklayerTCP NetworklayerTCP;
+
+#define BINARYCONNECTION_PROTOCOL_VERSION  0
+#define BINARYCONNECTION_MAX_CHUNK_COUNT 1
+#define BINARYCONNECTION_MAX_MESSAGE_SIZE 8192
+
+UA_Int32 NetworklayerTCP_new(NetworklayerTCP **newlayer, UA_ConnectionConfig localConf,
+							 UA_UInt32 port);
+void NetworklayerTCP_delete(NetworklayerTCP *layer);
+UA_Int32 NetworkLayerTCP_run(NetworklayerTCP *layer, UA_Server *server, struct timeval tv,
+							   void(*worker)(UA_Server*), UA_Boolean *running);
+
+#endif /* NETWORKLAYERTCP_H_ */

+ 16 - 39
examples/opcuaServer.c

@@ -1,5 +1,4 @@
 #include <stdio.h>
-#include <stdlib.h>
 
 #ifndef WIN32
 #include <sys/mman.h>
@@ -7,19 +6,13 @@
 #include <unistd.h>
 #endif
 #include <sys/types.h>
-#include <time.h>
+#include <sys/time.h>
 #include <fcntl.h>
 #include <signal.h>
 
+#include "server/ua_server.h"
 #include "logger_stdout.h"
-#include "networklayer.h"
-#include "ua_application.h"
-#include "ua_channel_manager.h"
-#include "ua_session_manager.h"
-#include "ua_server.h"
-#include "networklayer.h"
-#include "ua_application.h"
-
+#include "networklayer_tcp.h"
 
 UA_Boolean running = UA_TRUE;
 
@@ -27,41 +20,25 @@ void stopHandler(int sign) {
 	running = UA_FALSE;
 }
 
-UA_Int32 serverCallback(void * arg) {
-	char *name = (char *) arg;
-	printf("%s does whatever servers do\n",name);
-
-	/* Namespace* ns0 = (Namespace*)UA_indexedList_find(appMockup.namespaces, 0)->payload; */
-	/* UA_Int32 retval; */
-	/* const UA_Node * node; */
-	/* UA_ExpandedNodeId serverStatusNodeId; NS0EXPANDEDNODEID(serverStatusNodeId, 2256); */
-	/* retval = Namespace_get(ns0, &serverStatusNodeId.nodeId, &node); */
-	/* if(retval == UA_SUCCESS){ */
-	/* 	((UA_ServerStatusDataType*)(((UA_VariableNode*)node)->value.data))->currentTime = UA_DateTime_now(); */
-	/* } */
-
-	return UA_SUCCESS;
+void serverCallback(UA_Server *server) {
+	printf("does whatever servers do\n");
 }
 
 int main(int argc, char** argv) {
-	UA_Int32 retval;
-	/* gets called at ctrl-c */
-	signal(SIGINT, stopHandler);
+	signal(SIGINT, stopHandler); /* catches ctrl-c */
 
 	UA_Server server;
-	UA_alloc((void**)&server.applications, sizeof(UA_Application));
-	server.applicationsSize = 1;
-	server.logger_init = Logger_Stdout_init;
-	UA_Application_init(server.applications);
-	
-	NL_data* nl = NL_init(&NL_Description_TcpBinary, 16664);
 	UA_String endpointUrl;
 	UA_String_copycstring("no endpoint url",&endpointUrl);
-	SL_ChannelManager_init(10,36000,244,2,&endpointUrl);
-	UA_SessionManager_init(10,3600000,25);
-	struct timeval tv = {1, 0}; // 1 second
-
-	retval = NL_msgLoop(nl, &tv, &server, serverCallback, argv[0], &running);
-
+	UA_Server_init(&server, &endpointUrl);
+	Logger_Stdout_init(&server.logger);
+	
+	NetworklayerTCP* nl;
+	NetworklayerTCP_new(&nl, UA_ConnectionConfig_standard, 16664);
+	struct timeval callback_interval = {1, 0}; // 1 second
+	UA_Int32 retval = NetworkLayerTCP_run(nl, &server, callback_interval,
+										  serverCallback, &running);
+	NetworklayerTCP_delete(nl);
+	UA_Server_deleteMembers(&server);
 	return retval == UA_SUCCESS ? 0 : retval;
 }

src/server/ua_namespace_xml.c → src/ongoing/ua_namespace_xml.c


src/server/ua_namespace_xml.h → src/ongoing/ua_namespace_xml.h


src/ua_types_encoding_json.c → src/ongoing/ua_types_encoding_json.c


src/ua_types_encoding_json.h → src/ongoing/ua_types_encoding_json.h


src/ua_types_encoding_xml.c → src/ongoing/ua_types_encoding_xml.c


src/ua_types_encoding_xml.h → src/ongoing/ua_types_encoding_xml.h


src/ua_xml.c → src/ongoing/ua_xml.c


src/ua_xml.h → src/ongoing/ua_xml.h


+ 0 - 567
src/server/ua_application.c

@@ -1,567 +0,0 @@
-#include "ua_application.h"
-#include "ua_namespace.h"
-#include "ua_services_internal.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-UA_indexedList_List nsMockup;
-
-UA_Node* create_node_ns0(UA_Int32 class, UA_Int32 nodeClass, UA_Int32 const id, char const * qn, char const * dn, char const * desc) {
-	UA_Node* n; UA_.types[class].new((void **)&n);
-	n->nodeId.identifierType = UA_NODEIDTYPE_NUMERIC;
-	n->nodeId.namespaceIndex = 0;
-	n->nodeId.identifier.numeric = id;
-	UA_String_copycstring(qn,&(n->browseName.name));
-	UA_String_copycstring(dn,&n->displayName.text);
-	UA_String_copycstring(desc,&n->description.text);
-	n->nodeClass = nodeClass;
-	return n;
-}
-
-void UA_Application_init(UA_Application *application) {
-	//fill the UA_borrowed_ table that has been declaed in ua_namespace.c
-	for(UA_Int32 i=0;i<SIZE_UA_VTABLE;i++){
-		UA_borrowed_.types[i] = UA_.types[i];
-		UA_borrowed_.types[i].delete=(UA_Int32(*)(void *))phantom_delete;
-		UA_borrowed_.types[i].deleteMembers=(UA_Int32(*)(void *))phantom_delete;
-	}
-
-	// create namespaces
-	// TODO: A table that maps the namespaceUris to Ids
-	Namespace* ns0;
-	Namespace_new(&ns0, 0); //C2UA_STRING("http://opcfoundation.org/UA/"));
-
-	Namespace* local;
-	Namespace_new(&local, 1); //C2UA_STRING("http://localhost:16664/open62541/"));
-
-	// add to list of namespaces
-	UA_indexedList_init(application->namespaces);
-	UA_indexedList_addValueToFront(application->namespaces,0,ns0);
-	UA_indexedList_addValueToFront(application->namespaces,1,local);
-
-	/**************/
-	/* References */
-	/**************/
-
-	// ReferenceType Ids
-	UA_NodeId RefTypeId_References = NS0NODEID(31);
-	UA_NodeId RefTypeId_NonHierarchicalReferences = NS0NODEID(32);
-	UA_NodeId RefTypeId_HierarchicalReferences = NS0NODEID(33);
-	UA_NodeId RefTypeId_HasChild = NS0NODEID(34);
-	UA_NodeId RefTypeId_Organizes = NS0NODEID(35);
-	UA_NodeId RefTypeId_HasEventSource = NS0NODEID(36);
-	UA_NodeId RefTypeId_HasModellingRule = NS0NODEID(37);
-	UA_NodeId RefTypeId_HasEncoding = NS0NODEID(38);
-	UA_NodeId RefTypeId_HasDescription = NS0NODEID(39);
-	UA_NodeId RefTypeId_HasTypeDefinition = NS0NODEID(40);
-	UA_NodeId RefTypeId_GeneratesEvent = NS0NODEID(41);
-	UA_NodeId RefTypeId_Aggregates = NS0NODEID(44);
-	UA_NodeId RefTypeId_HasSubtype = NS0NODEID(45);
-	UA_NodeId RefTypeId_HasProperty = NS0NODEID(46);
-	UA_NodeId RefTypeId_HasComponent = NS0NODEID(47);
-	UA_NodeId RefTypeId_HasNotifier = NS0NODEID(48);
-	UA_NodeId RefTypeId_HasOrderedComponent = NS0NODEID(49);
-	UA_NodeId RefTypeId_HasModelParent = NS0NODEID(50);
-	UA_NodeId RefTypeId_FromState = NS0NODEID(51);
-	UA_NodeId RefTypeId_ToState = NS0NODEID(52);
-	UA_NodeId RefTypeId_HasCause = NS0NODEID(53);
-	UA_NodeId RefTypeId_HasEffect = NS0NODEID(54);
-	UA_NodeId RefTypeId_HasHistoricalConfiguration = NS0NODEID(56);
-
-#define ADDINVERSEREFERENCE(NODE,REFTYPE,TARGET_NODEID) \
-	static struct UA_ReferenceNode NODE##ReferenceNode; \
-	UA_ReferenceNode_init(&NODE##ReferenceNode); \
-	NODE##ReferenceNode.referenceTypeId = REFTYPE; \
-	NODE##ReferenceNode.isInverse = UA_TRUE; \
-	NODE##ReferenceNode.targetId.nodeId = TARGET_NODEID; \
-	NODE##ReferenceNode.targetId.namespaceUri = UA_STRING_NULL; \
-	NODE##ReferenceNode.targetId.serverIndex = 0; \
-	AddReference((UA_Node*)NODE, &NODE##ReferenceNode, ns0)
-
-	UA_ReferenceTypeNode *references;
-	UA_ReferenceTypeNode_new(&references);
-	references->nodeId = RefTypeId_References;
-	references->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(references->browseName, "References");
-	UA_LOCALIZEDTEXT_STATIC(references->displayName, "References");
-	UA_LOCALIZEDTEXT_STATIC(references->description, "References");
-	references->isAbstract = UA_TRUE;
-	references->symmetric = UA_TRUE;
-	Namespace_insert(ns0,(UA_Node**)&references, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hierarchicalreferences;
-	UA_ReferenceTypeNode_new(&hierarchicalreferences);
-	hierarchicalreferences->nodeId = RefTypeId_HierarchicalReferences;
-	hierarchicalreferences->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hierarchicalreferences->browseName, "HierarchicalReferences");
-	UA_LOCALIZEDTEXT_STATIC(hierarchicalreferences->displayName, "HierarchicalReferences");
-	UA_LOCALIZEDTEXT_STATIC(hierarchicalreferences->description, "HierarchicalReferences");
-	hierarchicalreferences->isAbstract = UA_TRUE;
-	hierarchicalreferences->symmetric = UA_FALSE;
-	ADDINVERSEREFERENCE(hierarchicalreferences, RefTypeId_HasSubtype, RefTypeId_References);
-	Namespace_insert(ns0,(UA_Node**)&hierarchicalreferences, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *nonhierarchicalreferences;
-	UA_ReferenceTypeNode_new(&nonhierarchicalreferences);
-	nonhierarchicalreferences->nodeId = RefTypeId_NonHierarchicalReferences;
-	nonhierarchicalreferences->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(nonhierarchicalreferences->browseName, "NonHierarchicalReferences");
-	UA_LOCALIZEDTEXT_STATIC(nonhierarchicalreferences->displayName, "NonHierarchicalReferences");
-	UA_LOCALIZEDTEXT_STATIC(nonhierarchicalreferences->description, "NonHierarchicalReferences");
-	nonhierarchicalreferences->isAbstract = UA_TRUE;
-	nonhierarchicalreferences->symmetric = UA_FALSE;
-	ADDINVERSEREFERENCE(nonhierarchicalreferences, RefTypeId_HasSubtype, RefTypeId_References);
-	Namespace_insert(ns0,(UA_Node**)&nonhierarchicalreferences, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *haschild;
-	UA_ReferenceTypeNode_new(&haschild);
-	haschild->nodeId = RefTypeId_HasChild;
-	haschild->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(haschild->browseName, "HasChild");
-	UA_LOCALIZEDTEXT_STATIC(haschild->displayName, "HasChild");
-	UA_LOCALIZEDTEXT_STATIC(haschild->description, "HasChild");
-	haschild->isAbstract = UA_TRUE;
-	haschild->symmetric = UA_FALSE;
-	ADDINVERSEREFERENCE(haschild, RefTypeId_HasSubtype, RefTypeId_HierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&haschild, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *organizes;
-	UA_ReferenceTypeNode_new(&organizes);
-	organizes->nodeId = RefTypeId_Organizes;
-	organizes->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(organizes->browseName, "Organizes");
-	UA_LOCALIZEDTEXT_STATIC(organizes->displayName, "Organizes");
-	UA_LOCALIZEDTEXT_STATIC(organizes->description, "Organizes");
-	organizes->isAbstract = UA_FALSE;
-	organizes->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(organizes->inverseName, "OrganizedBy");
-	ADDINVERSEREFERENCE(organizes, RefTypeId_HasSubtype, RefTypeId_HierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&organizes, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *haseventsource;
-	UA_ReferenceTypeNode_new(&haseventsource);
-	haseventsource->nodeId = RefTypeId_HasEventSource;
-	haseventsource->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(haseventsource->browseName, "HasEventSource");
-	UA_LOCALIZEDTEXT_STATIC(haseventsource->displayName, "HasEventSource");
-	UA_LOCALIZEDTEXT_STATIC(haseventsource->description, "HasEventSource");
-	haseventsource->isAbstract = UA_FALSE;
-	haseventsource->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(haseventsource->inverseName, "EventSourceOf");
-	ADDINVERSEREFERENCE(haseventsource, RefTypeId_HasSubtype, RefTypeId_HierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&haseventsource, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasmodellingrule;
-	UA_ReferenceTypeNode_new(&hasmodellingrule);
-	hasmodellingrule->nodeId = RefTypeId_HasModellingRule;
-	hasmodellingrule->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasmodellingrule->browseName, "HasModellingRule");
-	UA_LOCALIZEDTEXT_STATIC(hasmodellingrule->displayName, "HasModellingRule");
-	UA_LOCALIZEDTEXT_STATIC(hasmodellingrule->description, "HasModellingRule");
-	hasmodellingrule->isAbstract = UA_FALSE;
-	hasmodellingrule->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasmodellingrule->inverseName, "ModellingRuleOf");
-	ADDINVERSEREFERENCE(hasmodellingrule, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&hasmodellingrule, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasencoding;
-	UA_ReferenceTypeNode_new(&hasencoding);
-	hasencoding->nodeId = RefTypeId_HasEncoding;
-	hasencoding->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasencoding->browseName, "HasEncoding");
-	UA_LOCALIZEDTEXT_STATIC(hasencoding->displayName, "HasEncoding");
-	UA_LOCALIZEDTEXT_STATIC(hasencoding->description, "HasEncoding");
-	hasencoding->isAbstract = UA_FALSE;
-	hasencoding->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasencoding->inverseName, "EncodingOf");
-	ADDINVERSEREFERENCE(hasencoding, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&hasencoding, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasdescription;
-	UA_ReferenceTypeNode_new(&hasdescription);
-	hasdescription->nodeId = RefTypeId_HasDescription;
-	hasdescription->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasdescription->browseName, "HasDescription");
-	UA_LOCALIZEDTEXT_STATIC(hasdescription->displayName, "HasDescription");
-	UA_LOCALIZEDTEXT_STATIC(hasdescription->description, "HasDescription");
-	hasdescription->isAbstract = UA_FALSE;
-	hasdescription->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasdescription->inverseName, "DescriptionOf");
-	ADDINVERSEREFERENCE(hasdescription, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&hasdescription, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hastypedefinition;
-	UA_ReferenceTypeNode_new(&hastypedefinition);
-	hastypedefinition->nodeId = RefTypeId_HasTypeDefinition;
-	hastypedefinition->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hastypedefinition->browseName, "HasTypeDefinition");
-	UA_LOCALIZEDTEXT_STATIC(hastypedefinition->displayName, "HasTypeDefinition");
-	UA_LOCALIZEDTEXT_STATIC(hastypedefinition->description, "HasTypeDefinition");
-	hastypedefinition->isAbstract = UA_FALSE;
-	hastypedefinition->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hastypedefinition->inverseName, "TypeDefinitionOf");
-	ADDINVERSEREFERENCE(hastypedefinition, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&hastypedefinition, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *generatesevent;
-	UA_ReferenceTypeNode_new(&generatesevent);
-	generatesevent->nodeId = RefTypeId_GeneratesEvent;
-	generatesevent->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(generatesevent->browseName, "GeneratesEvent");
-	UA_LOCALIZEDTEXT_STATIC(generatesevent->displayName, "GeneratesEvent");
-	UA_LOCALIZEDTEXT_STATIC(generatesevent->description, "GeneratesEvent");
-	generatesevent->isAbstract = UA_FALSE;
-	generatesevent->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(generatesevent->inverseName, "GeneratedBy");
-	ADDINVERSEREFERENCE(generatesevent, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&generatesevent, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *aggregates;
-	UA_ReferenceTypeNode_new(&aggregates);
-	aggregates->nodeId = RefTypeId_Aggregates;
-	aggregates->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(aggregates->browseName, "Aggregates");
-	UA_LOCALIZEDTEXT_STATIC(aggregates->displayName, "Aggregates");
-	UA_LOCALIZEDTEXT_STATIC(aggregates->description, "Aggregates");
-	aggregates->isAbstract = UA_TRUE;
-	aggregates->symmetric = UA_FALSE;
-	ADDINVERSEREFERENCE(aggregates, RefTypeId_HasSubtype, RefTypeId_HasChild);
-	Namespace_insert(ns0,(UA_Node**)&aggregates, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hassubtype;
-	UA_ReferenceTypeNode_new(&hassubtype);
-	hassubtype->nodeId = RefTypeId_HasSubtype;
-	hassubtype->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hassubtype->browseName, "HasSubtype");
-	UA_LOCALIZEDTEXT_STATIC(hassubtype->displayName, "HasSubtype");
-	UA_LOCALIZEDTEXT_STATIC(hassubtype->description, "HasSubtype");
-	hassubtype->isAbstract = UA_FALSE;
-	hassubtype->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hassubtype->inverseName, "SubtypeOf");
-	ADDINVERSEREFERENCE(hassubtype, RefTypeId_HasSubtype, RefTypeId_HasChild);
-	Namespace_insert(ns0,(UA_Node**)&hassubtype, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasproperty;
-	UA_ReferenceTypeNode_new(&hasproperty);
-	hasproperty->nodeId = RefTypeId_HasProperty;
-	hasproperty->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasproperty->browseName, "HasProperty");
-	UA_LOCALIZEDTEXT_STATIC(hasproperty->displayName, "HasProperty");
-	UA_LOCALIZEDTEXT_STATIC(hasproperty->description, "HasProperty");
-	hasproperty->isAbstract = UA_FALSE;
-	hasproperty->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasproperty->inverseName, "PropertyOf");
-	ADDINVERSEREFERENCE(hasproperty, RefTypeId_HasSubtype, RefTypeId_Aggregates);
-	Namespace_insert(ns0,(UA_Node**)&hasproperty, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hascomponent;
-	UA_ReferenceTypeNode_new(&hascomponent);
-	hascomponent->nodeId = RefTypeId_HasComponent;
-	hascomponent->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hascomponent->browseName, "HasComponent");
-	UA_LOCALIZEDTEXT_STATIC(hascomponent->displayName, "HasComponent");
-	UA_LOCALIZEDTEXT_STATIC(hascomponent->description, "HasComponent");
-	hascomponent->isAbstract = UA_FALSE;
-	hascomponent->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hascomponent->inverseName, "ComponentOf");
-	ADDINVERSEREFERENCE(hascomponent, RefTypeId_HasSubtype, RefTypeId_Aggregates);
-	Namespace_insert(ns0,(UA_Node**)&hascomponent, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasnotifier;
-	UA_ReferenceTypeNode_new(&hasnotifier);
-	hasnotifier->nodeId = RefTypeId_HasNotifier;
-	hasnotifier->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasnotifier->browseName, "HasNotifier");
-	UA_LOCALIZEDTEXT_STATIC(hasnotifier->displayName, "HasNotifier");
-	UA_LOCALIZEDTEXT_STATIC(hasnotifier->description, "HasNotifier");
-	hasnotifier->isAbstract = UA_FALSE;
-	hasnotifier->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasnotifier->inverseName, "NotifierOf");
-	ADDINVERSEREFERENCE(hasnotifier, RefTypeId_HasSubtype, RefTypeId_HasEventSource);
-	Namespace_insert(ns0,(UA_Node**)&hasnotifier, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasorderedcomponent;
-	UA_ReferenceTypeNode_new(&hasorderedcomponent);
-	hasorderedcomponent->nodeId = RefTypeId_HasOrderedComponent;
-	hasorderedcomponent->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasorderedcomponent->browseName, "HasOrderedComponent");
-	UA_LOCALIZEDTEXT_STATIC(hasorderedcomponent->displayName, "HasOrderedComponent");
-	UA_LOCALIZEDTEXT_STATIC(hasorderedcomponent->description, "HasOrderedComponent");
-	hasorderedcomponent->isAbstract = UA_FALSE;
-	hasorderedcomponent->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasorderedcomponent->inverseName, "OrderedComponentOf");
-	ADDINVERSEREFERENCE(hasorderedcomponent, RefTypeId_HasSubtype, RefTypeId_HasComponent);
-	Namespace_insert(ns0,(UA_Node**)&hasorderedcomponent, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hasmodelparent;
-	UA_ReferenceTypeNode_new(&hasmodelparent);
-	hasmodelparent->nodeId = RefTypeId_HasModelParent;
-	hasmodelparent->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hasmodelparent->browseName, "HasModelParent");
-	UA_LOCALIZEDTEXT_STATIC(hasmodelparent->displayName, "HasModelParent");
-	UA_LOCALIZEDTEXT_STATIC(hasmodelparent->description, "HasModelParent");
-	hasmodelparent->isAbstract = UA_FALSE;
-	hasmodelparent->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hasmodelparent->inverseName, "ModelParentOf");
-	ADDINVERSEREFERENCE(hasmodelparent, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&hasmodelparent, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *fromstate;
-	UA_ReferenceTypeNode_new(&fromstate);
-	fromstate->nodeId = RefTypeId_FromState;
-	fromstate->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(fromstate->browseName, "FromState");
-	UA_LOCALIZEDTEXT_STATIC(fromstate->displayName, "FromState");
-	UA_LOCALIZEDTEXT_STATIC(fromstate->description, "FromState");
-	fromstate->isAbstract = UA_FALSE;
-	fromstate->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(fromstate->inverseName, "ToTransition");
-	ADDINVERSEREFERENCE(fromstate, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&fromstate, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *tostate;
-	UA_ReferenceTypeNode_new(&tostate);
-	tostate->nodeId = RefTypeId_ToState;
-	tostate->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(tostate->browseName, "ToState");
-	UA_LOCALIZEDTEXT_STATIC(tostate->displayName, "ToState");
-	UA_LOCALIZEDTEXT_STATIC(tostate->description, "ToState");
-	tostate->isAbstract = UA_FALSE;
-	tostate->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(tostate->inverseName, "FromTransition");
-	ADDINVERSEREFERENCE(tostate, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&tostate, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hascause;
-	UA_ReferenceTypeNode_new(&hascause);
-	hascause->nodeId = RefTypeId_HasCause;
-	hascause->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hascause->browseName, "HasCause");
-	UA_LOCALIZEDTEXT_STATIC(hascause->displayName, "HasCause");
-	UA_LOCALIZEDTEXT_STATIC(hascause->description, "HasCause");
-	hascause->isAbstract = UA_FALSE;
-	hascause->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hascause->inverseName, "MayBeCausedBy");
-	ADDINVERSEREFERENCE(hascause, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&hascause, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *haseffect;
-	UA_ReferenceTypeNode_new(&haseffect);
-	haseffect->nodeId = RefTypeId_HasEffect;
-	haseffect->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(haseffect->browseName, "HasEffect");
-	UA_LOCALIZEDTEXT_STATIC(haseffect->displayName, "HasEffect");
-	UA_LOCALIZEDTEXT_STATIC(haseffect->description, "HasEffect");
-	haseffect->isAbstract = UA_FALSE;
-	haseffect->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(haseffect->inverseName, "MayBeEffectedBy");
-	ADDINVERSEREFERENCE(haseffect, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
-	Namespace_insert(ns0,(UA_Node**)&haseffect, NAMESPACE_INSERT_UNIQUE);
-
-	UA_ReferenceTypeNode *hashistoricalconfiguration;
-	UA_ReferenceTypeNode_new(&hashistoricalconfiguration);
-	hashistoricalconfiguration->nodeId = RefTypeId_HasHistoricalConfiguration;
-	hashistoricalconfiguration->nodeClass = UA_NODECLASS_REFERENCETYPE;
-	UA_QUALIFIEDNAME_STATIC(hashistoricalconfiguration->browseName, "HasHistoricalConfiguration");
-	UA_LOCALIZEDTEXT_STATIC(hashistoricalconfiguration->displayName, "HasHistoricalConfiguration");
-	UA_LOCALIZEDTEXT_STATIC(hashistoricalconfiguration->description, "HasHistoricalConfiguration");
-	hashistoricalconfiguration->isAbstract = UA_FALSE;
-	hashistoricalconfiguration->symmetric = UA_FALSE;
-	UA_LOCALIZEDTEXT_STATIC(hashistoricalconfiguration->inverseName, "HistoricalConfigurationOf");
-	ADDINVERSEREFERENCE(hashistoricalconfiguration, RefTypeId_HasSubtype, RefTypeId_Aggregates);
-	Namespace_insert(ns0,(UA_Node**)&hashistoricalconfiguration, NAMESPACE_INSERT_UNIQUE);
-
-
-	// ObjectTypes (Ids only)
-	UA_ExpandedNodeId ObjTypeId_FolderType; NS0EXPANDEDNODEID(ObjTypeId_FolderType, 61);
-
-	// Objects (Ids only)
-	UA_ExpandedNodeId ObjId_ObjectsFolder; NS0EXPANDEDNODEID(ObjId_ObjectsFolder, 85);
-	UA_ExpandedNodeId ObjId_TypesFolder; NS0EXPANDEDNODEID(ObjId_TypesFolder, 86);
-	UA_ExpandedNodeId ObjId_ViewsFolder; NS0EXPANDEDNODEID(ObjId_ViewsFolder, 87);
-	UA_ExpandedNodeId ObjId_Server; NS0EXPANDEDNODEID(ObjId_Server, 2253);
-	UA_ExpandedNodeId ObjId_ServerArray; NS0EXPANDEDNODEID(ObjId_ServerArray, 2254);
-	UA_ExpandedNodeId ObjId_NamespaceArray; NS0EXPANDEDNODEID(ObjId_NamespaceArray, 2255);
-	UA_ExpandedNodeId ObjId_ServerStatus; NS0EXPANDEDNODEID(ObjId_ServerStatus, 2256);
-	UA_ExpandedNodeId ObjId_ServerCapabilities; NS0EXPANDEDNODEID(ObjId_ServerCapabilities, 2268);
-	UA_ExpandedNodeId ObjId_State; NS0EXPANDEDNODEID(ObjId_State, 2259);
-
-	// FolderType
-	UA_ObjectNode *folderType;
-	UA_ObjectNode_new(&folderType);
-	folderType->nodeId = NS0NODEID(61);
-	folderType->nodeClass = UA_NODECLASS_OBJECTTYPE; // I should not have to set this manually
-	UA_QUALIFIEDNAME_STATIC(folderType->browseName, "FolderType");
-	UA_LOCALIZEDTEXT_STATIC(folderType->displayName, "FolderType");
-	UA_LOCALIZEDTEXT_STATIC(folderType->description, "FolderType");
-	Namespace_insert(ns0,(UA_Node**)&folderType, NAMESPACE_INSERT_UNIQUE);
-
-#define ADDREFERENCE(NODE, REFTYPE, INVERSE, TARGET_NODEID) \
-	static struct UA_ReferenceNode NODE##REFTYPE##TARGET_NODEID; \
-	UA_ReferenceNode_init(&NODE##REFTYPE##TARGET_NODEID); \
-	NODE##REFTYPE##TARGET_NODEID.referenceTypeId = REFTYPE; \
-	NODE##REFTYPE##TARGET_NODEID.isInverse = INVERSE; \
-	NODE##REFTYPE##TARGET_NODEID.targetId = TARGET_NODEID; \
-	AddReference((UA_Node*)NODE, &NODE##REFTYPE##TARGET_NODEID, ns0)
-
-	// Root
-	UA_ObjectNode *root;
-	UA_ObjectNode_new(&root);
-	root->nodeId = NS0NODEID(84);
-	root->nodeClass = UA_NODECLASS_OBJECT; // I should not have to set this manually
-	UA_QUALIFIEDNAME_STATIC(root->browseName, "Root");
-	UA_LOCALIZEDTEXT_STATIC(root->displayName, "Root");
-	UA_LOCALIZEDTEXT_STATIC(root->description, "Root");
-	ADDREFERENCE(root, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
-	ADDREFERENCE(root, RefTypeId_Organizes, UA_FALSE, ObjId_ObjectsFolder);
-	ADDREFERENCE(root, RefTypeId_Organizes, UA_FALSE, ObjId_TypesFolder);
-	ADDREFERENCE(root, RefTypeId_Organizes, UA_FALSE, ObjId_ViewsFolder);
-	/* root becomes a managed node. we need to release it at the end.*/
-	Namespace_insert(ns0,(UA_Node**)&root, NAMESPACE_INSERT_UNIQUE | NAMESPACE_INSERT_GETMANAGED);
-
-	// Objects
-	UA_ObjectNode *objects;
-	UA_ObjectNode_new(&objects);
-	objects->nodeId = ObjId_ObjectsFolder.nodeId;
-	objects->nodeClass = UA_NODECLASS_OBJECT;
-	UA_QUALIFIEDNAME_STATIC(objects->browseName, "Objects");
-	UA_LOCALIZEDTEXT_STATIC(objects->displayName, "Objects");
-	UA_LOCALIZEDTEXT_STATIC(objects->description, "Objects");
-	ADDREFERENCE(objects, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
-	ADDREFERENCE(objects, RefTypeId_Organizes, UA_FALSE, ObjId_Server);
-	Namespace_insert(ns0,(UA_Node**)&objects, NAMESPACE_INSERT_UNIQUE);
-
-	// Types
-	UA_ObjectNode *types;
-	UA_ObjectNode_new(&types);
-	types->nodeId = ObjId_TypesFolder.nodeId;
-	types->nodeClass = UA_NODECLASS_OBJECT;
-	UA_QUALIFIEDNAME_STATIC(types->browseName, "Types");
-	UA_LOCALIZEDTEXT_STATIC(types->displayName, "Types");
-	UA_LOCALIZEDTEXT_STATIC(types->description, "Types");
-	ADDREFERENCE(types, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
-	Namespace_insert(ns0,(UA_Node**)&types, NAMESPACE_INSERT_UNIQUE);
-
-	// Views
-	UA_ObjectNode *views;
-	UA_ObjectNode_new(&views);
-	views->nodeId = ObjId_ViewsFolder.nodeId;
-	views->nodeClass = UA_NODECLASS_OBJECT;
-	UA_QUALIFIEDNAME_STATIC(views->browseName, "Views");
-	UA_LOCALIZEDTEXT_STATIC(views->displayName, "Views");
-	UA_LOCALIZEDTEXT_STATIC(views->description, "Views");
-	ADDREFERENCE(views, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
-	Namespace_insert(ns0,(UA_Node**)&views, NAMESPACE_INSERT_UNIQUE);
-
-	// Server
-	UA_ObjectNode *server;
-	UA_ObjectNode_new(&server);
-	server->nodeId = ObjId_Server.nodeId;
-	server->nodeClass = UA_NODECLASS_OBJECT;
-	UA_QUALIFIEDNAME_STATIC(server->browseName, "Server");
-	UA_LOCALIZEDTEXT_STATIC(server->displayName, "Server");
-	UA_LOCALIZEDTEXT_STATIC(server->description, "Server");
-	ADDREFERENCE(server, RefTypeId_HasComponent, UA_FALSE, ObjId_ServerCapabilities);
-	ADDREFERENCE(server, RefTypeId_HasComponent, UA_FALSE, ObjId_NamespaceArray);
-	ADDREFERENCE(server, RefTypeId_HasProperty, UA_FALSE, ObjId_ServerStatus);
-	ADDREFERENCE(server, RefTypeId_HasProperty, UA_FALSE, ObjId_ServerArray);
-	Namespace_insert(ns0,(UA_Node**)&server, NAMESPACE_INSERT_UNIQUE);
-
-	// NamespaceArray
-	UA_VariableNode *namespaceArray;
-	UA_VariableNode_new(&namespaceArray);
-	namespaceArray->nodeId = ObjId_NamespaceArray.nodeId;
-	namespaceArray->nodeClass = UA_NODECLASS_VARIABLE; //FIXME: this should go into _new?
-	UA_QUALIFIEDNAME_STATIC(namespaceArray->browseName, "NamespaceArray");
-	UA_LOCALIZEDTEXT_STATIC(namespaceArray->displayName, "NamespaceArray");
-	UA_LOCALIZEDTEXT_STATIC(namespaceArray->description, "NamespaceArray");
-	UA_Array_new((void**)&namespaceArray->value.data, 2, &UA_.types[UA_STRING]);
-	namespaceArray->value.vt = &UA_.types[UA_STRING];
-	namespaceArray->value.arrayLength = 2;
-	UA_String_copycstring("http://opcfoundation.org/UA/",&((UA_String *)((namespaceArray->value).data))[0]);
-	UA_String_copycstring("http://localhost:16664/open62541/",&((UA_String *)(((namespaceArray)->value).data))[1]);
-	namespaceArray->arrayDimensionsSize = 1;
-	UA_UInt32* dimensions = UA_NULL;
-	UA_alloc((void**)&dimensions, sizeof(UA_UInt32));
-	*dimensions = 2;
-	namespaceArray->arrayDimensions = dimensions;
-	namespaceArray->dataType = NS0NODEID(UA_STRING_NS0);
-	namespaceArray->valueRank = 1;
-	namespaceArray->minimumSamplingInterval = 1.0;
-	namespaceArray->historizing = UA_FALSE;
-	Namespace_insert(ns0,(UA_Node**)&namespaceArray, NAMESPACE_INSERT_UNIQUE);
-
-	// ServerStatus
-	UA_VariableNode *serverstatus;
-	UA_VariableNode_new(&serverstatus);
-	serverstatus->nodeId = ObjId_ServerStatus.nodeId;
-	serverstatus->nodeClass = UA_NODECLASS_VARIABLE;
-	UA_QUALIFIEDNAME_STATIC(serverstatus->browseName, "ServerStatus");
-	UA_LOCALIZEDTEXT_STATIC(serverstatus->displayName, "ServerStatus");
-	UA_LOCALIZEDTEXT_STATIC(serverstatus->description, "ServerStatus");
-	UA_ServerStatusDataType *status;
-	UA_ServerStatusDataType_new(&status);
-	status->startTime = UA_DateTime_now();
-	status->currentTime = UA_DateTime_now();
-	status->state = UA_SERVERSTATE_RUNNING;
-	UA_STRING_STATIC(status->buildInfo.productUri, "open62541.org");
-	UA_STRING_STATIC(status->buildInfo.manufacturerName, "open62541");
-	UA_STRING_STATIC(status->buildInfo.productName, "open62541");
-	UA_STRING_STATIC(status->buildInfo.softwareVersion, "0.0");
-	UA_STRING_STATIC(status->buildInfo.buildNumber, "0.0");
-	status->buildInfo.buildDate = UA_DateTime_now();
-	status->secondsTillShutdown = 99999999;
-	UA_LOCALIZEDTEXT_STATIC(status->shutdownReason, "because");
-	serverstatus->value.vt = &UA_.types[UA_SERVERSTATUSDATATYPE]; // gets encoded as an extensionobject
-	serverstatus->value.arrayLength = 1;
-	serverstatus->value.data = status;
-	Namespace_insert(ns0,(UA_Node**)&serverstatus, NAMESPACE_INSERT_UNIQUE);
-
-	// State (Component of ServerStatus)
-	UA_VariableNode *state;
-	UA_VariableNode_new(&state);
-	state->nodeId = ObjId_State.nodeId;
-	state->nodeClass = UA_NODECLASS_VARIABLE;
-	UA_QUALIFIEDNAME_STATIC(state->browseName, "State");
-	UA_LOCALIZEDTEXT_STATIC(state->displayName, "State");
-	UA_LOCALIZEDTEXT_STATIC(state->description, "State");
-	state->value.vt = &UA_borrowed_.types[UA_SERVERSTATE];
-	state->value.arrayDimensionsLength = 1; // added to ensure encoding in readreponse
-	state->value.arrayLength = 1;
-	state->value.data = &status->state; // points into the other object.
-	Namespace_insert(ns0,(UA_Node**)&state, NAMESPACE_INSERT_UNIQUE);
-
-	//TODO: free(namespaceArray->value.data) later or forget it
-
-
-	/* UA_VariableNode* v = (UA_VariableNode*)np; */
-	/* UA_Array_new((void**)&v->value.data, 2, &UA_.types[UA_STRING]); */
-	/* v->value.vt = &UA_.types[UA_STRING]; */
-	/* v->value.arrayLength = 2; */
-	/* UA_String_copycstring("http://opcfoundation.org/UA/",&((UA_String *)((v->value).data))[0]); */
-	/* UA_String_copycstring("http://localhost:16664/open62541/",&((UA_String *)(((v)->value).data))[1]); */
-	/* v->dataType.identifierType = UA_NODEIDTYPE_FOURBYTE; */
-	/* v->dataType.identifier.numeric = UA_STRING_NS0; */
-	/* v->valueRank = 1; */
-	/* v->minimumSamplingInterval = 1.0; */
-	/* v->historizing = UA_FALSE; */
-	/* Namespace_insert(ns0,np); */
-
-	/*******************/
-	/* Namespace local */
-	/*******************/
-	
-	Namespace_releaseManagedNode((const UA_Node*)root);
-
-#if defined(DEBUG) && defined(VERBOSE)
-	uint32_t i;
-	for (i=0;i < ns0->size;i++) {
-		if (ns0->entries[i].node != UA_NULL) {
-			printf("application_init - entries[%d]={",i);
-			UA_Node_print(ns0->entries[i].node, stdout);
-			printf("}\n");
-		}
-	}
-#endif
-}

+ 0 - 14
src/server/ua_application.h

@@ -1,14 +0,0 @@
-#ifndef OPCUA_APPLICATION_H_
-#define OPCUA_APPLICATION_H_
-
-#include "ua_types.h"
-#include "ua_namespace.h"
-#include "util/ua_indexedList.h"
-
-typedef struct UA_Application {
-	UA_ApplicationDescription *description;
-	UA_indexedList_List *namespaces; // each entry is a namespace
-} UA_Application;
-
-void UA_Application_init(UA_Application *application);
-#endif

+ 0 - 139
src/server/ua_channel_manager.c

@@ -1,139 +0,0 @@
-#include "ua_channel_manager.h"
-
-struct SL_ChannelManager {
-	UA_Int32 maxChannelCount;
-	UA_Int32 lastChannelId;
-	UA_DateTime maxChannelLifeTime;
-	UA_list_List channels;
-	UA_MessageSecurityMode securityMode;
-	UA_String endpointUrl;
-	UA_DateTime channelLifeTime;
-	UA_UInt32 lastTokenId;
-};
-
-static SL_ChannelManager *channelManager;
-
-UA_Int32 SL_ChannelManager_init(UA_UInt32 maxChannelCount, UA_UInt32 tokenLifetime, UA_UInt32 startChannelId,
-								UA_UInt32 startTokenId, UA_String *endpointUrl) {
-	UA_alloc((void**)&channelManager,sizeof(SL_ChannelManager));
-	UA_list_init(&(channelManager->channels));
-	channelManager->lastChannelId = startChannelId;
-	channelManager->lastTokenId = startTokenId;
-	UA_String_copy(endpointUrl,&channelManager->endpointUrl);
-	channelManager->maxChannelLifeTime = tokenLifetime;
-	channelManager->maxChannelCount = maxChannelCount;
-
-	return UA_SUCCESS;
-}
-
-UA_Int32 SL_ChannelManager_addChannel(SL_Channel *channel) {
-	if (!channelManager || (channelManager->maxChannelCount <= channelManager->channels.size))
-		return UA_ERROR;
-
-	//TODO lock access (mulitthreading)------------
-	UA_list_addPayloadToBack(&channelManager->channels,(void*)channel);
-	return UA_SUCCESS;
-	//TODO lock access------------
-}
-
-UA_Int32 generateNewTokenId() {
-	//TODO lock accesss
-	return channelManager->lastTokenId++;
-}
-
-UA_Int32 SL_ChannelManager_generateChannelId(UA_UInt32 *newChannelId) {
-	if(channelManager) {
-		*newChannelId = channelManager->lastChannelId++;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_UInt32 SL_ChannelManager_generateNewTokenId() {
-	return channelManager->lastTokenId++;
-}
-
-UA_Int32 SL_ChannelManager_generateToken(SL_Channel *channel, UA_Int32 requestedLifeTime,
-		SecurityTokenRequestType requestType,
-		UA_ChannelSecurityToken* newToken) {
-	UA_UInt32 tokenId;
-	if(channel){
-		SL_Channel_getTokenId(channel,&tokenId);
-		if(requestType==UA_SECURITYTOKEN_ISSUE) {
-			SL_Channel_getChannelId(channel,&newToken->channelId);
-			newToken->createdAt = UA_DateTime_now();
-			newToken->revisedLifetime = requestedLifeTime > channelManager->maxChannelLifeTime ? channelManager->maxChannelLifeTime : requestedLifeTime;
-			newToken->tokenId = SL_ChannelManager_generateNewTokenId();
-			return UA_SUCCESS;
-		} else if(requestType==UA_SECURITYTOKEN_RENEW) {
-			SL_Channel_getChannelId(channel,&newToken->channelId);
-			newToken->createdAt = UA_DateTime_now();
-			newToken->revisedLifetime = requestedLifeTime > channelManager->maxChannelLifeTime ? channelManager->maxChannelLifeTime : requestedLifeTime;
-			return UA_SUCCESS;
-		}
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_ChannelManager_removeChannel(UA_Int32 channelId) {
-	//TODO lock access
-	SL_Channel *channel;
-	UA_Int32 retval = UA_SUCCESS;
-	SL_ChannelManager_getChannel(channelId, &channel);
-
-	UA_list_Element *element =  UA_list_search(&channelManager->channels, (UA_list_PayloadComparer)SL_Channel_compare, &channel);
-	if(element) {
-		retval |= UA_list_removeElement(element,(UA_list_PayloadVisitor)SL_Channel_delete);
-		return retval;
-	}
-		//TODO notify server application that secureChannel has been closed part 6 - §7.1.4
-
-	return UA_ERROR;
-}
-
-UA_Int32 SL_ChannelManager_getChannelLifeTime(UA_DateTime *lifeTime) {
-	*lifeTime = channelManager->channelLifeTime;
-	return UA_SUCCESS;
-}
-
-/*UA_Int32 SL_ChannelManager_getChannelsByConnectionId(UA_Int32 connectionId,
-		SL_secureChannel **channels, UA_Int32 *noOfChannels)
-{
-	return UA_SUCCESS;UA_list_Element
-}
-*/
-
-UA_Int32 SL_ChannelManager_getChannel(UA_UInt32 channelId, SL_Channel **channel) {
-	UA_UInt32 tmpChannelId;
-	if(channelManager==UA_NULL){
-		*channel = UA_NULL;
-		return UA_ERROR;
-	}
-
- 	UA_list_Element* current = channelManager->channels.first;
-	while (current) {
-		if (current->payload) {
-			UA_list_Element* elem = (UA_list_Element*) current;
-			*channel = ((SL_Channel*) (elem->payload));
-			SL_Channel_getChannelId(*channel, &tmpChannelId);
-		 	if(tmpChannelId == channelId)
-		 		return UA_SUCCESS;
-		}
-		current = current->next;
-	}
-#ifdef DEBUG
-
-//	SL_Channel c1 = *(SL_Channel*)(channelManager->channels.first->payload);
-//	SL_Channel c2 = *(SL_Channel*)(channelManager->channels.last->payload);
-//	UA_UInt32 id1,id2;
-
-//	SL_Channel_getChannelId(c1,&id1);
-//	SL_Channel_getChannelId(c2,&id2);
-//
-//	printf("SL_ChannelManager_getChannel c1: %i \n",id1);
-//	printf("SL_ChannelManager_getChannel c2: %i \n",id2);
-#endif
-	*channel = UA_NULL;
-	return UA_ERROR;
-}
-

+ 0 - 17
src/server/ua_channel_manager.h

@@ -1,17 +0,0 @@
-#ifndef UA_CHANNEL_MANAGER_H_
-#define UA_CHANNEL_MANAGER_H_
-
-#include "ua_channel.h"
-
-struct SL_ChannelManager;
-typedef struct SL_ChannelManager SL_ChannelManager;
-
-UA_Int32 SL_ChannelManager_init(UA_UInt32 maxChannelCount,UA_UInt32 tokenLifetime, UA_UInt32 startChannelId, UA_UInt32 startTokenId, UA_String *endpointUrl);
-UA_Int32 SL_ChannelManager_addChannel(SL_Channel *channel);
-UA_Int32 SL_ChannelManager_removeChannel(UA_Int32 channelId);
-UA_Int32 SL_ChannelManager_getChannel(UA_UInt32 channelId, SL_Channel **channel);
-UA_Int32 SL_ChannelManager_getChannelLifeTime(UA_DateTime *lifeTime);
-UA_Int32 SL_ChannelManager_generateToken(SL_Channel *channel, UA_Int32 requestedLifeTime, SecurityTokenRequestType requestType, UA_ChannelSecurityToken* newToken);
-UA_Int32 SL_ChannelManager_generateChannelId(UA_UInt32 *newChannelId);
-
-#endif /* UA_CHANNEL_MANAGER_H_ */

+ 17 - 18
src/server/ua_namespace.c

@@ -2,8 +2,7 @@
 #include <string.h>
 #include <stdio.h>
 
-struct Namespace {
-	UA_UInt32 namespaceIndex;
+struct UA_Namespace {
 	const UA_Node ** entries;
 	UA_UInt32 size;
 	UA_UInt32 count;
@@ -105,7 +104,7 @@ static INLINE hash_t hash(const UA_NodeId *n) {
 	}
 }
 
-static INLINE void clear_entry(Namespace * ns, const UA_Node ** entry) {
+static INLINE void clear_entry(UA_Namespace * ns, const UA_Node ** entry) {
 	const UA_Node *node;
 	if(entry == UA_NULL || *entry == UA_NULL)
 		return;
@@ -145,7 +144,7 @@ static INLINE void clear_entry(Namespace * ns, const UA_Node ** entry) {
 
 /* Returns UA_SUCCESS if an entry was found. Otherwise, UA_ERROR is returned and the "entry"
    argument points to the first free entry under the NodeId. */
-static INLINE UA_Int32 find_entry(const Namespace * ns, const UA_NodeId * nodeid, const UA_Node *** entry) {
+static INLINE UA_Int32 find_entry(const UA_Namespace * ns, const UA_NodeId * nodeid, const UA_Node *** entry) {
 	hash_t h = hash(nodeid);
 	UA_UInt32 size = ns->size;
 	hash_t index = mod(h, size);
@@ -188,7 +187,7 @@ static INLINE UA_Int32 find_entry(const Namespace * ns, const UA_NodeId * nodeid
    repeatedly inserts the table elements. The occupancy of the table after the
    call will be about 50%. If memory allocation failures occur, this function
    will return UA_ERROR. */
-static UA_Int32 expand(Namespace * ns) {
+static UA_Int32 expand(UA_Namespace * ns) {
 	const UA_Node **nentries;
 	int32_t nsize;
 	UA_UInt32 nindex;
@@ -232,10 +231,10 @@ static UA_Int32 expand(Namespace * ns) {
 /* Exported functions */
 /**********************/
 
-UA_Int32 Namespace_new(Namespace ** result, UA_UInt32 namespaceIndex) {
-	Namespace *ns;
+UA_Int32 UA_Namespace_new(UA_Namespace ** result) {
+	UA_Namespace *ns;
 	UA_UInt32 sizePrimeIndex, size;
-	if(UA_alloc((void **)&ns, sizeof(Namespace)) != UA_SUCCESS)
+	if(UA_alloc((void **)&ns, sizeof(UA_Namespace)) != UA_SUCCESS)
 		return UA_ERR_NO_MEMORY;
 
 	sizePrimeIndex = higher_prime_index(32);
@@ -248,12 +247,12 @@ UA_Int32 Namespace_new(Namespace ** result, UA_UInt32 namespaceIndex) {
 	/* set entries to zero */
 	memset(ns->entries, 0, size * sizeof(UA_Node *));
 
-	*ns = (Namespace) {namespaceIndex, ns->entries, size, 0, sizePrimeIndex};
+	*ns = (UA_Namespace) {ns->entries, size, 0, sizePrimeIndex};
 	*result = ns;
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_delete(Namespace * ns) {
+UA_Int32 UA_Namespace_delete(UA_Namespace * ns) {
 	UA_UInt32 size = ns->size;
 	const UA_Node **entries = ns->entries;
 
@@ -265,7 +264,7 @@ UA_Int32 Namespace_delete(Namespace * ns) {
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
+UA_Int32 UA_Namespace_insert(UA_Namespace *ns, UA_Node **node, UA_Byte flags) {
 	if(ns == UA_NULL || node == UA_NULL || *node == UA_NULL)
 		return UA_ERROR;
 	
@@ -277,7 +276,7 @@ UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
 	const UA_Node ** entry;
 	UA_Int32 found = find_entry(ns, &(*node)->nodeId, &entry);
 
-	if(flags & NAMESPACE_INSERT_UNIQUE) {
+	if(flags & UA_NAMESPACE_INSERT_UNIQUE) {
 		if(found == UA_SUCCESS)
 			return UA_ERROR;	/* There is already an entry for that nodeid */
 		else
@@ -288,14 +287,14 @@ UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
 		*entry = *node;
 	}
 
-	if(!(flags & NAMESPACE_INSERT_GETMANAGED))
+	if(!(flags & UA_NAMESPACE_INSERT_GETMANAGED))
 		*node = UA_NULL;
 	
 	ns->count++;
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_get(const Namespace *ns, const UA_NodeId *nodeid, const UA_Node **managedNode) {
+UA_Int32 UA_Namespace_get(const UA_Namespace *ns, const UA_NodeId *nodeid, const UA_Node **managedNode) {
 	const UA_Node **entry;
 	if(ns == UA_NULL || nodeid == UA_NULL || managedNode == UA_NULL)
 		return UA_ERROR;
@@ -307,12 +306,12 @@ UA_Int32 Namespace_get(const Namespace *ns, const UA_NodeId *nodeid, const UA_No
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_remove(Namespace * ns, const UA_NodeId * nodeid) {
+UA_Int32 UA_Namespace_remove(UA_Namespace * ns, const UA_NodeId * nodeid) {
 	const UA_Node **entry;
 	if(find_entry(ns, nodeid, &entry) != UA_SUCCESS)
 		return UA_ERROR;
 
-	// Check before if deleting the node makes the Namespace inconsistent.
+	// Check before if deleting the node makes the UA_Namespace inconsistent.
 	clear_entry(ns, entry);
 
 	/* Downsize the hashmap if it is very empty */
@@ -322,7 +321,7 @@ UA_Int32 Namespace_remove(Namespace * ns, const UA_NodeId * nodeid) {
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_iterate(const Namespace * ns, Namespace_nodeVisitor visitor) {
+UA_Int32 UA_Namespace_iterate(const UA_Namespace * ns, UA_Namespace_nodeVisitor visitor) {
 	if(ns == UA_NULL || visitor == UA_NULL)
 		return UA_ERROR;
 	
@@ -334,6 +333,6 @@ UA_Int32 Namespace_iterate(const Namespace * ns, Namespace_nodeVisitor visitor)
 	return UA_SUCCESS;
 }
 
-void Namespace_releaseManagedNode(const UA_Node *managed) {
+void UA_Namespace_releaseManagedNode(const UA_Node *managed) {
 	;
 }

+ 20 - 17
src/server/ua_namespace.h

@@ -1,11 +1,13 @@
-#ifndef __NAMESPACE_H__
-#define __NAMESPACE_H__
+#ifndef UA_NAMESPACE_H_
+#define UA_NAMESPACE_H_
 
 #include "ua_types.h"
 #include "ua_types_generated.h"
 #include "util/ua_list.h"
 
 /**
+   @ingroup server
+   
    @defgroup namespace Namespace
 
    @brief The namespace is the central storage for nodes in the UA address
@@ -21,45 +23,46 @@
    @{
  */
 
-/** @brief Namespace datastructure. Mainly a hashmap to UA_Nodes */
-struct Namespace;
-typedef struct Namespace Namespace;
+/** @brief UA_Namespace datastructure. Mainly a hashmap to UA_Nodes */
+struct UA_Namespace;
+typedef struct UA_Namespace UA_Namespace;
 
 /** @brief Create a new namespace */
-UA_Int32 Namespace_new(Namespace **result, UA_UInt32 namespaceIndex);
+UA_Int32 UA_Namespace_new(UA_Namespace **result);
 
 /** @brief Delete the namespace and all nodes in it */
-UA_Int32 Namespace_delete(Namespace *ns);
+UA_Int32 UA_Namespace_delete(UA_Namespace *ns);
 
-#define NAMESPACE_INSERT_UNIQUE 1
-#define NAMESPACE_INSERT_GETMANAGED 2
+#define UA_NAMESPACE_INSERT_UNIQUE 1
+#define UA_NAMESPACE_INSERT_GETMANAGED 2
 /** @brief Insert a new node into the namespace
 
     With the UNIQUE flag, the node is only inserted if the nodeid does not
     already exist. With the GETMANAGED flag, the node pointer is replaced with
     the managed pointer. Otherwise, it is set to UA_NULL. */
-UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags);
+UA_Int32 UA_Namespace_insert(UA_Namespace *ns, UA_Node **node, UA_Byte flags);
 
 /** @brief Remove a node from the namespace. Always succeeds, even if the node
 	was not found. */
-UA_Int32 Namespace_remove(Namespace *ns, const UA_NodeId *nodeid);
+UA_Int32 UA_Namespace_remove(UA_Namespace *ns, const UA_NodeId *nodeid);
 
 /** @brief Retrieve a node (read-only) from the namespace. Nodes are immutable.
     They can only be replaced. After the Node is no longer used, the locked
     entry needs to be released. */
-UA_Int32 Namespace_get(const Namespace *ns, const UA_NodeId *nodeid, const UA_Node **managedNode);
+UA_Int32 UA_Namespace_get(const UA_Namespace *ns, const UA_NodeId *nodeid,
+						  const UA_Node **managedNode);
 
 /** @brief Release a managed node. Do never insert a node that isn't stored in a
 	namespace. */
-void Namespace_releaseManagedNode(const UA_Node *managed);
+void UA_Namespace_releaseManagedNode(const UA_Node *managed);
 
 /** @brief A function that can be evaluated on all entries in a namespace via
-	Namespace_iterate. Note that the visitor is read-only on the nodes. */
-typedef void (*Namespace_nodeVisitor)(const UA_Node *node);
+	UA_Namespace_iterate. Note that the visitor is read-only on the nodes. */
+typedef void (*UA_Namespace_nodeVisitor)(const UA_Node *node);
 
 /** @brief Iterate over all nodes in a namespace. */
-UA_Int32 Namespace_iterate(const Namespace *ns, Namespace_nodeVisitor visitor);
+UA_Int32 UA_Namespace_iterate(const UA_Namespace *ns, UA_Namespace_nodeVisitor visitor);
 
 /// @} /* end of group */
 
-#endif /* __NAMESPACE_H */
+#endif /* UA_NAMESPACE_H_ */

+ 27 - 29
src/server/ua_namespace_concurrent.c

@@ -5,17 +5,15 @@
 #include <urcu/uatomic.h>
 #include <urcu/rculfhash.h>
 
-
 #define ALIVE_BIT (1 << 15) /* Alive bit in the readcount */
-typedef struct Namespace_Entry {
+typedef struct UA_Namespace_Entry {
 	struct cds_lfht_node htn; /* contains next-ptr for urcu-hashmap */
 	struct rcu_head rcu_head; /* For call-rcu */
 	UA_UInt16 readcount;      /* Counts the amount of readers on it [alive-bit, 15 counter-bits] */
 	UA_Node   node;           /* Might be cast from any _bigger_ UA_Node* type. Allocate enough memory! */
-} Namespace_Entry;
+} UA_Namespace_Entry;
 
-struct Namespace {
-	UA_UInt32       namespaceIndex;
+struct UA_Namespace {
 	struct cds_lfht *ht; /* Hash table */
 };
 
@@ -97,7 +95,7 @@ static inline hash_t hash(const UA_NodeId *n) {
 }
 
 /*************/
-/* Namespace */
+/* UA_Namespace */
 /*************/
 
 static inline void node_deleteMembers(const UA_Node *node) {
@@ -142,7 +140,7 @@ static inline void node_deleteMembers(const UA_Node *node) {
 /* We are in a rcu_read lock. So the node will not be freed under our feet. */
 static int compare(struct cds_lfht_node *htn, const void *orig) {
 	UA_NodeId *origid = (UA_NodeId*)orig;
-	UA_NodeId   *newid  = &((Namespace_Entry *)htn)->node.nodeId; /* The htn is first in the entry structure. */
+	UA_NodeId   *newid  = &((UA_Namespace_Entry *)htn)->node.nodeId; /* The htn is first in the entry structure. */
 
 	return UA_NodeId_equal(newid, origid) == UA_EQUAL;
 }
@@ -152,7 +150,7 @@ static int compare(struct cds_lfht_node *htn, const void *orig) {
    section) increased the readcount, we only need to wait for the readcount
    to reach zero. */
 static void markDead(struct rcu_head *head) {
-	Namespace_Entry *entry = caa_container_of(head, Namespace_Entry, rcu_head);
+	UA_Namespace_Entry *entry = caa_container_of(head, UA_Namespace_Entry, rcu_head);
 	if(uatomic_sub_return(&entry->readcount, ALIVE_BIT) > 0)
 		return;
 
@@ -162,11 +160,11 @@ static void markDead(struct rcu_head *head) {
 }
 
 /* Free the entry if it is dead and nobody uses it anymore */
-void Namespace_releaseManagedNode(const UA_Node *managed) {
+void UA_Namespace_releaseManagedNode(const UA_Node *managed) {
 	if(managed == UA_NULL)
 		return;
 	
-	Namespace_Entry *entry = caa_container_of(managed, Namespace_Entry, node); // pointer to the first entry
+	UA_Namespace_Entry *entry = caa_container_of(managed, UA_Namespace_Entry, node); // pointer to the first entry
 	if(uatomic_sub_return(&entry->readcount, 1) > 0)
 		return;
 
@@ -175,9 +173,9 @@ void Namespace_releaseManagedNode(const UA_Node *managed) {
 	return;
 }
 
-UA_Int32 Namespace_new(Namespace **result, UA_UInt32 namespaceIndex) {
-	Namespace *ns;
-	if(UA_alloc((void **)&ns, sizeof(Namespace)) != UA_SUCCESS)
+UA_Int32 UA_Namespace_new(UA_Namespace **result, UA_UInt32 namespaceIndex) {
+	UA_Namespace *ns;
+	if(UA_alloc((void **)&ns, sizeof(UA_Namespace)) != UA_SUCCESS)
 		return UA_ERR_NO_MEMORY;
 
 	/* 32 is the minimum size for the hashtable. */
@@ -192,7 +190,7 @@ UA_Int32 Namespace_new(Namespace **result, UA_UInt32 namespaceIndex) {
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_delete(Namespace *ns) {
+UA_Int32 UA_Namespace_delete(UA_Namespace *ns) {
 	if(ns == UA_NULL)
 		return UA_ERROR;
 
@@ -205,7 +203,7 @@ UA_Int32 Namespace_delete(Namespace *ns) {
 	while(iter.node != UA_NULL) {
 		found_htn = cds_lfht_iter_get_node(&iter);
 		if(!cds_lfht_del(ht, found_htn)) {
-			Namespace_Entry *entry = caa_container_of(found_htn, Namespace_Entry, htn);
+			UA_Namespace_Entry *entry = caa_container_of(found_htn, UA_Namespace_Entry, htn);
 			call_rcu(&entry->rcu_head, markDead);
 		}
 		cds_lfht_next(ht, &iter);
@@ -220,7 +218,7 @@ UA_Int32 Namespace_delete(Namespace *ns) {
 		return UA_ERROR;
 }
 
-UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
+UA_Int32 UA_Namespace_insert(UA_Namespace *ns, UA_Node **node, UA_Byte flags) {
 	if(ns == UA_NULL || node == UA_NULL || *node == UA_NULL || (*node)->nodeId.namespaceIndex != ns->namespaceIndex)
 		return UA_ERROR;
 
@@ -263,19 +261,19 @@ UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
 		return UA_ERROR;
 	}
 
-	Namespace_Entry *entry;
-	if(UA_alloc((void **)&entry, sizeof(Namespace_Entry) - sizeof(UA_Node) + nodesize))
+	UA_Namespace_Entry *entry;
+	if(UA_alloc((void **)&entry, sizeof(UA_Namespace_Entry) - sizeof(UA_Node) + nodesize))
 		return UA_ERR_NO_MEMORY;
 	memcpy(&entry->node, *node, nodesize);
 
 	cds_lfht_node_init(&entry->htn);
 	entry->readcount = ALIVE_BIT;
-	if(flags & NAMESPACE_INSERT_GETMANAGED)
+	if(flags & UA_NAMESPACE_INSERT_GETMANAGED)
 		entry->readcount++;
 
 	hash_t nhash = hash(&(*node)->nodeId);
 	struct cds_lfht_node *result;
-	if(flags & NAMESPACE_INSERT_UNIQUE) {
+	if(flags & UA_NAMESPACE_INSERT_UNIQUE) {
 		rcu_read_lock();
 		result = cds_lfht_add_unique(ns->ht, nhash, compare, &entry->node.nodeId, &entry->htn);
 		rcu_read_unlock();
@@ -290,14 +288,14 @@ UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
 		result = cds_lfht_add_replace(ns->ht, nhash, compare, &(*node)->nodeId, &entry->htn);
 		/* If an entry got replaced, mark it as dead. */
 		if(result) {
-			Namespace_Entry *entry = caa_container_of(result, Namespace_Entry, htn);
+			UA_Namespace_Entry *entry = caa_container_of(result, UA_Namespace_Entry, htn);
 			call_rcu(&entry->rcu_head, markDead);      /* Queue this for the next time when no readers are on the entry.*/
 		}
 		rcu_read_unlock();
 	}
 
 	UA_free((UA_Node*)*node);     /* The old node is replaced by a managed node. */
-	if(flags & NAMESPACE_INSERT_GETMANAGED)
+	if(flags & UA_NAMESPACE_INSERT_GETMANAGED)
 		*node = &entry->node;
 	else
 		*node = UA_NULL;
@@ -305,7 +303,7 @@ UA_Int32 Namespace_insert(Namespace *ns, UA_Node **node, UA_Byte flags) {
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_remove(Namespace *ns, const UA_NodeId *nodeid) {
+UA_Int32 UA_Namespace_remove(UA_Namespace *ns, const UA_NodeId *nodeid) {
 	hash_t nhash = hash(nodeid);
 	struct cds_lfht_iter iter;
 
@@ -319,20 +317,20 @@ UA_Int32 Namespace_remove(Namespace *ns, const UA_NodeId *nodeid) {
 		return UA_ERROR;
 	}
 	
-	Namespace_Entry *entry = caa_container_of(found_htn, Namespace_Entry, htn);
+	UA_Namespace_Entry *entry = caa_container_of(found_htn, UA_Namespace_Entry, htn);
 	call_rcu(&entry->rcu_head, markDead);
 	rcu_read_unlock();
 
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_get(const Namespace *ns, const UA_NodeId *nodeid, const UA_Node **managedNode) {
+UA_Int32 UA_Namespace_get(const UA_Namespace *ns, const UA_NodeId *nodeid, const UA_Node **managedNode) {
 	hash_t nhash     = hash(nodeid);
 	struct cds_lfht_iter iter;
 
 	rcu_read_lock();
 	cds_lfht_lookup(ns->ht, nhash, compare, nodeid, &iter);
-	Namespace_Entry *found_entry = (Namespace_Entry *)cds_lfht_iter_get_node(&iter);
+	UA_Namespace_Entry *found_entry = (UA_Namespace_Entry *)cds_lfht_iter_get_node(&iter);
 
 	if(!found_entry) {
 		rcu_read_unlock();
@@ -347,7 +345,7 @@ UA_Int32 Namespace_get(const Namespace *ns, const UA_NodeId *nodeid, const UA_No
 	return UA_SUCCESS;
 }
 
-UA_Int32 Namespace_iterate(const Namespace *ns, Namespace_nodeVisitor visitor) {
+UA_Int32 UA_Namespace_iterate(const UA_Namespace *ns, UA_Namespace_nodeVisitor visitor) {
 	if(ns == UA_NULL || visitor == UA_NULL)
 		return UA_ERROR;
 	
@@ -357,12 +355,12 @@ UA_Int32 Namespace_iterate(const Namespace *ns, Namespace_nodeVisitor visitor) {
 	rcu_read_lock();
 	cds_lfht_first(ht, &iter);
 	while(iter.node != UA_NULL) {
-		Namespace_Entry *found_entry = (Namespace_Entry *)cds_lfht_iter_get_node(&iter);
+		UA_Namespace_Entry *found_entry = (UA_Namespace_Entry *)cds_lfht_iter_get_node(&iter);
 		uatomic_inc(&found_entry->readcount);
 		const UA_Node *node = &found_entry->node;
 		rcu_read_unlock();
 		visitor(node);
-		Namespace_releaseManagedNode((UA_Node *)node);
+		UA_Namespace_releaseManagedNode((UA_Node *)node);
 		rcu_read_lock();
 		cds_lfht_next(ht, &iter);
 	}

+ 139 - 0
src/server/ua_securechannel_manager.c

@@ -0,0 +1,139 @@
+#include "ua_securechannel_manager.h"
+#include "util/ua_util.h"
+
+struct channel_list_entry {
+	UA_SecureChannel channel;
+	LIST_ENTRY(channel_list_entry) pointers;
+};
+
+struct UA_SecureChannelManager {
+	UA_Int32 maxChannelCount;
+	UA_DateTime maxChannelLifetime;
+	LIST_HEAD(channel_list, channel_list_entry) channels;
+	UA_MessageSecurityMode securityMode;
+	UA_String endpointUrl;
+	UA_DateTime channelLifeTime;
+	UA_Int32 lastChannelId;
+	UA_UInt32 lastTokenId;
+};
+
+UA_Int32 UA_SecureChannelManager_new(UA_SecureChannelManager **cm, UA_UInt32 maxChannelCount,
+							UA_UInt32 tokenLifetime, UA_UInt32 startChannelId,
+							UA_UInt32 startTokenId, UA_String *endpointUrl) {
+	UA_alloc((void**)cm,sizeof(UA_SecureChannelManager));
+	UA_SecureChannelManager *channelManager = *cm;
+	LIST_INIT(&channelManager->channels);
+	channelManager->lastChannelId = startChannelId;
+	channelManager->lastTokenId = startTokenId;
+	UA_String_copy(endpointUrl,&channelManager->endpointUrl);
+	channelManager->maxChannelLifetime = tokenLifetime;
+	channelManager->maxChannelCount = maxChannelCount;
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_SecureChannelManager_delete(UA_SecureChannelManager *cm) {
+	struct channel_list_entry *entry;
+	LIST_FOREACH(entry, &cm->channels, pointers) {
+		// deleting a securechannel means closing the connection
+		// delete the binaryconnction beforehand. so there is no pointer
+		// todo: unbind entry->channel.connection;
+		LIST_REMOVE(entry, pointers);
+		UA_SecureChannel_deleteMembers(&entry->channel);
+		UA_free(entry);
+	}
+	UA_String_deleteMembers(&cm->endpointUrl);
+	UA_free(cm);	
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_SecureChannelManager_open(UA_SecureChannelManager *cm,
+									  UA_Connection *conn,
+									  const UA_OpenSecureChannelRequest* request,
+									  UA_OpenSecureChannelResponse* response) {
+	struct channel_list_entry *entry;
+	UA_alloc((void**)&entry, sizeof(struct channel_list_entry));
+
+	entry->channel.connection = conn;
+	entry->channel.securityToken.channelId = cm->lastChannelId++;
+	entry->channel.securityToken.tokenId = cm->lastTokenId++;
+	entry->channel.securityToken.createdAt = UA_DateTime_now();
+	entry->channel.securityToken.revisedLifetime =
+		request->requestedLifetime > cm->maxChannelLifetime ?
+		cm->maxChannelLifetime : request->requestedLifetime;
+
+	switch (request->securityMode) {
+	case UA_SECURITYMODE_INVALID:
+		printf("UA_SecureChannel_processOpenRequest - client demands invalid \n");
+		break;
+
+	case UA_SECURITYMODE_NONE:
+		UA_ByteString_copy(&request->clientNonce, &entry->channel.clientNonce);
+		entry->channel.clientAsymAlgSettings.receiverCertificateThumbprint.data = UA_NULL;
+		entry->channel.clientAsymAlgSettings.receiverCertificateThumbprint.length = -1;
+		entry->channel.clientAsymAlgSettings.senderCertificate.data = UA_NULL;
+		entry->channel.clientAsymAlgSettings.senderCertificate.length = -1;
+		break;
+
+	case UA_SECURITYMODE_SIGNANDENCRYPT:
+		printf("UA_SecureChannel_processOpenRequest - client demands signed & encrypted \n");
+		//TODO check if senderCertificate and ReceiverCertificateThumbprint are present
+		break;
+	}
+
+	UA_String_copycstring("http://opcfoundation.org/UA/SecurityPolicy#None",
+						  (UA_String*)&entry->channel.serverAsymAlgSettings.securityPolicyUri);
+	LIST_INSERT_HEAD(&cm->channels, entry, pointers);
+
+	response->serverProtocolVersion = 0;
+	UA_SecureChannel_generateNonce(&entry->channel.serverNonce);
+	UA_ByteString_copy(&entry->channel.serverNonce, &response->serverNonce);
+	UA_ChannelSecurityToken_copy(&entry->channel.securityToken, &response->securityToken);
+	
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_SecureChannelManager_renew(UA_SecureChannelManager *cm,
+									   UA_Connection *conn,
+									   const UA_OpenSecureChannelRequest* request,
+									   UA_OpenSecureChannelResponse* response) {
+
+	UA_SecureChannel *channel = conn->channel;
+	if(channel == UA_NULL)
+		return UA_ERROR;
+
+
+	// TODO write response
+
+	channel->securityToken.createdAt = UA_DateTime_now(); // todo: is wanted?
+	channel->securityToken.revisedLifetime = request->requestedLifetime > cm->maxChannelLifetime ?
+		cm->maxChannelLifetime : request->requestedLifetime;
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_SecureChannelManager_get(UA_SecureChannelManager *cm, UA_UInt32 channelId, UA_SecureChannel **channel) {
+	struct channel_list_entry *entry;
+	LIST_FOREACH(entry, &cm->channels, pointers) {
+		if(entry->channel.securityToken.channelId == channelId) {
+			*channel = &entry->channel;
+			return UA_SUCCESS;
+		}
+	}
+	*channel = UA_NULL;
+	return UA_ERROR;
+}
+
+UA_Int32 UA_SecureChannelManager_close(UA_SecureChannelManager *cm, UA_UInt32 channelId) {
+	//TODO lock access
+	// TODO: close the binaryconnection if it is still open. So we dö not have stray pointers..
+	struct channel_list_entry *entry;
+	LIST_FOREACH(entry, &cm->channels, pointers) {
+		if(entry->channel.securityToken.channelId == channelId) {
+			UA_SecureChannel_deleteMembers(&entry->channel);
+			LIST_REMOVE(entry, pointers);
+			UA_free(entry);
+			return UA_SUCCESS;
+		}
+	}
+	//TODO notify server application that secureChannel has been closed part 6 - §7.1.4
+	return UA_ERROR;
+}

+ 24 - 0
src/server/ua_securechannel_manager.h

@@ -0,0 +1,24 @@
+#ifndef UA_CHANNEL_MANAGER_H_
+#define UA_CHANNEL_MANAGER_H_
+
+#include "ua_types_generated.h"
+#include "ua_securechannel.h"
+
+struct UA_SecureChannelManager;
+typedef struct UA_SecureChannelManager UA_SecureChannelManager;
+
+UA_Int32 UA_SecureChannelManager_new(UA_SecureChannelManager **cm, UA_UInt32 maxChannelCount,
+									 UA_UInt32 tokenLifetime, UA_UInt32 startChannelId,
+									 UA_UInt32 startTokenId, UA_String *endpointUrl);
+UA_Int32 UA_SecureChannelManager_delete(UA_SecureChannelManager *cm);
+UA_Int32 UA_SecureChannelManager_open(UA_SecureChannelManager *cm, UA_Connection *conn,
+										const UA_OpenSecureChannelRequest* request,
+										UA_OpenSecureChannelResponse* response);
+UA_Int32 UA_SecureChannelManager_renew(UA_SecureChannelManager *cm, UA_Connection *conn,
+									   const UA_OpenSecureChannelRequest* request,
+									   UA_OpenSecureChannelResponse* response);
+UA_Int32 UA_SecureChannelManager_get(UA_SecureChannelManager *cm, UA_UInt32 channelId,
+									   UA_SecureChannel **channel);
+UA_Int32 UA_SecureChannelManager_close(UA_SecureChannelManager *cm, UA_UInt32 channelId);
+
+#endif /* UA_CHANNEL_MANAGER_H_ */

+ 576 - 0
src/server/ua_server.c

@@ -1,2 +1,578 @@
 #include "ua_server.h"
+#include "ua_services_internal.h" // AddReferences
+#include "ua_namespace_0.h"
 
+UA_Int32 UA_Server_deleteMembers(UA_Server *server) {
+	UA_ApplicationDescription_delete(&server->description);
+	UA_SecureChannelManager_delete(server->secureChannelManager);
+	UA_SessionManager_delete(server->sessionManager);
+	for(UA_UInt32 i=0;i<server->namespacesSize;i++)
+		UA_Namespace_delete(server->namespaces[i].namespace);
+
+	UA_free(server->namespaces);
+	UA_free(server);
+	return UA_SUCCESS;
+}
+
+void UA_Server_init(UA_Server *server, UA_String *endpointUrl) {
+	UA_ApplicationDescription_init(&server->description);
+#define MAXCHANNELCOUNT 100
+#define STARTCHANNELID 1
+#define TOKENLIFETIME 10000
+#define STARTTOKENID 1
+	UA_SecureChannelManager_new(&server->secureChannelManager, MAXCHANNELCOUNT,
+		TOKENLIFETIME, STARTCHANNELID, STARTTOKENID, endpointUrl);
+
+#define MAXSESSIONCOUNT 1000
+#define SESSIONLIFETIME 10000
+#define STARTSESSIONID 1
+	UA_SessionManager_new(&server->sessionManager, MAXSESSIONCOUNT, SESSIONLIFETIME,
+		STARTSESSIONID);
+	
+	// todo: get this out of here!!!
+	// fill the UA_borrowed_ table that has been declaed in ua_namespace.c
+	for(UA_Int32 i=0;i<SIZE_UA_VTABLE;i++){
+		UA_borrowed_.types[i] = UA_.types[i];
+		UA_borrowed_.types[i].delete=(UA_Int32(*)(void *))phantom_delete;
+		UA_borrowed_.types[i].deleteMembers=(UA_Int32(*)(void *))phantom_delete;
+	}
+
+	// create namespaces
+	server->namespacesSize = 2;
+	UA_alloc((void**)&server->namespaces, sizeof(UA_IndexedNamespace)*2);
+
+	UA_Namespace_new(&server->namespaces[0].namespace);
+	server->namespaces[0].namespaceIndex = 0;
+	UA_Namespace *ns0 = server->namespaces[0].namespace;
+	//C2UA_STRING("http://opcfoundation.org/UA/"));
+
+	UA_Namespace_new(&server->namespaces[1].namespace);
+	server->namespaces[1].namespaceIndex = 1;
+	//UA_Namespace *ns1 = server->namespaces[1].namespace;
+	//C2UA_STRING("http://localhost:16664/open62541/"));
+
+	/**************/
+	/* References */
+	/**************/
+
+	// ReferenceType Ids
+	UA_NodeId RefTypeId_References = NS0NODEID(31);
+	UA_NodeId RefTypeId_NonHierarchicalReferences = NS0NODEID(32);
+	UA_NodeId RefTypeId_HierarchicalReferences = NS0NODEID(33);
+	UA_NodeId RefTypeId_HasChild = NS0NODEID(34);
+	UA_NodeId RefTypeId_Organizes = NS0NODEID(35);
+	UA_NodeId RefTypeId_HasEventSource = NS0NODEID(36);
+	UA_NodeId RefTypeId_HasModellingRule = NS0NODEID(37);
+	UA_NodeId RefTypeId_HasEncoding = NS0NODEID(38);
+	UA_NodeId RefTypeId_HasDescription = NS0NODEID(39);
+	UA_NodeId RefTypeId_HasTypeDefinition = NS0NODEID(40);
+	UA_NodeId RefTypeId_GeneratesEvent = NS0NODEID(41);
+	UA_NodeId RefTypeId_Aggregates = NS0NODEID(44);
+	UA_NodeId RefTypeId_HasSubtype = NS0NODEID(45);
+	UA_NodeId RefTypeId_HasProperty = NS0NODEID(46);
+	UA_NodeId RefTypeId_HasComponent = NS0NODEID(47);
+	UA_NodeId RefTypeId_HasNotifier = NS0NODEID(48);
+	UA_NodeId RefTypeId_HasOrderedComponent = NS0NODEID(49);
+	UA_NodeId RefTypeId_HasModelParent = NS0NODEID(50);
+	UA_NodeId RefTypeId_FromState = NS0NODEID(51);
+	UA_NodeId RefTypeId_ToState = NS0NODEID(52);
+	UA_NodeId RefTypeId_HasCause = NS0NODEID(53);
+	UA_NodeId RefTypeId_HasEffect = NS0NODEID(54);
+	UA_NodeId RefTypeId_HasHistoricalConfiguration = NS0NODEID(56);
+
+#define ADDINVERSEREFERENCE(NODE,REFTYPE,TARGET_NODEID) \
+	static struct UA_ReferenceNode NODE##ReferenceNode; \
+	UA_ReferenceNode_init(&NODE##ReferenceNode); \
+	NODE##ReferenceNode.referenceTypeId = REFTYPE; \
+	NODE##ReferenceNode.isInverse = UA_TRUE; \
+	NODE##ReferenceNode.targetId.nodeId = TARGET_NODEID; \
+	NODE##ReferenceNode.targetId.namespaceUri = UA_STRING_NULL; \
+	NODE##ReferenceNode.targetId.serverIndex = 0; \
+	AddReference((UA_Node*)NODE, &NODE##ReferenceNode, ns0)
+
+	UA_ReferenceTypeNode *references;
+	UA_ReferenceTypeNode_new(&references);
+	references->nodeId = RefTypeId_References;
+	references->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(references->browseName, "References");
+	UA_LOCALIZEDTEXT_STATIC(references->displayName, "References");
+	UA_LOCALIZEDTEXT_STATIC(references->description, "References");
+	references->isAbstract = UA_TRUE;
+	references->symmetric = UA_TRUE;
+	UA_Namespace_insert(ns0,(UA_Node**)&references, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hierarchicalreferences;
+	UA_ReferenceTypeNode_new(&hierarchicalreferences);
+	hierarchicalreferences->nodeId = RefTypeId_HierarchicalReferences;
+	hierarchicalreferences->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hierarchicalreferences->browseName, "HierarchicalReferences");
+	UA_LOCALIZEDTEXT_STATIC(hierarchicalreferences->displayName, "HierarchicalReferences");
+	UA_LOCALIZEDTEXT_STATIC(hierarchicalreferences->description, "HierarchicalReferences");
+	hierarchicalreferences->isAbstract = UA_TRUE;
+	hierarchicalreferences->symmetric = UA_FALSE;
+	ADDINVERSEREFERENCE(hierarchicalreferences, RefTypeId_HasSubtype, RefTypeId_References);
+	UA_Namespace_insert(ns0,(UA_Node**)&hierarchicalreferences, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *nonhierarchicalreferences;
+	UA_ReferenceTypeNode_new(&nonhierarchicalreferences);
+	nonhierarchicalreferences->nodeId = RefTypeId_NonHierarchicalReferences;
+	nonhierarchicalreferences->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(nonhierarchicalreferences->browseName, "NonHierarchicalReferences");
+	UA_LOCALIZEDTEXT_STATIC(nonhierarchicalreferences->displayName, "NonHierarchicalReferences");
+	UA_LOCALIZEDTEXT_STATIC(nonhierarchicalreferences->description, "NonHierarchicalReferences");
+	nonhierarchicalreferences->isAbstract = UA_TRUE;
+	nonhierarchicalreferences->symmetric = UA_FALSE;
+	ADDINVERSEREFERENCE(nonhierarchicalreferences, RefTypeId_HasSubtype, RefTypeId_References);
+	UA_Namespace_insert(ns0,(UA_Node**)&nonhierarchicalreferences, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *haschild;
+	UA_ReferenceTypeNode_new(&haschild);
+	haschild->nodeId = RefTypeId_HasChild;
+	haschild->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(haschild->browseName, "HasChild");
+	UA_LOCALIZEDTEXT_STATIC(haschild->displayName, "HasChild");
+	UA_LOCALIZEDTEXT_STATIC(haschild->description, "HasChild");
+	haschild->isAbstract = UA_TRUE;
+	haschild->symmetric = UA_FALSE;
+	ADDINVERSEREFERENCE(haschild, RefTypeId_HasSubtype, RefTypeId_HierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&haschild, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *organizes;
+	UA_ReferenceTypeNode_new(&organizes);
+	organizes->nodeId = RefTypeId_Organizes;
+	organizes->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(organizes->browseName, "Organizes");
+	UA_LOCALIZEDTEXT_STATIC(organizes->displayName, "Organizes");
+	UA_LOCALIZEDTEXT_STATIC(organizes->description, "Organizes");
+	organizes->isAbstract = UA_FALSE;
+	organizes->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(organizes->inverseName, "OrganizedBy");
+	ADDINVERSEREFERENCE(organizes, RefTypeId_HasSubtype, RefTypeId_HierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&organizes, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *haseventsource;
+	UA_ReferenceTypeNode_new(&haseventsource);
+	haseventsource->nodeId = RefTypeId_HasEventSource;
+	haseventsource->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(haseventsource->browseName, "HasEventSource");
+	UA_LOCALIZEDTEXT_STATIC(haseventsource->displayName, "HasEventSource");
+	UA_LOCALIZEDTEXT_STATIC(haseventsource->description, "HasEventSource");
+	haseventsource->isAbstract = UA_FALSE;
+	haseventsource->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(haseventsource->inverseName, "EventSourceOf");
+	ADDINVERSEREFERENCE(haseventsource, RefTypeId_HasSubtype, RefTypeId_HierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&haseventsource, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasmodellingrule;
+	UA_ReferenceTypeNode_new(&hasmodellingrule);
+	hasmodellingrule->nodeId = RefTypeId_HasModellingRule;
+	hasmodellingrule->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasmodellingrule->browseName, "HasModellingRule");
+	UA_LOCALIZEDTEXT_STATIC(hasmodellingrule->displayName, "HasModellingRule");
+	UA_LOCALIZEDTEXT_STATIC(hasmodellingrule->description, "HasModellingRule");
+	hasmodellingrule->isAbstract = UA_FALSE;
+	hasmodellingrule->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasmodellingrule->inverseName, "ModellingRuleOf");
+	ADDINVERSEREFERENCE(hasmodellingrule, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasmodellingrule, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasencoding;
+	UA_ReferenceTypeNode_new(&hasencoding);
+	hasencoding->nodeId = RefTypeId_HasEncoding;
+	hasencoding->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasencoding->browseName, "HasEncoding");
+	UA_LOCALIZEDTEXT_STATIC(hasencoding->displayName, "HasEncoding");
+	UA_LOCALIZEDTEXT_STATIC(hasencoding->description, "HasEncoding");
+	hasencoding->isAbstract = UA_FALSE;
+	hasencoding->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasencoding->inverseName, "EncodingOf");
+	ADDINVERSEREFERENCE(hasencoding, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasencoding, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasdescription;
+	UA_ReferenceTypeNode_new(&hasdescription);
+	hasdescription->nodeId = RefTypeId_HasDescription;
+	hasdescription->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasdescription->browseName, "HasDescription");
+	UA_LOCALIZEDTEXT_STATIC(hasdescription->displayName, "HasDescription");
+	UA_LOCALIZEDTEXT_STATIC(hasdescription->description, "HasDescription");
+	hasdescription->isAbstract = UA_FALSE;
+	hasdescription->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasdescription->inverseName, "DescriptionOf");
+	ADDINVERSEREFERENCE(hasdescription, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasdescription, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hastypedefinition;
+	UA_ReferenceTypeNode_new(&hastypedefinition);
+	hastypedefinition->nodeId = RefTypeId_HasTypeDefinition;
+	hastypedefinition->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hastypedefinition->browseName, "HasTypeDefinition");
+	UA_LOCALIZEDTEXT_STATIC(hastypedefinition->displayName, "HasTypeDefinition");
+	UA_LOCALIZEDTEXT_STATIC(hastypedefinition->description, "HasTypeDefinition");
+	hastypedefinition->isAbstract = UA_FALSE;
+	hastypedefinition->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hastypedefinition->inverseName, "TypeDefinitionOf");
+	ADDINVERSEREFERENCE(hastypedefinition, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&hastypedefinition, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *generatesevent;
+	UA_ReferenceTypeNode_new(&generatesevent);
+	generatesevent->nodeId = RefTypeId_GeneratesEvent;
+	generatesevent->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(generatesevent->browseName, "GeneratesEvent");
+	UA_LOCALIZEDTEXT_STATIC(generatesevent->displayName, "GeneratesEvent");
+	UA_LOCALIZEDTEXT_STATIC(generatesevent->description, "GeneratesEvent");
+	generatesevent->isAbstract = UA_FALSE;
+	generatesevent->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(generatesevent->inverseName, "GeneratedBy");
+	ADDINVERSEREFERENCE(generatesevent, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&generatesevent, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *aggregates;
+	UA_ReferenceTypeNode_new(&aggregates);
+	aggregates->nodeId = RefTypeId_Aggregates;
+	aggregates->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(aggregates->browseName, "Aggregates");
+	UA_LOCALIZEDTEXT_STATIC(aggregates->displayName, "Aggregates");
+	UA_LOCALIZEDTEXT_STATIC(aggregates->description, "Aggregates");
+	aggregates->isAbstract = UA_TRUE;
+	aggregates->symmetric = UA_FALSE;
+	ADDINVERSEREFERENCE(aggregates, RefTypeId_HasSubtype, RefTypeId_HasChild);
+	UA_Namespace_insert(ns0,(UA_Node**)&aggregates, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hassubtype;
+	UA_ReferenceTypeNode_new(&hassubtype);
+	hassubtype->nodeId = RefTypeId_HasSubtype;
+	hassubtype->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hassubtype->browseName, "HasSubtype");
+	UA_LOCALIZEDTEXT_STATIC(hassubtype->displayName, "HasSubtype");
+	UA_LOCALIZEDTEXT_STATIC(hassubtype->description, "HasSubtype");
+	hassubtype->isAbstract = UA_FALSE;
+	hassubtype->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hassubtype->inverseName, "SubtypeOf");
+	ADDINVERSEREFERENCE(hassubtype, RefTypeId_HasSubtype, RefTypeId_HasChild);
+	UA_Namespace_insert(ns0,(UA_Node**)&hassubtype, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasproperty;
+	UA_ReferenceTypeNode_new(&hasproperty);
+	hasproperty->nodeId = RefTypeId_HasProperty;
+	hasproperty->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasproperty->browseName, "HasProperty");
+	UA_LOCALIZEDTEXT_STATIC(hasproperty->displayName, "HasProperty");
+	UA_LOCALIZEDTEXT_STATIC(hasproperty->description, "HasProperty");
+	hasproperty->isAbstract = UA_FALSE;
+	hasproperty->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasproperty->inverseName, "PropertyOf");
+	ADDINVERSEREFERENCE(hasproperty, RefTypeId_HasSubtype, RefTypeId_Aggregates);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasproperty, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hascomponent;
+	UA_ReferenceTypeNode_new(&hascomponent);
+	hascomponent->nodeId = RefTypeId_HasComponent;
+	hascomponent->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hascomponent->browseName, "HasComponent");
+	UA_LOCALIZEDTEXT_STATIC(hascomponent->displayName, "HasComponent");
+	UA_LOCALIZEDTEXT_STATIC(hascomponent->description, "HasComponent");
+	hascomponent->isAbstract = UA_FALSE;
+	hascomponent->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hascomponent->inverseName, "ComponentOf");
+	ADDINVERSEREFERENCE(hascomponent, RefTypeId_HasSubtype, RefTypeId_Aggregates);
+	UA_Namespace_insert(ns0,(UA_Node**)&hascomponent, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasnotifier;
+	UA_ReferenceTypeNode_new(&hasnotifier);
+	hasnotifier->nodeId = RefTypeId_HasNotifier;
+	hasnotifier->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasnotifier->browseName, "HasNotifier");
+	UA_LOCALIZEDTEXT_STATIC(hasnotifier->displayName, "HasNotifier");
+	UA_LOCALIZEDTEXT_STATIC(hasnotifier->description, "HasNotifier");
+	hasnotifier->isAbstract = UA_FALSE;
+	hasnotifier->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasnotifier->inverseName, "NotifierOf");
+	ADDINVERSEREFERENCE(hasnotifier, RefTypeId_HasSubtype, RefTypeId_HasEventSource);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasnotifier, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasorderedcomponent;
+	UA_ReferenceTypeNode_new(&hasorderedcomponent);
+	hasorderedcomponent->nodeId = RefTypeId_HasOrderedComponent;
+	hasorderedcomponent->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasorderedcomponent->browseName, "HasOrderedComponent");
+	UA_LOCALIZEDTEXT_STATIC(hasorderedcomponent->displayName, "HasOrderedComponent");
+	UA_LOCALIZEDTEXT_STATIC(hasorderedcomponent->description, "HasOrderedComponent");
+	hasorderedcomponent->isAbstract = UA_FALSE;
+	hasorderedcomponent->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasorderedcomponent->inverseName, "OrderedComponentOf");
+	ADDINVERSEREFERENCE(hasorderedcomponent, RefTypeId_HasSubtype, RefTypeId_HasComponent);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasorderedcomponent, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hasmodelparent;
+	UA_ReferenceTypeNode_new(&hasmodelparent);
+	hasmodelparent->nodeId = RefTypeId_HasModelParent;
+	hasmodelparent->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hasmodelparent->browseName, "HasModelParent");
+	UA_LOCALIZEDTEXT_STATIC(hasmodelparent->displayName, "HasModelParent");
+	UA_LOCALIZEDTEXT_STATIC(hasmodelparent->description, "HasModelParent");
+	hasmodelparent->isAbstract = UA_FALSE;
+	hasmodelparent->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hasmodelparent->inverseName, "ModelParentOf");
+	ADDINVERSEREFERENCE(hasmodelparent, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&hasmodelparent, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *fromstate;
+	UA_ReferenceTypeNode_new(&fromstate);
+	fromstate->nodeId = RefTypeId_FromState;
+	fromstate->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(fromstate->browseName, "FromState");
+	UA_LOCALIZEDTEXT_STATIC(fromstate->displayName, "FromState");
+	UA_LOCALIZEDTEXT_STATIC(fromstate->description, "FromState");
+	fromstate->isAbstract = UA_FALSE;
+	fromstate->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(fromstate->inverseName, "ToTransition");
+	ADDINVERSEREFERENCE(fromstate, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&fromstate, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *tostate;
+	UA_ReferenceTypeNode_new(&tostate);
+	tostate->nodeId = RefTypeId_ToState;
+	tostate->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(tostate->browseName, "ToState");
+	UA_LOCALIZEDTEXT_STATIC(tostate->displayName, "ToState");
+	UA_LOCALIZEDTEXT_STATIC(tostate->description, "ToState");
+	tostate->isAbstract = UA_FALSE;
+	tostate->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(tostate->inverseName, "FromTransition");
+	ADDINVERSEREFERENCE(tostate, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&tostate, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hascause;
+	UA_ReferenceTypeNode_new(&hascause);
+	hascause->nodeId = RefTypeId_HasCause;
+	hascause->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hascause->browseName, "HasCause");
+	UA_LOCALIZEDTEXT_STATIC(hascause->displayName, "HasCause");
+	UA_LOCALIZEDTEXT_STATIC(hascause->description, "HasCause");
+	hascause->isAbstract = UA_FALSE;
+	hascause->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hascause->inverseName, "MayBeCausedBy");
+	ADDINVERSEREFERENCE(hascause, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&hascause, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *haseffect;
+	UA_ReferenceTypeNode_new(&haseffect);
+	haseffect->nodeId = RefTypeId_HasEffect;
+	haseffect->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(haseffect->browseName, "HasEffect");
+	UA_LOCALIZEDTEXT_STATIC(haseffect->displayName, "HasEffect");
+	UA_LOCALIZEDTEXT_STATIC(haseffect->description, "HasEffect");
+	haseffect->isAbstract = UA_FALSE;
+	haseffect->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(haseffect->inverseName, "MayBeEffectedBy");
+	ADDINVERSEREFERENCE(haseffect, RefTypeId_HasSubtype, RefTypeId_NonHierarchicalReferences);
+	UA_Namespace_insert(ns0,(UA_Node**)&haseffect, UA_NAMESPACE_INSERT_UNIQUE);
+
+	UA_ReferenceTypeNode *hashistoricalconfiguration;
+	UA_ReferenceTypeNode_new(&hashistoricalconfiguration);
+	hashistoricalconfiguration->nodeId = RefTypeId_HasHistoricalConfiguration;
+	hashistoricalconfiguration->nodeClass = UA_NODECLASS_REFERENCETYPE;
+	UA_QUALIFIEDNAME_STATIC(hashistoricalconfiguration->browseName, "HasHistoricalConfiguration");
+	UA_LOCALIZEDTEXT_STATIC(hashistoricalconfiguration->displayName, "HasHistoricalConfiguration");
+	UA_LOCALIZEDTEXT_STATIC(hashistoricalconfiguration->description, "HasHistoricalConfiguration");
+	hashistoricalconfiguration->isAbstract = UA_FALSE;
+	hashistoricalconfiguration->symmetric = UA_FALSE;
+	UA_LOCALIZEDTEXT_STATIC(hashistoricalconfiguration->inverseName, "HistoricalConfigurationOf");
+	ADDINVERSEREFERENCE(hashistoricalconfiguration, RefTypeId_HasSubtype, RefTypeId_Aggregates);
+	UA_Namespace_insert(ns0,(UA_Node**)&hashistoricalconfiguration, UA_NAMESPACE_INSERT_UNIQUE);
+
+
+	// ObjectTypes (Ids only)
+	UA_ExpandedNodeId ObjTypeId_FolderType; NS0EXPANDEDNODEID(ObjTypeId_FolderType, 61);
+
+	// Objects (Ids only)
+	UA_ExpandedNodeId ObjId_ObjectsFolder; NS0EXPANDEDNODEID(ObjId_ObjectsFolder, 85);
+	UA_ExpandedNodeId ObjId_TypesFolder; NS0EXPANDEDNODEID(ObjId_TypesFolder, 86);
+	UA_ExpandedNodeId ObjId_ViewsFolder; NS0EXPANDEDNODEID(ObjId_ViewsFolder, 87);
+	UA_ExpandedNodeId ObjId_Server; NS0EXPANDEDNODEID(ObjId_Server, 2253);
+	UA_ExpandedNodeId ObjId_ServerArray; NS0EXPANDEDNODEID(ObjId_ServerArray, 2254);
+	UA_ExpandedNodeId ObjId_NamespaceArray; NS0EXPANDEDNODEID(ObjId_NamespaceArray, 2255);
+	UA_ExpandedNodeId ObjId_ServerStatus; NS0EXPANDEDNODEID(ObjId_ServerStatus, 2256);
+	UA_ExpandedNodeId ObjId_ServerCapabilities; NS0EXPANDEDNODEID(ObjId_ServerCapabilities, 2268);
+	UA_ExpandedNodeId ObjId_State; NS0EXPANDEDNODEID(ObjId_State, 2259);
+
+	// FolderType
+	UA_ObjectNode *folderType;
+	UA_ObjectNode_new(&folderType);
+	folderType->nodeId = NS0NODEID(61);
+	folderType->nodeClass = UA_NODECLASS_OBJECTTYPE; // I should not have to set this manually
+	UA_QUALIFIEDNAME_STATIC(folderType->browseName, "FolderType");
+	UA_LOCALIZEDTEXT_STATIC(folderType->displayName, "FolderType");
+	UA_LOCALIZEDTEXT_STATIC(folderType->description, "FolderType");
+	UA_Namespace_insert(ns0,(UA_Node**)&folderType, UA_NAMESPACE_INSERT_UNIQUE);
+
+#define ADDREFERENCE(NODE, REFTYPE, INVERSE, TARGET_NODEID) \
+	static struct UA_ReferenceNode NODE##REFTYPE##TARGET_NODEID; \
+	UA_ReferenceNode_init(&NODE##REFTYPE##TARGET_NODEID); \
+	NODE##REFTYPE##TARGET_NODEID.referenceTypeId = REFTYPE; \
+	NODE##REFTYPE##TARGET_NODEID.isInverse = INVERSE; \
+	NODE##REFTYPE##TARGET_NODEID.targetId = TARGET_NODEID; \
+	AddReference((UA_Node*)NODE, &NODE##REFTYPE##TARGET_NODEID, ns0)
+
+	// Root
+	UA_ObjectNode *root;
+	UA_ObjectNode_new(&root);
+	root->nodeId = NS0NODEID(84);
+	root->nodeClass = UA_NODECLASS_OBJECT; // I should not have to set this manually
+	UA_QUALIFIEDNAME_STATIC(root->browseName, "Root");
+	UA_LOCALIZEDTEXT_STATIC(root->displayName, "Root");
+	UA_LOCALIZEDTEXT_STATIC(root->description, "Root");
+	ADDREFERENCE(root, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
+	ADDREFERENCE(root, RefTypeId_Organizes, UA_FALSE, ObjId_ObjectsFolder);
+	ADDREFERENCE(root, RefTypeId_Organizes, UA_FALSE, ObjId_TypesFolder);
+	ADDREFERENCE(root, RefTypeId_Organizes, UA_FALSE, ObjId_ViewsFolder);
+	/* root becomes a managed node. we need to release it at the end.*/
+	UA_Namespace_insert(ns0,(UA_Node**)&root, UA_NAMESPACE_INSERT_UNIQUE | UA_NAMESPACE_INSERT_GETMANAGED);
+
+	// Objects
+	UA_ObjectNode *objects;
+	UA_ObjectNode_new(&objects);
+	objects->nodeId = ObjId_ObjectsFolder.nodeId;
+	objects->nodeClass = UA_NODECLASS_OBJECT;
+	UA_QUALIFIEDNAME_STATIC(objects->browseName, "Objects");
+	UA_LOCALIZEDTEXT_STATIC(objects->displayName, "Objects");
+	UA_LOCALIZEDTEXT_STATIC(objects->description, "Objects");
+	ADDREFERENCE(objects, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
+	ADDREFERENCE(objects, RefTypeId_Organizes, UA_FALSE, ObjId_Server);
+	UA_Namespace_insert(ns0,(UA_Node**)&objects, UA_NAMESPACE_INSERT_UNIQUE);
+
+	// Types
+	UA_ObjectNode *types;
+	UA_ObjectNode_new(&types);
+	types->nodeId = ObjId_TypesFolder.nodeId;
+	types->nodeClass = UA_NODECLASS_OBJECT;
+	UA_QUALIFIEDNAME_STATIC(types->browseName, "Types");
+	UA_LOCALIZEDTEXT_STATIC(types->displayName, "Types");
+	UA_LOCALIZEDTEXT_STATIC(types->description, "Types");
+	ADDREFERENCE(types, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
+	UA_Namespace_insert(ns0,(UA_Node**)&types, UA_NAMESPACE_INSERT_UNIQUE);
+
+	// Views
+	UA_ObjectNode *views;
+	UA_ObjectNode_new(&views);
+	views->nodeId = ObjId_ViewsFolder.nodeId;
+	views->nodeClass = UA_NODECLASS_OBJECT;
+	UA_QUALIFIEDNAME_STATIC(views->browseName, "Views");
+	UA_LOCALIZEDTEXT_STATIC(views->displayName, "Views");
+	UA_LOCALIZEDTEXT_STATIC(views->description, "Views");
+	ADDREFERENCE(views, RefTypeId_HasTypeDefinition, UA_FALSE, ObjTypeId_FolderType);
+	UA_Namespace_insert(ns0,(UA_Node**)&views, UA_NAMESPACE_INSERT_UNIQUE);
+
+	// Server
+	UA_ObjectNode *servernode;
+	UA_ObjectNode_new(&servernode);
+	servernode->nodeId = ObjId_Server.nodeId;
+	servernode->nodeClass = UA_NODECLASS_OBJECT;
+	UA_QUALIFIEDNAME_STATIC(servernode->browseName, "Server");
+	UA_LOCALIZEDTEXT_STATIC(servernode->displayName, "Server");
+	UA_LOCALIZEDTEXT_STATIC(servernode->description, "Server");
+	ADDREFERENCE(servernode, RefTypeId_HasComponent, UA_FALSE, ObjId_ServerCapabilities);
+	ADDREFERENCE(servernode, RefTypeId_HasComponent, UA_FALSE, ObjId_NamespaceArray);
+	ADDREFERENCE(servernode, RefTypeId_HasProperty, UA_FALSE, ObjId_ServerStatus);
+	ADDREFERENCE(servernode, RefTypeId_HasProperty, UA_FALSE, ObjId_ServerArray);
+	UA_Namespace_insert(ns0,(UA_Node**)&servernode, UA_NAMESPACE_INSERT_UNIQUE);
+
+	// NamespaceArray
+	UA_VariableNode *namespaceArray;
+	UA_VariableNode_new(&namespaceArray);
+	namespaceArray->nodeId = ObjId_NamespaceArray.nodeId;
+	namespaceArray->nodeClass = UA_NODECLASS_VARIABLE; //FIXME: this should go into _new?
+	UA_QUALIFIEDNAME_STATIC(namespaceArray->browseName, "NamespaceArray");
+	UA_LOCALIZEDTEXT_STATIC(namespaceArray->displayName, "NamespaceArray");
+	UA_LOCALIZEDTEXT_STATIC(namespaceArray->description, "NamespaceArray");
+	UA_Array_new((void**)&namespaceArray->value.data, 2, &UA_.types[UA_STRING]);
+	namespaceArray->value.vt = &UA_.types[UA_STRING];
+	namespaceArray->value.arrayLength = 2;
+	UA_String_copycstring("http://opcfoundation.org/UA/",&((UA_String *)((namespaceArray->value).data))[0]);
+	UA_String_copycstring("http://localhost:16664/open62541/",&((UA_String *)(((namespaceArray)->value).data))[1]);
+	namespaceArray->arrayDimensionsSize = 1;
+	UA_UInt32* dimensions = UA_NULL;
+	UA_alloc((void**)&dimensions, sizeof(UA_UInt32));
+	*dimensions = 2;
+	namespaceArray->arrayDimensions = dimensions;
+	namespaceArray->dataType = NS0NODEID(UA_STRING_NS0);
+	namespaceArray->valueRank = 1;
+	namespaceArray->minimumSamplingInterval = 1.0;
+	namespaceArray->historizing = UA_FALSE;
+	UA_Namespace_insert(ns0,(UA_Node**)&namespaceArray, UA_NAMESPACE_INSERT_UNIQUE);
+
+	// ServerStatus
+	UA_VariableNode *serverstatus;
+	UA_VariableNode_new(&serverstatus);
+	serverstatus->nodeId = ObjId_ServerStatus.nodeId;
+	serverstatus->nodeClass = UA_NODECLASS_VARIABLE;
+	UA_QUALIFIEDNAME_STATIC(serverstatus->browseName, "ServerStatus");
+	UA_LOCALIZEDTEXT_STATIC(serverstatus->displayName, "ServerStatus");
+	UA_LOCALIZEDTEXT_STATIC(serverstatus->description, "ServerStatus");
+	UA_ServerStatusDataType *status;
+	UA_ServerStatusDataType_new(&status);
+	status->startTime = UA_DateTime_now();
+	status->currentTime = UA_DateTime_now();
+	status->state = UA_SERVERSTATE_RUNNING;
+	UA_STRING_STATIC(status->buildInfo.productUri, "open62541.org");
+	UA_STRING_STATIC(status->buildInfo.manufacturerName, "open62541");
+	UA_STRING_STATIC(status->buildInfo.productName, "open62541");
+	UA_STRING_STATIC(status->buildInfo.softwareVersion, "0.0");
+	UA_STRING_STATIC(status->buildInfo.buildNumber, "0.0");
+	status->buildInfo.buildDate = UA_DateTime_now();
+	status->secondsTillShutdown = 99999999;
+	UA_LOCALIZEDTEXT_STATIC(status->shutdownReason, "because");
+	serverstatus->value.vt = &UA_.types[UA_SERVERSTATUSDATATYPE]; // gets encoded as an extensionobject
+	serverstatus->value.arrayLength = 1;
+	serverstatus->value.data = status;
+	UA_Namespace_insert(ns0,(UA_Node**)&serverstatus, UA_NAMESPACE_INSERT_UNIQUE);
+
+	// State (Component of ServerStatus)
+	UA_VariableNode *state;
+	UA_VariableNode_new(&state);
+	state->nodeId = ObjId_State.nodeId;
+	state->nodeClass = UA_NODECLASS_VARIABLE;
+	UA_QUALIFIEDNAME_STATIC(state->browseName, "State");
+	UA_LOCALIZEDTEXT_STATIC(state->displayName, "State");
+	UA_LOCALIZEDTEXT_STATIC(state->description, "State");
+	state->value.vt = &UA_borrowed_.types[UA_SERVERSTATE];
+	state->value.arrayDimensionsLength = 1; // added to ensure encoding in readreponse
+	state->value.arrayLength = 1;
+	state->value.data = &status->state; // points into the other object.
+	UA_Namespace_insert(ns0,(UA_Node**)&state, UA_NAMESPACE_INSERT_UNIQUE);
+
+	//TODO: free(namespaceArray->value.data) later or forget it
+
+
+	/* UA_VariableNode* v = (UA_VariableNode*)np; */
+	/* UA_Array_new((void**)&v->value.data, 2, &UA_.types[UA_STRING]); */
+	/* v->value.vt = &UA_.types[UA_STRING]; */
+	/* v->value.arrayLength = 2; */
+	/* UA_String_copycstring("http://opcfoundation.org/UA/",&((UA_String *)((v->value).data))[0]); */
+	/* UA_String_copycstring("http://localhost:16664/open62541/",&((UA_String *)(((v)->value).data))[1]); */
+	/* v->dataType.identifierType = UA_NODEIDTYPE_FOURBYTE; */
+	/* v->dataType.identifier.numeric = UA_STRING_NS0; */
+	/* v->valueRank = 1; */
+	/* v->minimumSamplingInterval = 1.0; */
+	/* v->historizing = UA_FALSE; */
+	/* UA_Namespace_insert(ns0,np); */
+
+	/*******************/
+	/* Namespace local */
+	/*******************/
+	
+	UA_Namespace_releaseManagedNode((const UA_Node*)root);
+
+#if defined(DEBUG) && defined(VERBOSE)
+	uint32_t i;
+	for (i=0;i < ns0->size;i++) {
+		if (ns0->entries[i].node != UA_NULL) {
+			printf("application_init - entries[%d]={",i);
+			UA_Node_print(ns0->entries[i].node, stdout);
+			printf("}\n");
+		}
+	}
+#endif
+}

+ 26 - 11
src/server/ua_server.h

@@ -1,19 +1,34 @@
 #ifndef UA_SERVER_H_
 #define UA_SERVER_H_
 
-#include "ua_application.h"
+#include "ua_types.h"
+#include "ua_types_generated.h"
+#include "ua_namespace.h"
+#include "ua_securechannel_manager.h"
+#include "ua_session_manager.h"
+#include "util/ua_log.h"
+
+/**
+   @defgroup server
+*/
+
+typedef struct UA_IndexedNamespace {
+	UA_UInt32 namespaceIndex;
+	UA_Namespace *namespace;
+} UA_IndexedNamespace;
 
-struct UA_Server;
 typedef struct UA_Server {
-	// SL_ChannelManager *cm;
-	// UA_SessionManager sm;
-	UA_UInt32 applicationsSize;
-	UA_Application *applications;
-	/** Every thread needs to init its logger variable. The server-object stores a
-		function pointer and logger configuration for that purpose. */
-	void (*logger_init)(void *config);
-	/** Configuration for the logger */
-	void *logger_configuration;
+	UA_ApplicationDescription description;
+	UA_SecureChannelManager *secureChannelManager;
+	UA_SessionManager *sessionManager;
+	UA_UInt32 namespacesSize;
+	UA_IndexedNamespace *namespaces;
+	UA_Logger logger;
 } UA_Server;
 
+void UA_Server_init(UA_Server *server, UA_String *endpointUrl);
+UA_Int32 UA_Server_deleteMembers(UA_Server *server);
+UA_Int32 UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
+										const UA_ByteString* msg);
+
 #endif /* UA_SERVER_H_ */

+ 322 - 0
src/server/ua_server_binary.c

@@ -0,0 +1,322 @@
+#include "ua_server.h"
+#include "ua_services.h"
+#include "ua_statuscodes.h"
+
+static void processHello(UA_Connection *connection, const UA_ByteString* msg,
+						 UA_UInt32* pos) {
+	UA_UInt32 tmpPos = 0;
+	UA_OPCUATcpHelloMessage helloMessage;
+
+	if (connection->state != UA_CONNECTION_OPENING) {
+		// multiple HEL are not allowed
+		connection->close(connection->callbackHandle);
+		return;
+	}
+
+	UA_OPCUATcpHelloMessage_decodeBinary(msg,pos,&helloMessage);
+	connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount;
+	connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize;
+	connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
+	connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
+	connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
+
+	connection->state = UA_CONNECTION_ESTABLISHED;
+
+	// build acknowledge response
+	UA_OPCUATcpMessageHeader ackHeader;
+	ackHeader.messageType = UA_MESSAGETYPE_ACK;
+	ackHeader.isFinal = 'F';
+
+	UA_OPCUATcpAcknowledgeMessage ackMessage;
+	ackMessage.protocolVersion = connection->localConf.protocolVersion;
+	ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
+	ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
+	ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
+	ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
+
+	ackHeader.messageSize = UA_OPCUATcpAcknowledgeMessage_calcSizeBinary(&ackMessage) +
+		UA_OPCUATcpMessageHeader_calcSizeBinary(&ackHeader);
+	UA_ByteString *ack_msg;
+	UA_alloc((void **)&ack_msg, sizeof(UA_ByteString));
+	UA_ByteString_newMembers(ack_msg, ackHeader.messageSize);
+	tmpPos = 0;
+	UA_OPCUATcpMessageHeader_encodeBinary(&ackHeader,ack_msg,&tmpPos);
+	UA_OPCUATcpAcknowledgeMessage_encodeBinary(&ackMessage, ack_msg,&tmpPos);
+	UA_ByteStringArray answer_buf = {.stringsSize = 1, .strings = ack_msg};
+	connection->write(connection->callbackHandle, &answer_buf);
+	UA_ByteString_delete(ack_msg);
+}
+
+static void processOpen(UA_Connection *connection, UA_Server *server,
+					   const UA_ByteString* msg, UA_UInt32* pos) {
+	UA_UInt32 secureChannelId;
+	if (connection->state != UA_CONNECTION_ESTABLISHED) {
+		if(connection->state == UA_CONNECTION_OPENING)
+			connection->close(connection->callbackHandle);
+		return;
+	}
+
+	UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
+	// needs asym encoding for returning
+	// call the service!!!!
+	/* if(connection->channel != UA_NULL) { */
+	/* 	//create new channel */
+	/* 	SL_Channel *newChannel; */
+	/* 	retval |= SL_ChannelManager_generateChannel(cm, ) */
+	/* 	retval |= SL_ProcessOpenChannel(newChannel, server, msg, pos); */
+	/* 	retval |= SL_Channel_bind(newChannel, connection); */
+	/* 	return retval; */
+	/* } */
+	/* // channel already exists, renew token? */
+	/* retval |= SL_ProcessOpenChannel(channel, server, msg, pos); */
+	/* return retval; */
+}
+
+static void init_response_header(UA_RequestHeader const * p, UA_ResponseHeader * r) {
+	r->requestHandle = p->requestHandle;
+	r->serviceResult = UA_STATUSCODE_GOOD;
+	r->stringTableSize = 0;
+	r->timestamp = UA_DateTime_now();
+}
+
+#define CHECK_PROCESS(CODE, CLEANUP)								\
+	do {															\
+	if(CODE != UA_SUCCESS) {										\
+	    CLEANUP;                                                    \
+        goto clean_up;												\
+    } } while(0)
+
+#define INVOKE_SERVICE(TYPE) do {										\
+	UA_##TYPE##Request p;											\
+	UA_##TYPE##Response r;											\
+	UA_Session *session = UA_NULL;									\
+	CHECK_PROCESS(UA_##TYPE##Request_decodeBinary(msg, pos, &p),;);		\
+	UA_##TYPE##Response_init(&r);										\
+		init_response_header(&p.requestHeader, &r.responseHeader);		\
+	UA_SessionManager_getSessionByToken(server->sessionManager, &p.requestHeader.authenticationToken, \
+										&session);						\
+	DBG_VERBOSE(printf("Invoke Service: %s\n", #TYPE));					\
+	Service_##TYPE(server, session, &p, &r);							\
+	DBG_VERBOSE(printf("Finished Service: %s\n", #TYPE));				\
+	UA_ByteString_newMembers(&responseBuf.strings[1], UA_##TYPE##Response_calcSizeBinary(&r)); \
+	UA_##TYPE##Response_encodeBinary(&r, &responseBuf.strings[1], &sendOffset);	\
+	UA_##TYPE##Request_deleteMembers(&p);								\
+	UA_##TYPE##Response_deleteMembers(&r);								\
+	responseType = requestType.nodeId.identifier.numeric + 3;			\
+	} while(0)
+
+static void processMessage(UA_Connection *connection, UA_Server *server,
+						   const UA_ByteString* msg, UA_UInt32* pos) {
+	// 1) Read in the securechannel
+	UA_UInt32 secureChannelId;
+	UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
+	UA_SecureChannel *channel;
+ 	UA_SecureChannelManager_get(server->secureChannelManager, secureChannelId, &channel);
+
+	// 2) Read the security header
+	UA_UInt32 tokenId;
+	UA_UInt32_decodeBinary(msg, pos, &tokenId);
+	UA_SequenceHeader sequenceHeader;
+	CHECK_PROCESS(UA_SequenceHeader_decodeBinary(msg, pos, &sequenceHeader),;);
+	//UA_SecureChannel_checkSequenceNumber(channel,sequenceHeader.sequenceNumber);
+	//UA_SecureChannel_checkRequestId(channel,sequenceHeader.requestId);
+	
+	// 3) Read the nodeid of the request
+	UA_ExpandedNodeId requestType;
+	CHECK_PROCESS(UA_ExpandedNodeId_decodeBinary(msg, pos, &requestType),;);
+	if(requestType.nodeId.identifierType != UA_NODEIDTYPE_NUMERIC)
+		goto close_connection;
+
+	// 4) process the request
+	UA_ByteStringArray responseBuf;
+	UA_ByteStringArray_init(&responseBuf, 2);
+
+	UA_UInt32 responseType;
+
+	//subtract 2 for binary encoding
+	UA_UInt32 sendOffset = 0;
+	switch(requestType.nodeId.identifier.numeric - 2) {
+	case UA_GETENDPOINTSREQUEST_NS0: {
+		UA_GetEndpointsRequest p;
+		UA_GetEndpointsResponse r;
+		CHECK_PROCESS(UA_GetEndpointsRequest_decodeBinary(msg, pos, &p),;);
+		UA_GetEndpointsResponse_init(&r);
+		init_response_header(&p.requestHeader, &r.responseHeader);
+		Service_GetEndpoints(server, &p, &r);
+		UA_ByteString_newMembers(&responseBuf.strings[1],
+								 UA_GetEndpointsResponse_calcSizeBinary(&r));
+		UA_GetEndpointsResponse_encodeBinary(&r, &responseBuf.strings[1], &sendOffset);
+		UA_GetEndpointsRequest_deleteMembers(&p);
+		UA_GetEndpointsResponse_deleteMembers(&r);
+		responseType = requestType.nodeId.identifier.numeric + 3;
+		break;
+	}
+		
+	case UA_CREATESESSIONREQUEST_NS0: {
+		UA_CreateSessionRequest p;
+		UA_CreateSessionResponse r;
+		CHECK_PROCESS(UA_CreateSessionRequest_decodeBinary(msg, pos, &p),;);
+		UA_CreateSessionResponse_init(&r);
+		init_response_header(&p.requestHeader, &r.responseHeader);
+		Service_CreateSession(server,channel,  &p, &r);
+		UA_ByteString_newMembers(&responseBuf.strings[1],
+								 UA_CreateSessionResponse_calcSizeBinary(&r));
+		UA_CreateSessionResponse_encodeBinary(&r, &responseBuf.strings[1], &sendOffset);
+		UA_CreateSessionRequest_deleteMembers(&p);
+		UA_CreateSessionResponse_deleteMembers(&r);
+		responseType = requestType.nodeId.identifier.numeric + 3;
+		break;
+	}
+
+	case UA_ACTIVATESESSIONREQUEST_NS0:
+		INVOKE_SERVICE(ActivateSession);
+		break;
+
+	case UA_READREQUEST_NS0:
+		INVOKE_SERVICE(Read);
+		break;
+
+	case UA_WRITEREQUEST_NS0:
+		INVOKE_SERVICE(Write);
+		break;
+
+	case UA_BROWSEREQUEST_NS0:
+		INVOKE_SERVICE(Browse);
+		break;
+
+	case UA_CREATESUBSCRIPTIONREQUEST_NS0:
+		INVOKE_SERVICE(CreateSubscription);
+		break;
+
+	case UA_TRANSLATEBROWSEPATHSTONODEIDSREQUEST_NS0:
+		INVOKE_SERVICE(TranslateBrowsePathsToNodeIds);
+		break;
+		
+	case UA_PUBLISHREQUEST_NS0:
+		INVOKE_SERVICE(Publish);
+		break;
+
+	case UA_CREATEMONITOREDITEMSREQUEST_NS0:
+		INVOKE_SERVICE(CreateMonitoredItems);
+		break;
+
+	case UA_SETPUBLISHINGMODEREQUEST_NS0:
+		INVOKE_SERVICE(SetPublishingMode);
+		break;
+		
+	default: {
+		printf("SL_processMessage - unknown request, namespace=%d, request=%d\n",
+			   requestType.nodeId.namespaceIndex, requestType.nodeId.identifier.numeric);
+		UA_RequestHeader p;
+		UA_ResponseHeader r;
+		CHECK_PROCESS(UA_RequestHeader_decodeBinary(msg, pos, &p),;);
+		UA_ResponseHeader_init(&r);
+		r.requestHandle = p.requestHandle;
+		r.serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
+		UA_ByteString_newMembers(&responseBuf.strings[1], UA_ResponseHeader_calcSizeBinary(&r));
+		UA_ResponseHeader_encodeBinary(&r, &responseBuf.strings[1], &sendOffset);
+		UA_RequestHeader_deleteMembers(&p);
+		UA_ResponseHeader_deleteMembers(&r);
+		responseType = UA_RESPONSEHEADER_NS0 + 2;
+	}
+	}
+
+	// 5) Build the header
+#define SIZE_SECURECHANNEL_HEADER 12
+#define SIZE_SEQHEADER_HEADER 8
+	UA_NodeId response_nodeid = {.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC,
+								 .identifier.numeric = responseType}; // add 2 for binary encoding
+
+	UA_ByteString_newMembers(&responseBuf.strings[0],
+							 8 + 16 + // normal header + 4*32bit secure channel information
+							 UA_NodeId_calcSizeBinary(&response_nodeid));
+
+	// sizePadding = 0;
+	// sizeSignature = 0;
+	UA_ByteString *header = &responseBuf.strings[0];
+
+	// secure conversation message header
+	header->data[0] = 'M';
+	header->data[1] = 'S';
+	header->data[2] = 'G';
+	header->data[3] = 'F';
+	UA_UInt32 rpos = 4;
+
+	UA_Int32 packetSize = header->length + responseBuf.strings[0].length;
+	UA_Int32_encodeBinary(&packetSize, header, &rpos);
+	UA_UInt32_encodeBinary(&channel->securityToken.channelId, header, &rpos);
+
+	// algorithm security header
+	UA_UInt32_encodeBinary(&channel->securityToken.tokenId, header,&rpos);
+
+	// encode sequence header
+	UA_UInt32_encodeBinary(&channel->sequenceNumber, header, &rpos);
+	UA_UInt32_encodeBinary(&channel->requestId, header,&rpos);
+
+	// add payload type
+	UA_NodeId_encodeBinary(&response_nodeid, header,&rpos);
+
+	// sign data
+
+	// encrypt data
+
+	// 6) Send it over the wire.
+	connection->write(connection->callbackHandle, &responseBuf);
+
+ clean_up:
+	UA_ExpandedNodeId_deleteMembers(&requestType);
+	UA_ByteStringArray_deleteMembers(&responseBuf);
+	return;
+
+ close_connection:
+	// make sure allocated data has been freed
+	connection->state = UA_CONNECTION_CLOSING;
+	connection->close(connection->callbackHandle);
+	return;
+}
+
+static void processClose(UA_Connection *connection, UA_Server *server,
+						const UA_ByteString* msg, UA_UInt32* pos) {
+	// just read in the sequenceheader
+
+}
+
+UA_Int32 UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
+										const UA_ByteString* msg) {
+	UA_Int32 retval = UA_SUCCESS;
+	UA_UInt32 pos = 0;
+	UA_OPCUATcpMessageHeader tcpMessageHeader;
+	do {
+		retval = UA_OPCUATcpMessageHeader_decodeBinary(msg,&pos,&tcpMessageHeader);
+		if (retval == UA_SUCCESS) {
+			// none of the process-functions returns an error its all contained inside.
+			switch(tcpMessageHeader.messageType) {
+			case UA_MESSAGETYPE_HEL:
+				processHello(connection, msg, &pos);
+				break;
+			case UA_MESSAGETYPE_OPN:
+				processOpen(connection, server, msg, &pos);
+				break;
+			case UA_MESSAGETYPE_MSG:
+				// if this fails, the connection is closed (no break on the case)
+				if(connection->state == UA_CONNECTION_ESTABLISHED &&
+				   connection->channel != UA_NULL) {
+					processMessage(connection, server, msg, &pos);
+					break;
+				}
+			case UA_MESSAGETYPE_CLO:
+				connection->state = UA_CONNECTION_CLOSING;
+				processClose(connection, server, msg, &pos);
+				connection->close(connection->callbackHandle);
+				break;
+			}
+		} else {
+			printf("TL_Process - ERROR: decoding of header failed \n");
+			connection->state = UA_CONNECTION_CLOSING;
+			processClose(connection, server, msg, &pos);
+			connection->close(connection->callbackHandle);
+		}
+		UA_OPCUATcpMessageHeader_deleteMembers(&tcpMessageHeader);
+	} while(msg->length > (UA_Int32)pos);
+	return retval;
+}

+ 47 - 35
src/server/ua_services.h

@@ -1,18 +1,9 @@
-/**
- * @file ua_services.h
- *
- * @brief Defines the method signatures for all the standard defined services.
- */
-
 #ifndef UA_SERVICES_H_
 #define UA_SERVICES_H_
 
 #include "ua_types.h"
 #include "ua_types_generated.h"
 #include "ua_server.h"
-#include "ua_transport_binary_secure.h"
-#include "ua_session_manager.h"
-#include "ua_channel_manager.h"
 
 /**
  * @defgroup services Services
@@ -37,7 +28,9 @@
  * the configuration information required to establish a SecureChannel and a
  * Session.
  */
-UA_Int32 Service_GetEndpoints(SL_Channel *channel, const UA_GetEndpointsRequest* request, UA_GetEndpointsResponse *response);
+UA_Int32 Service_GetEndpoints(UA_Server *server,
+							  const UA_GetEndpointsRequest* request,
+							  UA_GetEndpointsResponse *response);
 // Service_RegisterServer
 /** @} */
 
@@ -51,17 +44,17 @@ UA_Int32 Service_GetEndpoints(SL_Channel *channel, const UA_GetEndpointsRequest*
  * @{
  */
 
-/**
- * @brief This Service is used to open or renew a SecureChannel that can be used
- * to ensure Confidentiality and Integrity for Message exchange during a
- * Session.
- */
-UA_Int32 Service_OpenSecureChannel(SL_Channel *channel, const UA_OpenSecureChannelRequest* request, UA_OpenSecureChannelResponse* response);
+/** @brief This Service is used to open or renew a SecureChannel that can be
+  used to ensure Confidentiality and Integrity for Message exchange during a
+  Session. */
+UA_Int32 Service_OpenSecureChannel(UA_Server *server, UA_Connection *connection,
+								   const UA_OpenSecureChannelRequest* request,
+								   UA_OpenSecureChannelResponse* response);
 
-/**
- * @brief This Service is used to terminate a SecureChannel.
- */
-UA_Int32 Service_CloseSecureChannel(SL_Channel *channel, const UA_CloseSecureChannelRequest *request, UA_CloseSecureChannelResponse *response);
+/** @brief This Service is used to terminate a SecureChannel. */
+UA_Int32 Service_CloseSecureChannel(UA_Server *server, UA_SecureChannel *channel,
+									const UA_CloseSecureChannelRequest *request,
+									UA_CloseSecureChannelResponse *response);
 /** @} */
 
 /**
@@ -80,7 +73,9 @@ UA_Int32 Service_CloseSecureChannel(SL_Channel *channel, const UA_CloseSecureCha
  * logs and in the Server’s address space. The second is the authenticationToken
  * which is used to associate an incoming request with a Session.
  */
-UA_Int32 Service_CreateSession(SL_Channel *channel, UA_Server *server, const UA_CreateSessionRequest *request, UA_CreateSessionResponse *response);
+UA_Int32 Service_CreateSession(UA_Server *server, UA_SecureChannel *channel,
+							   const UA_CreateSessionRequest *request,
+							   UA_CreateSessionResponse *response);
 
 /**
  * @brief This Service is used by the Client to submit its SoftwareCertificates
@@ -89,12 +84,16 @@ UA_Int32 Service_CreateSession(SL_Channel *channel, UA_Server *server, const UA_
  * Client before it issues any other Service request after CreateSession.
  * Failure to do so shall cause the Server to close the Session.
  */
-UA_Int32 Service_ActivateSession(SL_Channel *channel, UA_Session *session, const UA_ActivateSessionRequest *request, UA_ActivateSessionResponse *response);
+UA_Int32 Service_ActivateSession(UA_Server *server, UA_Session *session,
+								 const UA_ActivateSessionRequest *request,
+								 UA_ActivateSessionResponse *response);
 
 /**
  * @brief This Service is used to terminate a Session.
  */
-UA_Int32 Service_CloseSession(UA_Session *session, const UA_CloseSessionRequest *request, UA_CloseSessionResponse *response);
+UA_Int32 Service_CloseSession(UA_Server *server, UA_Session *session,
+							  const UA_CloseSessionRequest *request,
+							  UA_CloseSessionResponse *response);
 // Service_Cancel
 /** @} */
 
@@ -111,12 +110,15 @@ UA_Int32 Service_CloseSession(UA_Session *session, const UA_CloseSessionRequest
 /**
  * @brief This Service is used to add one or more Nodes into the AddressSpace hierarchy.
  */
-UA_Int32 Service_AddNodes(UA_Session *session, const UA_AddNodesRequest *request, UA_AddNodesResponse *response);
+UA_Int32 Service_AddNodes(UA_Server *server, UA_Session *session,
+						  const UA_AddNodesRequest *request, UA_AddNodesResponse *response);
 
 /**
  * @brief This Service is used to add one or more References to one or more Nodes
  */
-UA_Int32 Service_AddReferences(UA_Session *session, const UA_AddReferencesRequest *request, UA_AddReferencesResponse *response);
+UA_Int32 Service_AddReferences(UA_Server *server, UA_Session *session,
+							   const UA_AddReferencesRequest *request,
+							   UA_AddReferencesResponse *response);
 
 // Service_DeleteNodes
 // Service_DeleteReferences
@@ -136,12 +138,15 @@ UA_Int32 Service_AddReferences(UA_Session *session, const UA_AddReferencesReques
  * The browse can be further limited by the use of a View. This Browse Service
  * also supports a primitive filtering capability.
  */ 
-UA_Int32 Service_Browse(UA_Session *session, const UA_BrowseRequest *request, UA_BrowseResponse *response);
+UA_Int32 Service_Browse(UA_Server *server, UA_Session *session,
+						const UA_BrowseRequest *request, UA_BrowseResponse *response);
 
 /**
  * @brief This Service is used to translate textual node paths to their respective ids.
  */
-UA_Int32 Service_TranslateBrowsePathsToNodeIds(UA_Session *session, const UA_TranslateBrowsePathsToNodeIdsRequest *request, UA_TranslateBrowsePathsToNodeIdsResponse *response);
+UA_Int32 Service_TranslateBrowsePathsToNodeIds(UA_Server *server, UA_Session *session,
+											   const UA_TranslateBrowsePathsToNodeIdsRequest *request,
+											   UA_TranslateBrowsePathsToNodeIdsResponse *response);
 // Service_BrowseNext
 // Service_TranslateBrowsePathsToNodeIds
 // Service_RegisterNodes
@@ -184,7 +189,8 @@ UA_Int32 Service_TranslateBrowsePathsToNodeIds(UA_Session *session, const UA_Tra
  * values as a composite, to read individual elements or to read ranges of
  * elements of the composite.
  */
-UA_Int32 Service_Read(UA_Session *session, const UA_ReadRequest *request, UA_ReadResponse *response);
+UA_Int32 Service_Read(UA_Server *server, UA_Session *session, const UA_ReadRequest *request,
+					  UA_ReadResponse *response);
 // Service_HistoryRead
 /**
  * @brief This Service is used to write one or more Attributes of one or more
@@ -193,7 +199,8 @@ UA_Int32 Service_Read(UA_Session *session, const UA_ReadRequest *request, UA_Rea
  *  values as a composite, to write individual elements or to write ranges of
  *  elements of the composite.
  */
-UA_Int32 Service_Write(UA_Session *session, const UA_WriteRequest *request,UA_WriteResponse *response);
+UA_Int32 Service_Write(UA_Server *server, UA_Session *session, const UA_WriteRequest *request,
+					   UA_WriteResponse *response);
 // Service_HistoryUpdate
 /** @} */
 
@@ -225,7 +232,9 @@ a component of an Object.
  * triggered item links to be deleted, but has no effect on the MonitoredItems
  * referenced by the triggered items.
  */
-UA_Int32 Service_CreateMonitoredItems(UA_Session *session, const UA_CreateMonitoredItemsRequest *request, UA_CreateMonitoredItemsResponse *response);
+UA_Int32 Service_CreateMonitoredItems(UA_Server *server, UA_Session *session,
+									  const UA_CreateMonitoredItemsRequest *request,
+									  UA_CreateMonitoredItemsResponse *response);
 // Service_ModifyMonitoredItems
 // Service_SetMonitoringMode
 // Service_SetTriggering
@@ -240,15 +249,18 @@ UA_Int32 Service_CreateMonitoredItems(UA_Session *session, const UA_CreateMonito
  * @{
  */
 // Service_CreateSubscription
-UA_Int32 Service_CreateSubscription(UA_Session *session, const UA_CreateSubscriptionRequest *request,
-                                   UA_CreateSubscriptionResponse *response);
+UA_Int32 Service_CreateSubscription(UA_Server *server, UA_Session *session,
+									const UA_CreateSubscriptionRequest *request,
+									UA_CreateSubscriptionResponse *response);
 // Service_ModifySubscription
 // Service_SetPublishingMode
-UA_Int32 Service_SetPublishingMode(UA_Session *session, const UA_SetPublishingModeRequest *request,
+UA_Int32 Service_SetPublishingMode(UA_Server *server, UA_Session *session,
+								   const UA_SetPublishingModeRequest *request,
                                    UA_SetPublishingModeResponse *response);
 
-UA_Int32 Service_Publish(UA_Session *session, const UA_PublishRequest *request,
-                                   UA_PublishResponse *response);
+UA_Int32 Service_Publish(UA_Server *server, UA_Session *session,
+						 const UA_PublishRequest *request,
+						 UA_PublishResponse *response);
 
 // Service_Republish
 // Service_TransferSubscription

+ 33 - 31
src/server/ua_services_attribute.c

@@ -33,31 +33,31 @@ enum UA_AttributeId {
 		break;													   \
 	}															   \
 
-static UA_DataValue service_read_node(UA_Application *app, const UA_ReadValueId *id) {
+static UA_DataValue service_read_node(UA_Server *server, const UA_ReadValueId *id) {
 	UA_DataValue v;
 	UA_DataValue_init(&v);
 
-	DBG(printf("service_read_node - entered with ns=%d,id=%d,attr=%i\n", id->nodeId.namespaceIndex,
-	           id->nodeId.identifier.numeric, id->attributeId));
-	Namespace *ns = UA_indexedList_findValue(app->namespaces, id->nodeId.namespaceIndex);
+	UA_Namespace *ns = UA_NULL;
+	for(UA_UInt32 i=0; i<server->namespacesSize;i++) {
+		if(server->namespaces[i].namespaceIndex == id->nodeId.namespaceIndex) {
+			ns = server->namespaces[i].namespace;
+			break;
+		}
+	}
 
 	if(ns == UA_NULL) {
-		DBG_VERBOSE(printf("service_read_node - unknown namespace %d\n", id->nodeId.namespaceIndex));
 		v.encodingMask = UA_DATAVALUE_ENCODINGMASK_STATUSCODE;
 		v.status       = UA_STATUSCODE_BADNODEIDUNKNOWN;
 		return v;
 	}
 
 	UA_Node const *node = UA_NULL;
-	DBG_VERBOSE(UA_NodeId_printf("service_read_node - search for ", &(id->nodeId)));
-	UA_Int32 result = Namespace_get(ns, &(id->nodeId), &node);
+	UA_Int32 result = UA_Namespace_get(ns, &(id->nodeId), &node);
 	if(result != UA_SUCCESS || node == UA_NULL) {
 		v.encodingMask = UA_DATAVALUE_ENCODINGMASK_STATUSCODE;
 		v.status       = UA_STATUSCODE_BADNODEIDUNKNOWN;
 		return v;
 	}
-	DBG_VERBOSE(UA_NodeId_printf("service_read_node - found node=", &(node->nodeId)));
-
 	UA_Int32 retval = UA_SUCCESS;
 
 	switch(id->attributeId) {
@@ -213,27 +213,22 @@ static UA_DataValue service_read_node(UA_Application *app, const UA_ReadValueId
 		break;
 	}
 
-	Namespace_releaseManagedNode(node);
+	UA_Namespace_releaseManagedNode(node);
 
 	if(retval != UA_SUCCESS) {
 		v.encodingMask = UA_DATAVALUE_ENCODINGMASK_STATUSCODE;
 		v.status       = UA_STATUSCODE_BADNOTREADABLE;
 	}
 
+
 	return v;
 }
-UA_Int32 Service_Read(UA_Session *session, const UA_ReadRequest *request,
-                      UA_ReadResponse *response) {
-	UA_Application *application = UA_NULL;
+UA_Int32 Service_Read(UA_Server *server, UA_Session *session, const UA_ReadRequest *request,
+					  UA_ReadResponse *response) {
 	UA_Int32 readsize;
-	if(session == UA_NULL)
+	if(server == UA_NULL || session == UA_NULL)
 		return UA_ERROR;
 
-	UA_Session_getApplicationPointer(session,&application);
-
-	if( application == UA_NULL)
-		return UA_ERROR;    // TODO: Return error message
-
 	readsize = request->nodesToReadSize;
 	/* NothingTodo */
 	if(readsize <= 0) {
@@ -247,24 +242,32 @@ UA_Int32 Service_Read(UA_Session *session, const UA_ReadRequest *request,
 	for(UA_Int32 i = 0;i < readsize;i++) {
 		DBG_VERBOSE(printf("service_read - attributeId=%d\n", request->nodesToRead[i].attributeId));
 		DBG_VERBOSE(UA_NodeId_printf("service_read - nodeId=", &(request->nodesToRead[i].nodeId)));
-		response->results[i] = service_read_node(application, &request->nodesToRead[i]);
+		response->results[i] = service_read_node(server, &request->nodesToRead[i]);
 	}
 	response->responseHeader.serviceResult = UA_STATUSCODE_GOOD;
 	response->diagnosticInfosSize = 0;
 	return UA_SUCCESS;
 }
 
-UA_Int32 Service_Write_writeNode(UA_Application *app, UA_WriteValue *writeValue, UA_StatusCode *result)
-{
+UA_Int32 Service_Write_writeNode(UA_Server *server, UA_WriteValue *writeValue,
+								 UA_StatusCode *result) {
 	UA_Int32 retval = UA_SUCCESS;
-	Namespace *ns = UA_indexedList_findValue(app->namespaces, writeValue->nodeId.namespaceIndex);
+
+	UA_Namespace *ns = UA_NULL;
+	for(UA_UInt32 i=0; i<server->namespacesSize;i++) {
+		if(server->namespaces[i].namespaceIndex == writeValue->nodeId.namespaceIndex) {
+			ns = server->namespaces[i].namespace;
+			break;
+		}
+	}
+	
 	if(ns==UA_NULL) {
 		*result = UA_STATUSCODE_BADNODEIDINVALID;
 		return UA_ERROR;
 	}
 
 	const UA_Node *node;
-	if(Namespace_get(ns, &writeValue->nodeId, &node) != UA_SUCCESS) {
+	if(UA_Namespace_get(ns, &writeValue->nodeId, &node) != UA_SUCCESS) {
 		return UA_ERROR;
 	}
 
@@ -400,23 +403,22 @@ UA_Int32 Service_Write_writeNode(UA_Application *app, UA_WriteValue *writeValue,
 		break;
 	}
 
-	Namespace_releaseManagedNode(node);
+	UA_Namespace_releaseManagedNode(node);
 	return retval;
 
 }
-UA_Int32 Service_Write(UA_Session *session, const UA_WriteRequest *request,
-                      UA_WriteResponse *response) {
+
+UA_Int32 Service_Write(UA_Server *server, UA_Session *session, const UA_WriteRequest *request,
+					   UA_WriteResponse *response) {
 	UA_Int32 retval = UA_SUCCESS;
 	UA_Int32 i;
-	UA_Application *application = UA_NULL;
-	UA_Session_getApplicationPointer(session, &application);
-	if(session == UA_NULL || application == UA_NULL)
+	if(session == UA_NULL || server == UA_NULL)
 		return UA_ERROR;    // TODO: Return error message
 	response->resultsSize = request->nodesToWriteSize;
 	//TODO evalutate diagnostic info within the request
 	UA_Array_new((void**)&response->results,response->resultsSize,&UA_.types[UA_STATUSCODE]);
 	for(i=0; i < request->nodesToWriteSize; i++){
-		retval |= Service_Write_writeNode(application, &request->nodesToWrite[i], &response->results[i]);
+		retval |= Service_Write_writeNode(server, &request->nodesToWrite[i], &response->results[i]);
 	}
 
 	return retval;

+ 10 - 19
src/server/ua_services_discovery.c

@@ -1,27 +1,18 @@
 #include "ua_services.h"
-UA_Int32 Service_GetEndpoints(SL_Channel *channel,
-		const UA_GetEndpointsRequest* request,
-		UA_GetEndpointsResponse *response) {
-#ifdef DEBUG
-	UA_String_printx("endpointUrl=", &request->endpointUrl);
-#endif
 
+UA_Int32 Service_GetEndpoints(UA_Server *server,
+							  const UA_GetEndpointsRequest* request,
+							  UA_GetEndpointsResponse *response) {
 	response->endpointsSize = 1;
 	UA_Array_new((void**) &response->endpoints, response->endpointsSize,
 			&UA_.types[UA_ENDPOINTDESCRIPTION]);
 
-	//Security issues:
-	//The policy should be 'http://opcfoundation.org/UA/SecurityPolicy#None'
-	//FIXME String or ByteString
-	UA_AsymmetricAlgorithmSecurityHeader *asymSettings;
-	SL_Channel_getLocalAsymAlgSettings(channel, &asymSettings);
-	UA_String_copy((UA_String *) &(asymSettings->securityPolicyUri),
-			&response->endpoints[0].securityPolicyUri);
 	//FIXME hard-coded code
 	response->endpoints[0].securityMode = UA_MESSAGESECURITYMODE_NONE;
-	UA_String_copycstring(
-			"http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary",
-			&response->endpoints[0].transportProfileUri);
+	UA_String_copycstring("http://opcfoundation.org/UA/SecurityPolicy#None",
+						  &response->endpoints[0].securityPolicyUri);
+	UA_String_copycstring("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary",
+						  &response->endpoints[0].transportProfileUri);
 
 	response->endpoints[0].userIdentityTokensSize = 1;
 	UA_Array_new((void**) &response->endpoints[0].userIdentityTokens,
@@ -36,12 +27,12 @@ UA_Int32 Service_GetEndpoints(SL_Channel *channel,
 
 	UA_String_copy(&request->endpointUrl, &response->endpoints[0].endpointUrl);
 	UA_String_copycstring("http://open62541.info/product/release",
-			&(response->endpoints[0].server.productUri));
+						  &(response->endpoints[0].server.productUri));
 	// FIXME: This information should be provided by the application, preferably in the address space
 	UA_String_copycstring("http://open62541.info/applications/4711",
-			&(response->endpoints[0].server.applicationUri));
+						  &(response->endpoints[0].server.applicationUri));
 	UA_LocalizedText_copycstring("The open62541 application",
-			&(response->endpoints[0].server.applicationName));
+								 &(response->endpoints[0].server.applicationName));
 	// FIXME: This should be a feature of the application and an enum
 	response->endpoints[0].server.applicationType = UA_APPLICATIONTYPE_SERVER;
 	// all the other strings are empty by initialization

+ 1 - 1
src/server/ua_services_internal.h

@@ -13,4 +13,4 @@
  * @param The reference itself
  * @param The namespace where the target node is looked up for the reverse reference (this is omitted if targetns is UA_NULL)
  */
-UA_Int32 AddReference(UA_Node *node, UA_ReferenceNode *reference, Namespace *targetns);
+UA_Int32 AddReference(UA_Node *node, UA_ReferenceNode *reference, UA_Namespace *targetns);

+ 3 - 1
src/server/ua_services_monitoreditems.c

@@ -4,7 +4,9 @@
 //#if 0
 /* Activate once the infrastructure for pushing events is in place. */
 
-UA_Int32 Service_CreateMonitoredItems(UA_Session *session, const UA_CreateMonitoredItemsRequest *request, UA_CreateMonitoredItemsResponse *response) {
+UA_Int32 Service_CreateMonitoredItems(UA_Server *server, UA_Session *session,
+									  const UA_CreateMonitoredItemsRequest *request,
+									  UA_CreateMonitoredItemsResponse *response) {
 	if (request->itemsToCreateSize > 0) {
 		response->resultsSize = request->itemsToCreateSize;
 

+ 29 - 17
src/server/ua_services_nodemanagement.c

@@ -11,22 +11,36 @@
 		goto GOTO; \
 	} } while(0) \
 
-static UA_AddNodesResult addSingleNode(UA_Application *app, UA_AddNodesItem *item) {
+static UA_AddNodesResult addSingleNode(UA_Server *server, UA_AddNodesItem *item) {
 	UA_AddNodesResult result;
 	UA_AddNodesResult_init(&result);
 
-	Namespace *parent_ns = UA_indexedList_findValue(app->namespaces, item->parentNodeId.nodeId.namespaceIndex);
 	// TODO: search for namespaceUris and not only ns-ids.
+	UA_Namespace *parent_ns = UA_NULL;
+	for(UA_UInt32 i=0; i<server->namespacesSize;i++) {
+		if(server->namespaces[i].namespaceIndex == item->parentNodeId.nodeId.namespaceIndex) {
+			parent_ns = server->namespaces[i].namespace;
+			break;
+		}
+	}
+	
 	if(parent_ns == UA_NULL) {
 		result.statusCode = UA_STATUSCODE_BADPARENTNODEIDINVALID;
 		return result;
 	}
 
-	Namespace *ns = UA_NULL;
+	UA_Namespace *ns = UA_NULL;
 	UA_Boolean nodeid_isnull = UA_NodeId_isNull(&item->requestedNewNodeId.nodeId);
 
 	if(nodeid_isnull) ns = parent_ns;
-	else ns = UA_indexedList_findValue(app->namespaces, item->requestedNewNodeId.nodeId.namespaceIndex);
+	else {
+		for(UA_UInt32 i=0; i<server->namespacesSize;i++) {
+			if(server->namespaces[i].namespaceIndex == item->requestedNewNodeId.nodeId.namespaceIndex) {
+				parent_ns = server->namespaces[i].namespace;
+				break;
+			}
+		}
+	}
 
 	if(ns == UA_NULL || item->requestedNewNodeId.nodeId.namespaceIndex == 0) {
 		result.statusCode = UA_STATUSCODE_BADNODEIDREJECTED;
@@ -35,7 +49,7 @@ static UA_AddNodesResult addSingleNode(UA_Application *app, UA_AddNodesItem *ite
 
 	UA_Int32 status = UA_SUCCESS;
 	const UA_Node *parent;
-	CHECKED_ACTION(Namespace_get(parent_ns, &item->parentNodeId.nodeId, &parent),
+	CHECKED_ACTION(UA_Namespace_get(parent_ns, &item->parentNodeId.nodeId, &parent),
 				   result.statusCode = UA_STATUSCODE_BADPARENTNODEIDINVALID, ret);
 
 	/* if(!nodeid_isnull && Namespace_contains(ns, &item->requestedNewNodeId.nodeId)) { */
@@ -62,18 +76,14 @@ static UA_AddNodesResult addSingleNode(UA_Application *app, UA_AddNodesItem *ite
 	 */
 
  ret:
-	Namespace_releaseManagedNode(parent);
+	UA_Namespace_releaseManagedNode(parent);
 	return result;
 }
 
-UA_Int32 Service_AddNodes(UA_Session *session, const UA_AddNodesRequest *request, UA_AddNodesResponse *response) {
-
-	UA_Application *application;
+UA_Int32 Service_AddNodes(UA_Server *server, UA_Session *session,
+						  const UA_AddNodesRequest *request, UA_AddNodesResponse *response) {
 	if(session == UA_NULL)
 		return UA_ERROR;	// TODO: Return error message
-	UA_Session_getApplicationPointer(session,&application);
-	if(application == UA_NULL)
-		return UA_ERROR;
 
 	UA_Int32 nodestoaddsize = request->nodesToAddSize;
 	if(nodestoaddsize <= 0) {
@@ -86,7 +96,7 @@ UA_Int32 Service_AddNodes(UA_Session *session, const UA_AddNodesRequest *request
 	UA_alloc((void **)&response->results, sizeof(void *) * nodestoaddsize);
 	for(int i = 0; i < nodestoaddsize; i++) {
 		DBG_VERBOSE(UA_QualifiedName_printf("service_addnodes - name=", &(request->nodesToAdd[i].browseName)));
-		response->results[i] = addSingleNode(application, &request->nodesToAdd[i]);
+		response->results[i] = addSingleNode(server, &request->nodesToAdd[i]);
 	}
 	response->responseHeader.serviceResult = UA_STATUSCODE_GOOD;
 	response->diagnosticInfosSize = -1;
@@ -119,7 +129,7 @@ static UA_Int32 AddSingleReference(UA_Node *node, UA_ReferenceNode *reference) {
 	return retval;
 }
 
-UA_Int32 AddReference(UA_Node *node, UA_ReferenceNode *reference, Namespace *targetns) {
+UA_Int32 AddReference(UA_Node *node, UA_ReferenceNode *reference, UA_Namespace *targetns) {
 	UA_Int32 retval = AddSingleReference(node, reference);
 	UA_Node *targetnode;
 	UA_ReferenceNode inversereference;
@@ -127,7 +137,7 @@ UA_Int32 AddReference(UA_Node *node, UA_ReferenceNode *reference, Namespace *tar
 		return retval;
 
 	// Do a copy every time?
-	if(Namespace_get(targetns, &reference->targetId.nodeId, (const UA_Node**)&targetnode) != UA_SUCCESS)
+	if(UA_Namespace_get(targetns, &reference->targetId.nodeId, (const UA_Node**)&targetnode) != UA_SUCCESS)
 		return UA_ERROR;
 
 	inversereference.referenceTypeId = reference->referenceTypeId;
@@ -136,11 +146,13 @@ UA_Int32 AddReference(UA_Node *node, UA_ReferenceNode *reference, Namespace *tar
 	inversereference.targetId.namespaceUri = UA_STRING_NULL;
 	inversereference.targetId.serverIndex = 0;
 	retval = AddSingleReference(targetnode, &inversereference);
-	Namespace_releaseManagedNode(targetnode);
+	UA_Namespace_releaseManagedNode(targetnode);
 
 	return retval;
 }
 
-UA_Int32 Service_AddReferences(UA_Session *session, const UA_AddReferencesRequest *request, UA_AddReferencesResponse *response) {
+UA_Int32 Service_AddReferences(UA_Server *server, UA_Session *session,
+							   const UA_AddReferencesRequest *request,
+							   UA_AddReferencesResponse *response) {
 	return UA_ERROR;
 }

+ 14 - 19
src/server/ua_services_securechannel.c

@@ -1,26 +1,21 @@
 #include "ua_services.h"
-#include "ua_transport_binary_secure.h"
 
-UA_Int32 Service_OpenSecureChannel(SL_Channel *channel,
-const UA_OpenSecureChannelRequest* request,
-UA_OpenSecureChannelResponse* response)
-{
+UA_Int32 Service_OpenSecureChannel(UA_Server *server, UA_Connection *connection,
+								   const UA_OpenSecureChannelRequest* request,
+								   UA_OpenSecureChannelResponse* response) {
 	UA_Int32 retval = UA_SUCCESS;
-	SL_channelState channelState;
-	//channel takes care of opening process
-	retval |= SL_Channel_processOpenRequest(channel, request,response);
-	retval |= SL_Channel_getState(channel, &channelState);
+	// todo: if(request->clientProtocolVersion != protocolVersion)
+	if(request->requestType == UA_SECURITYTOKEN_ISSUE) {
+		retval |= UA_SecureChannelManager_open(server->secureChannelManager, connection, request, response);
+	} else {
+		retval |= UA_SecureChannelManager_renew(server->secureChannelManager, connection, request, response);
+	}
 	return retval;
 }
 
-UA_Int32 Service_CloseSecureChannel(SL_Channel *channel, const UA_CloseSecureChannelRequest *request,
-UA_CloseSecureChannelResponse *response)
-{
-	UA_Int32 retval = UA_SUCCESS;
-	UA_UInt32 channelId;
-	SL_Channel_getChannelId(channel,&channelId);
-	SL_ChannelManager_removeChannel(channelId);
-// 62451 Part 6 Chapter 7.1.4 - The server does not send a CloseSecureChannel response
-
-return retval;
+UA_Int32 Service_CloseSecureChannel(UA_Server *server, UA_SecureChannel *channel,
+									const UA_CloseSecureChannelRequest *request,
+									UA_CloseSecureChannelResponse *response) {
+	return UA_SecureChannelManager_close(server->secureChannelManager, channel->securityToken.channelId);
+	// 62451 Part 6 Chapter 7.1.4 - The server does not send a CloseSecureChannel response
 }

+ 17 - 20
src/server/ua_services_session.c

@@ -1,11 +1,10 @@
 #include "ua_services.h"
 #include "ua_server.h"
 
-UA_Int32 Service_CreateSession(SL_Channel *channel, UA_Server *server, const UA_CreateSessionRequest *request, UA_CreateSessionResponse *response) {
-#ifdef DEBUG
-	UA_String_printf("CreateSession Service - endpointUrl=", &(request->endpointUrl));
-#endif
-	UA_Session *newSession;
+UA_Int32 Service_CreateSession(UA_Server *server, UA_SecureChannel *channel,
+							   const UA_CreateSessionRequest *request,
+							   UA_CreateSessionResponse *response) {
+	/* UA_Session *newSession;
 	UA_Int64 timeout;
 
 	UA_SessionManager_getSessionTimeout(&timeout);
@@ -22,28 +21,26 @@ UA_Int32 Service_CreateSession(SL_Channel *channel, UA_Server *server, const UA_
 	UA_SessionManager_addSession(newSession);
 	UA_Session_getId(newSession, &response->sessionId);
 	UA_Session_getToken(newSession, &(response->authenticationToken));
-	response->revisedSessionTimeout = timeout;
+	response->revisedSessionTimeout = timeout; */
 	//TODO fill results
 	return UA_SUCCESS;
 }
 
-UA_Int32 Service_ActivateSession(SL_Channel *channel, UA_Session *session, const UA_ActivateSessionRequest *request, UA_ActivateSessionResponse *response) {
-	UA_Session_bind(session, channel);
-#ifdef DEBUG
-	UA_NodeId_printf("ActivateSession - authToken=", &(request->requestHeader.authenticationToken));
-	// 321 == AnonymousIdentityToken_Encoding_DefaultBinary
-	UA_NodeId_printf("ActivateSession - uIdToken.type=", &(request->userIdentityToken.typeId));
-	UA_ByteString_printx_hex("ActivateSession - uIdToken.body=", &(request->userIdentityToken.body));
-#endif
+UA_Int32 Service_ActivateSession(UA_Server *server, UA_Session *session,
+								 const UA_ActivateSessionRequest *request,
+								 UA_ActivateSessionResponse *response) {
+	//UA_Session_bind(session, channel);
 	//TODO fill results
 	return UA_SUCCESS;
 }
 
-UA_Int32 Service_CloseSession(UA_Session *session, const UA_CloseSessionRequest *request, UA_CloseSessionResponse *response) {
-	UA_NodeId sessionId;
-	UA_Session_getId(session,&sessionId);
+UA_Int32 Service_CloseSession(UA_Server *server, UA_Session *session,
+							  const UA_CloseSessionRequest *request,
+							  UA_CloseSessionResponse *response) {
+	/* UA_NodeId sessionId; */
+	/* UA_Session_getId(session,&sessionId); */
 
-	UA_SessionManager_removeSession(&sessionId);
-// FIXME: set response
-return UA_SUCCESS;
+	/* UA_SessionManager_removeSession(&sessionId); */
+	// FIXME: set response
+	return UA_SUCCESS;
 }

+ 9 - 9
src/server/ua_services_subscription.c

@@ -7,9 +7,9 @@
 #include "ua_services.h"
 #include "ua_statuscodes.h"
 
-UA_Int32 Service_CreateSubscription(UA_Session *session, const UA_CreateSubscriptionRequest *request,
-                                   UA_CreateSubscriptionResponse *response)
-{
+UA_Int32 Service_CreateSubscription(UA_Server *server, UA_Session *session,
+									const UA_CreateSubscriptionRequest *request,
+									UA_CreateSubscriptionResponse *response) {
 
 	response->subscriptionId = 42;
 	response->revisedPublishingInterval = 100000;
@@ -18,9 +18,9 @@ UA_Int32 Service_CreateSubscription(UA_Session *session, const UA_CreateSubscrip
 	return UA_SUCCESS;
 }
 
-UA_Int32 Service_Publish(UA_Session *session, const UA_PublishRequest *request,
-                                   UA_PublishResponse *response)
-{
+UA_Int32 Service_Publish(UA_Server *server, UA_Session *session,
+						 const UA_PublishRequest *request,
+						 UA_PublishResponse *response) {
 
 	response->subscriptionId = 42;
 	response->notificationMessage.sequenceNumber = 1;
@@ -28,9 +28,9 @@ UA_Int32 Service_Publish(UA_Session *session, const UA_PublishRequest *request,
 	return UA_SUCCESS;
 }
 
-UA_Int32 Service_SetPublishingMode(UA_Session *session, const UA_SetPublishingModeRequest *request,
-                                   UA_SetPublishingModeResponse *response)
-{
+UA_Int32 Service_SetPublishingMode(UA_Server *server, UA_Session *session,
+								   const UA_SetPublishingModeRequest *request,
+                                   UA_SetPublishingModeResponse *response) {
 	response->diagnosticInfos = UA_NULL;
 	response->results = UA_NULL;
 	response->resultsSize = 0;

+ 50 - 39
src/server/ua_services_view.c

@@ -1,10 +1,11 @@
 #include "ua_services.h"
 #include "ua_statuscodes.h"
 
-UA_Int32 Service_Browse_getReferenceDescription(Namespace *ns, UA_ReferenceNode* reference, UA_UInt32 nodeClassMask,
-												UA_UInt32 resultMask, UA_ReferenceDescription* referenceDescription) {
+UA_Int32 Service_Browse_getReferenceDescription(UA_Namespace *ns, UA_ReferenceNode* reference,
+												UA_UInt32 nodeClassMask, UA_UInt32 resultMask,
+												UA_ReferenceDescription* referenceDescription) {
 	const UA_Node* foundNode;
-	if(Namespace_get(ns,&reference->targetId.nodeId,&foundNode) != UA_SUCCESS)
+	if(UA_Namespace_get(ns,&reference->targetId.nodeId,&foundNode) != UA_SUCCESS)
 		return UA_ERROR;
 
 	UA_NodeId_copy(&foundNode->nodeId, &referenceDescription->nodeId.nodeId);
@@ -46,23 +47,24 @@ UA_Int32 Service_Browse_getReferenceDescription(Namespace *ns, UA_ReferenceNode*
 		}
 	}
 	
-	Namespace_releaseManagedNode(foundNode);
+	UA_Namespace_releaseManagedNode(foundNode);
 	return UA_SUCCESS;
 }
 
 /* singly-linked list */
 struct SubRefTypeId {
 	UA_NodeId id;
-	UA_SLIST_ENTRY(SubRefTypeId) next;
+	SLIST_ENTRY(SubRefTypeId) next;
 };
-UA_SLIST_HEAD(SubRefTypeIdList, SubRefTypeId);
+SLIST_HEAD(SubRefTypeIdList, SubRefTypeId);
 
-UA_UInt32 walkReferenceTree(Namespace *ns, const UA_ReferenceTypeNode *current, struct SubRefTypeIdList *list) {
+UA_UInt32 walkReferenceTree(UA_Namespace *ns, const UA_ReferenceTypeNode *current,
+							struct SubRefTypeIdList *list) {
 	// insert the current referencetype
 	struct SubRefTypeId *element;
 	UA_alloc((void**)&element, sizeof(struct SubRefTypeId));
 	element->id = current->nodeId;
-	UA_SLIST_INSERT_HEAD(list, element, next);
+	SLIST_INSERT_HEAD(list, element, next);
 
 	UA_UInt32 count = 1; // the current element
 
@@ -71,10 +73,10 @@ UA_UInt32 walkReferenceTree(Namespace *ns, const UA_ReferenceTypeNode *current,
 		if(current->references[i].referenceTypeId.identifier.numeric == 45 /* HasSubtype */ &&
 		   current->references[i].isInverse == UA_FALSE) {
 			const UA_Node *node;
-			if(Namespace_get(ns, &current->references[i].targetId.nodeId, &node) == UA_SUCCESS &&
-			   node->nodeClass == UA_NODECLASS_REFERENCETYPE) {
+			if(UA_Namespace_get(ns, &current->references[i].targetId.nodeId, &node) == UA_SUCCESS
+			   && node->nodeClass == UA_NODECLASS_REFERENCETYPE) {
 				count += walkReferenceTree(ns,(UA_ReferenceTypeNode*)node, list);
-				Namespace_releaseManagedNode(node);
+				UA_Namespace_releaseManagedNode(node);
 			}
 		}
 	}
@@ -82,25 +84,26 @@ UA_UInt32 walkReferenceTree(Namespace *ns, const UA_ReferenceTypeNode *current,
 }
 
 /* We do not search across namespaces so far. The id of the father-referencetype is returned in the array also. */
-static UA_Int32 findSubReferenceTypes(Namespace *ns, UA_NodeId *rootReferenceType, UA_NodeId **ids, UA_UInt32 *idcount) {
+static UA_Int32 findSubReferenceTypes(UA_Namespace *ns, UA_NodeId *rootReferenceType,
+									  UA_NodeId **ids, UA_UInt32 *idcount) {
 	struct SubRefTypeIdList list;
 	UA_UInt32 count;
-	UA_SLIST_INIT(&list);
+	SLIST_INIT(&list);
 
 	// walk the tree
 	const UA_ReferenceTypeNode *root;
-	if(Namespace_get(ns, rootReferenceType, (const UA_Node**)&root) != UA_SUCCESS ||
+	if(UA_Namespace_get(ns, rootReferenceType, (const UA_Node**)&root) != UA_SUCCESS ||
 	   root->nodeClass != UA_NODECLASS_REFERENCETYPE)
 		return UA_ERROR;
 	count = walkReferenceTree(ns, root, &list);
-	Namespace_releaseManagedNode((const UA_Node*) root);
+	UA_Namespace_releaseManagedNode((const UA_Node*) root);
 
 	// copy results into an array
 	UA_alloc((void**) ids, sizeof(UA_NodeId)*count);
 	for(UA_UInt32 i = 0; i < count;i++) {
-		struct SubRefTypeId *element = UA_SLIST_FIRST(&list);
+		struct SubRefTypeId *element = SLIST_FIRST(&list);
 		UA_NodeId_copy(&element->id, &(*ids)[i]);
-		UA_SLIST_REMOVE_HEAD(&list, next);
+		SLIST_REMOVE_HEAD(&list, next);
 		UA_free(element);
 	}
 	*idcount = count;
@@ -111,9 +114,11 @@ static UA_Int32 findSubReferenceTypes(Namespace *ns, UA_NodeId *rootReferenceTyp
 /* is this a relevant reference? */
 static INLINE UA_Boolean Service_Browse_returnReference(UA_BrowseDescription *browseDescription, UA_ReferenceNode* reference,
 														UA_NodeId *relevantRefTypes, UA_UInt32 relevantRefTypesCount) {
-	if (reference->isInverse == UA_TRUE && browseDescription->browseDirection == UA_BROWSEDIRECTION_FORWARD)
+	if (reference->isInverse == UA_TRUE &&
+		browseDescription->browseDirection == UA_BROWSEDIRECTION_FORWARD)
 		return UA_FALSE;
-	else if (reference->isInverse == UA_FALSE && browseDescription->browseDirection == UA_BROWSEDIRECTION_INVERSE)
+	else if (reference->isInverse == UA_FALSE &&
+			 browseDescription->browseDirection == UA_BROWSEDIRECTION_INVERSE)
 		return UA_FALSE;
 	for(UA_UInt32 i = 0; i<relevantRefTypesCount;i++) {
 		if(UA_NodeId_equal(&browseDescription->referenceTypeId, &relevantRefTypes[i]) == UA_EQUAL)
@@ -123,12 +128,14 @@ static INLINE UA_Boolean Service_Browse_returnReference(UA_BrowseDescription *br
 }
 
 /* Return results to a single browsedescription. */
-static void Service_Browse_getBrowseResult(Namespace *ns, UA_BrowseDescription *browseDescription,
-										   UA_UInt32 maxReferences, UA_BrowseResult *browseResult) {
+static void Service_Browse_getBrowseResult(UA_Namespace *ns,
+										   UA_BrowseDescription *browseDescription,
+										   UA_UInt32 maxReferences,
+										   UA_BrowseResult *browseResult) {
 	const UA_Node* node;
 	UA_NodeId *relevantReferenceTypes;
 	UA_UInt32 relevantReferenceTypesCount = 0;
-	if(Namespace_get(ns, &browseDescription->nodeId, &node) != UA_SUCCESS) {
+	if(UA_Namespace_get(ns, &browseDescription->nodeId, &node) != UA_SUCCESS) {
 		browseResult->statusCode = UA_STATUSCODE_BADNODEIDUNKNOWN;
 		return;
 	}
@@ -139,7 +146,8 @@ static void Service_Browse_getBrowseResult(Namespace *ns, UA_BrowseDescription *
 
 	// discover the relevant subtypes
 	if(!browseDescription->includeSubtypes ||
-	   findSubReferenceTypes(ns, &browseDescription->referenceTypeId, &relevantReferenceTypes, &relevantReferenceTypesCount) != UA_SUCCESS) {
+	   findSubReferenceTypes(ns, &browseDescription->referenceTypeId, &relevantReferenceTypes,
+							 &relevantReferenceTypesCount) != UA_SUCCESS) {
 		UA_alloc((void**)&relevantReferenceTypes, sizeof(UA_NodeId));
 		UA_NodeId_copy(&browseDescription->referenceTypeId, relevantReferenceTypes);
 		relevantReferenceTypesCount = 1;
@@ -180,30 +188,31 @@ static void Service_Browse_getBrowseResult(Namespace *ns, UA_BrowseDescription *
 		// Todo. Set the Statuscode and the continuation point.
 	}
 	
-	Namespace_releaseManagedNode(node);
+	UA_Namespace_releaseManagedNode(node);
 	UA_Array_delete(relevantReferenceTypes, relevantReferenceTypesCount, &UA_.types[UA_NODEID]);
 }
 
-UA_Int32 Service_Browse(UA_Session *session, const UA_BrowseRequest *request, UA_BrowseResponse *response) {
+UA_Int32 Service_Browse(UA_Server *server, UA_Session *session,
+						const UA_BrowseRequest *request, UA_BrowseResponse *response) {
 	UA_Int32 retval = UA_SUCCESS;
-	UA_Application *application;
-	if(session == UA_NULL)
-	{
+	if(server == UA_NULL || session == UA_NULL)
 		return UA_ERROR;
-	}
-	UA_Session_getApplicationPointer(session, &application);
-	if(application == UA_NULL)
-	{
-		return UA_ERROR;
-	}
-	DBG_VERBOSE(UA_NodeId_printf("BrowseService - view=", &request->view.viewId));
-
+	
 	//TODO request->view not used atm
 	UA_Array_new((void**) &(response->results), request->nodesToBrowseSize, &UA_.types[UA_BROWSERESULT]);
 	response->resultsSize = request->nodesToBrowseSize;
 
 	for(UA_Int32 i=0; i < request->nodesToBrowseSize; i++) {
-		Namespace *ns = UA_indexedList_findValue(application->namespaces, request->nodesToBrowse[i].nodeId.namespaceIndex);
+		UA_Namespace *ns = UA_NULL;
+
+		for(UA_UInt32 i=0; i<server->namespacesSize;i++) {
+			if(server->namespaces[i].namespaceIndex ==
+			   request->nodesToBrowse[i].nodeId.namespaceIndex) {
+				ns = server->namespaces[i].namespace;
+				break;
+			}
+		}
+
 		if(ns == UA_NULL) {
 			response->results[i].statusCode = UA_STATUSCODE_BADNODEIDUNKNOWN;
 			continue;
@@ -211,7 +220,8 @@ UA_Int32 Service_Browse(UA_Session *session, const UA_BrowseRequest *request, UA
 		
 		// Service_Browse_getBrowseResult has no return value. All errors are resolved internally.
 		Service_Browse_getBrowseResult(ns, &request->nodesToBrowse[i],
-									   request->requestedMaxReferencesPerNode, &response->results[i]);
+									   request->requestedMaxReferencesPerNode,
+									   &response->results[i]);
 	}
 
 	//TODO fill Diagnostic info array
@@ -221,7 +231,8 @@ UA_Int32 Service_Browse(UA_Session *session, const UA_BrowseRequest *request, UA
 }
 
 
-UA_Int32 Service_TranslateBrowsePathsToNodeIds(UA_Session *session, const UA_TranslateBrowsePathsToNodeIdsRequest *request,
+UA_Int32 Service_TranslateBrowsePathsToNodeIds(UA_Server *server, UA_Session *session,
+											   const UA_TranslateBrowsePathsToNodeIdsRequest *request,
 											   UA_TranslateBrowsePathsToNodeIdsResponse *response) {
 	UA_Int32 retval = UA_SUCCESS;
 	DBG_VERBOSE(printf("TranslateBrowsePathsToNodeIdsService - %i path(s)", request->browsePathsSize));

+ 49 - 63
src/server/ua_session_manager.c

@@ -1,4 +1,5 @@
 #include "ua_session_manager.h"
+#include "util/ua_list.h"
 
 struct UA_SessionManager {
 	UA_list_List sessions;
@@ -8,31 +9,38 @@ struct UA_SessionManager {
 	UA_DateTime maxSessionLifeTime;
 	UA_DateTime sessionTimeout;
 };
+UA_Int32 UA_SessionManager_new(UA_SessionManager **sessionManager, UA_UInt32 maxSessionCount,
+								UA_UInt32 sessionTimeout, UA_UInt32 startSessionId) {
+	UA_Int32 retval = UA_SUCCESS;
+	retval |= UA_alloc((void**)sessionManager,sizeof(UA_SessionManager));
+	retval |= UA_list_init(&(*sessionManager)->sessions);
+	(*sessionManager)->maxSessionCount = maxSessionCount;
+	(*sessionManager)->lastSessionId = startSessionId;
+	(*sessionManager)->sessionTimeout = sessionTimeout;
+	return retval;
+}
+
+UA_Int32 UA_SessionManager_delete(UA_SessionManager *sessionManager) {
+	// todo
+	return UA_SUCCESS;
+}
 
-static UA_SessionManager *sessionManager;
 
-UA_Int32 UA_SessionManager_generateSessionId(UA_NodeId *sessionId) {
+UA_Int32 UA_SessionManager_generateSessionId(UA_SessionManager *sessionManager,
+											 UA_NodeId *sessionId) {
 	sessionId->namespaceIndex = 0;
 	sessionId->identifierType = UA_NODEIDTYPE_NUMERIC;
 	sessionId->identifier.numeric = sessionManager->lastSessionId++;
 	return UA_SUCCESS;
 }
 
-UA_Int32 UA_SessionManager_init(UA_UInt32 maxSessionCount,UA_UInt32 sessionTimeout, UA_UInt32 startSessionId) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_alloc((void**)&sessionManager,sizeof(UA_SessionManager));
-	retval |= UA_list_init(&sessionManager->sessions);
-	sessionManager->maxSessionCount = maxSessionCount;
-	sessionManager->lastSessionId = startSessionId;
-	sessionManager->sessionTimeout = sessionTimeout;
-	return retval;
-}
-
-UA_Boolean UA_SessionManager_sessionExists(UA_Session *session) {
+UA_Boolean UA_SessionManager_sessionExists(UA_SessionManager *sessionManager,
+										   UA_Session *session) {
 	if(sessionManager == UA_NULL)
 		return UA_FALSE;
 
-	if(UA_list_search(&sessionManager->sessions,(UA_list_PayloadComparer)UA_Session_compare,(void*)session)) {
+	if(UA_list_search(&sessionManager->sessions,
+					  (UA_list_PayloadComparer)UA_Session_compare,(void*)session)) {
 		UA_Double pendingLifetime;
 		UA_Session_getPendingLifetime(session,&pendingLifetime);
 
@@ -40,14 +48,14 @@ UA_Boolean UA_SessionManager_sessionExists(UA_Session *session) {
 			return UA_TRUE;
 
 		//timeout of session reached so remove it
-		UA_NodeId sessionId;
-		UA_Session_getId(session,&sessionId);
-		UA_SessionManager_removeSession(&sessionId);
+		UA_NodeId *sessionId = &session->sessionId;
+		UA_SessionManager_removeSession(sessionManager, sessionId);
 	}
 	return UA_FALSE;
 }
 
-UA_Int32 UA_SessionManager_getSessionById(UA_NodeId *sessionId, UA_Session **session) {
+UA_Int32 UA_SessionManager_getSessionById(UA_SessionManager *sessionManager,
+										  UA_NodeId *sessionId, UA_Session **session) {
 	if(sessionManager == UA_NULL) {
 		*session = UA_NULL;
 		return UA_ERROR;
@@ -58,7 +66,7 @@ UA_Int32 UA_SessionManager_getSessionById(UA_NodeId *sessionId, UA_Session **ses
 		if (current->payload) {
 			UA_list_Element* elem = (UA_list_Element*) current;
 			*session = ((UA_Session*) (elem->payload));
-			if(UA_Session_compareById(*session,sessionId) == UA_EQUAL){
+			if(UA_NodeId_equal(&(*session)->sessionId, sessionId) == UA_EQUAL){
 				UA_Double pendingLifetime;
 				UA_Session_getPendingLifetime(*session, &pendingLifetime);
 
@@ -77,7 +85,8 @@ UA_Int32 UA_SessionManager_getSessionById(UA_NodeId *sessionId, UA_Session **ses
 	return UA_ERROR;
 }
 
-UA_Int32 UA_SessionManager_getSessionByToken(UA_NodeId *token, UA_Session **session) {
+UA_Int32 UA_SessionManager_getSessionByToken(UA_SessionManager *sessionManager,
+											 UA_NodeId *token, UA_Session **session) {
 	if(sessionManager == UA_NULL) {
 		*session = UA_NULL;
 		return UA_ERROR;
@@ -89,7 +98,7 @@ UA_Int32 UA_SessionManager_getSessionByToken(UA_NodeId *token, UA_Session **sess
 			UA_list_Element* elem = (UA_list_Element*) current;
 			*session = ((UA_Session*) (elem->payload));
 
-			if(UA_Session_compareByToken(*session,token) == UA_EQUAL) {
+			if(UA_NodeId_equal(&(*session)->authenticationToken, token) == UA_EQUAL) {
 				UA_Double pendingLifetime;
 				UA_Session_getPendingLifetime(*session, &pendingLifetime);
 
@@ -108,60 +117,37 @@ UA_Int32 UA_SessionManager_getSessionByToken(UA_NodeId *token, UA_Session **sess
 	return UA_ERROR;
 }
 
-UA_Int32 UA_SessionManager_addSession(UA_Session *session) {
+/** Creates and adds a session. */
+UA_Int32 UA_SessionManager_addSession(UA_SessionManager *sessionManager,
+									  UA_SecureChannel *channel, UA_Session **session) {
 	UA_Int32 retval = UA_SUCCESS;
-	UA_NodeId sessionId;
-	if(!UA_SessionManager_sessionExists(session)) {
-		retval |= UA_list_addPayloadToBack(&sessionManager->sessions,(void*)session);
-		UA_Session_getId(session, &sessionId);
-		printf("UA_SessionManager_addSession - added session with id = %d \n",sessionId.identifier.numeric);
-		printf("UA_SessionManager_addSession - current session count: %i \n",sessionManager->sessions.size);
-
-		return retval;
-	}
-	printf("UA_SessionManager_addSession - session already in list");
-	return UA_ERROR;
+	if(sessionManager->currentSessionCount >= sessionManager->maxSessionCount)
+		return UA_ERROR;
+	UA_Session_new(session);
+	(*session)->sessionId = (UA_NodeId){.namespaceIndex = 1, .identifierType = UA_NODEIDTYPE_NUMERIC,
+							 .identifier.numeric = sessionManager->lastSessionId++};
+	(*session)->channel = channel;
+	channel->session = *session;
+
+	sessionManager->currentSessionCount++;
+	return retval;
 }
 
-UA_Int32 UA_SessionManager_removeSession(UA_NodeId *sessionId) {
+UA_Int32 UA_SessionManager_removeSession(UA_SessionManager *sessionManager,
+										 UA_NodeId *sessionId) {
 	UA_Int32 retval = UA_SUCCESS;
 	UA_list_Element *element = UA_list_search(&sessionManager->sessions,(UA_list_PayloadComparer)UA_Session_compare,sessionId);
 	if(element) {
+	    UA_Session *session = element->payload;
+		session->channel->session = UA_NULL;
 		retval |= UA_list_removeElement(element,(UA_list_PayloadVisitor)UA_Session_delete);
 		printf("UA_SessionManager_removeSession - session removed, current count: %i \n",sessionManager->sessions.size);
 	}
 	return retval;
 }
-/*
-UA_Int32 UA_SessionManager_updateSessions()
-{
-	if(sessionManager == UA_NULL)
-	{
-		return UA_ERROR;
-	}
-	UA_list_Element* current = sessionManager->sessions.first;
-	while (current)
-	{
-		if (current->payload)
-		{
-			UA_list_Element* elem = (UA_list_Element*) current;
-			UA_Session *session = ((UA_Session*) (elem->payload));
-			UA_Double pendingLifetime;
-			UA_Session_getPendingLifetime(session, &pendingLifetime);
-
-			if(pendingLifetime <= 0){
-				UA_NodeId sessionId;
-				UA_Session_getId(session,&sessionId);
-				UA_SessionManager_removeSession(&sessionId);
-			}
-		}
-		current = current->next;
-	}
-	return UA_SUCCESS;
-}
-*/
 
-UA_Int32 UA_SessionManager_getSessionTimeout(UA_Int64 *timeout_ms) {
+UA_Int32 UA_SessionManager_getSessionTimeout(UA_SessionManager *sessionManager,
+											 UA_Int64 *timeout_ms) {
 	if(sessionManager) {
 		*timeout_ms = sessionManager->sessionTimeout;
 		return UA_SUCCESS;

+ 16 - 19
src/server/ua_session_manager.h

@@ -6,28 +6,21 @@
 struct UA_SessionManager;
 typedef struct UA_SessionManager UA_SessionManager;
 
-/**
- * @brief initializes the session manager
- * @param maxSessionCount maximum amount of sessions which should be allowed to be created
- * @param sessionLifetime lifetime of a session, after this time the session must be renewed
- * @param startSessionId the start id of the session identifiers, newer sessions get higher ids
- * @return error code
- */
-UA_Int32 UA_SessionManager_init(UA_UInt32 maxSessionCount,UA_UInt32 sessionLifetime, UA_UInt32 startSessionId);
+UA_Int32 UA_SessionManager_new(UA_SessionManager **sessionManager, UA_UInt32 maxSessionCount,
+								UA_UInt32 sessionLifetime, UA_UInt32 startSessionId);
 
-/**
- * @brief adds a session to the manager list
- * @param session session object which should be added to the manager list
- * @return error code
- */
-UA_Int32 UA_SessionManager_addSession(UA_Session *session);
+UA_Int32 UA_SessionManager_delete(UA_SessionManager *sessionManager);
+
+UA_Int32 UA_SessionManager_addSession(UA_SessionManager *sessionManager,
+									  UA_SecureChannel *channel, UA_Session **session);
 
 /**
  * @brief removes a session from the manager list
  * @param sessionId id which assign to a session
  * @return error code
  */
-UA_Int32 UA_SessionManager_removeSession(UA_NodeId *sessionId);
+UA_Int32 UA_SessionManager_removeSession(UA_SessionManager *sessionManager,
+										 UA_NodeId *sessionId);
 
 /**
  * @brief finds the session which is identified by the sessionId
@@ -35,7 +28,8 @@ UA_Int32 UA_SessionManager_removeSession(UA_NodeId *sessionId);
  * @param session the session object is returned if no error occurs
  * @return error code
  */
-UA_Int32 UA_SessionManager_getSessionById(UA_NodeId *sessionId, UA_Session **session);
+UA_Int32 UA_SessionManager_getSessionById(UA_SessionManager *sessionManager,
+										  UA_NodeId *sessionId, UA_Session **session);
 
 /**
  * @brief
@@ -43,7 +37,8 @@ UA_Int32 UA_SessionManager_getSessionById(UA_NodeId *sessionId, UA_Session **ses
  * @param session output, session object which is identified by the authentication token
  * @return error code
  */
-UA_Int32 UA_SessionManager_getSessionByToken(UA_NodeId *token, UA_Session **session);
+UA_Int32 UA_SessionManager_getSessionByToken(UA_SessionManager *sessionManager,
+											 UA_NodeId *token, UA_Session **session);
 
 /**
  * @brief gets the session timeout value which should be assigned to
@@ -51,10 +46,12 @@ UA_Int32 UA_SessionManager_getSessionByToken(UA_NodeId *token, UA_Session **sess
  * @param timeout_ms timeout in milliseconds
  * @return error code
  */
-UA_Int32 UA_SessionManager_getSessionTimeout(UA_Int64 *timeout_ms);
+UA_Int32 UA_SessionManager_getSessionTimeout(UA_SessionManager *sessionManager,
+											 UA_Int64 *timeout_ms);
 
 //UA_Int32 UA_SessionManager_updateSessions();
 //UA_Int32 UA_SessionManager_generateToken(UA_Session session, UA_Int32 requestedLifeTime, SecurityTokenRequestType requestType, UA_ChannelSecurityToken* newToken);
-UA_Int32 UA_SessionManager_generateSessionId(UA_NodeId *newSessionId);
+UA_Int32 UA_SessionManager_generateSessionId(UA_SessionManager *sessionManager,
+											 UA_NodeId *newSessionId);
 
 #endif /* UA_SESSION_MANAGER_H_ */

+ 0 - 65
src/server/ua_transport_connection_manager.c

@@ -1,65 +0,0 @@
-/*
- * ua_connection_manager.c
- *
- *  Created on: 11.05.2014
- *      Author: open62541
- */
-
-#include "ua_transport_connection_manager.h"
-#include "ua_indexedList.h"
-
-typedef struct UA_TL_ConnectionManager {
-	UA_list_List connections;
-	UA_UInt32 maxConnectionCount;
-	UA_UInt32 currentConnectionCount;
-} UA_TL_ConnectionManager;
-
-static UA_TL_ConnectionManager *connectionManager = UA_NULL;
-
-UA_Int32 UA_TL_ConnectionManager_init(UA_UInt32 maxConnectionCount) {
-	UA_Int32 retval = UA_SUCCESS;
-	if(connectionManager != UA_NULL)
-		return UA_ERROR; //connection Manager already exists
-
-	retval |= UA_alloc((void**)&connectionManager,sizeof(UA_TL_ConnectionManager));
-	connectionManager->maxConnectionCount = maxConnectionCount;
-	connectionManager->currentConnectionCount = 0;
-	retval |= UA_indexedList_init(&connectionManager->connections);
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_ConnectionManager_addConnection(UA_TL_Connection *connection) {
-	UA_UInt32 connectionId;
-	UA_TL_Connection_getHandle(connection, &connectionId);
-	printf("UA_TL_ConnectionManager_addConnection - added connection with handle = %d \n", connectionId);
-	return UA_list_addPayloadToBack(&(connectionManager->connections), (void*)connection);
-}
-
-UA_Int32 UA_TL_ConnectionManager_removeConnection(UA_TL_Connection *connection) {
-	UA_list_Element *element =  UA_list_find(&connectionManager->connections, (UA_list_PayloadMatcher)UA_TL_Connection_compare);
-	if(element) {
-		UA_list_removeElement(element, (UA_list_PayloadVisitor)UA_TL_Connection_delete);
-	}
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_ConnectionManager_getConnectionByHandle(UA_UInt32 connectionId, UA_TL_Connection **connection) {
-	UA_UInt32 tmpConnectionHandle;
-	if(connectionManager) {
-		UA_list_Element* current = connectionManager->connections.first;
-		while (current) {
-			if (current->payload) {
-				UA_list_Element* elem = (UA_list_Element*) current;
-				*connection = ((UA_TL_Connection*) (elem->payload));
-				UA_TL_Connection_getHandle(*connection, &tmpConnectionHandle);
-
-				if(tmpConnectionHandle == connectionId)
-					return UA_SUCCESS;
-			}
-			current = current->next;
-		}
-	}
-
-	*connection = UA_NULL;
-	return UA_ERROR;
-}

+ 0 - 14
src/server/ua_transport_connection_manager.h

@@ -1,14 +0,0 @@
-#ifndef UA_CONNECTION_MANAGER_H_
-#define UA_CONNECTION_MANAGER_H_
-
-#include "stdio.h"
-#include "ua_transport_connection.h"
-
-UA_Int32 UA_TL_ConnectionManager_init(UA_UInt32 maxConnectionCount);
-UA_Int32 UA_TL_ConnectionManager_addConnection(UA_TL_Connection *connection);
-UA_Int32 UA_TL_ConnectionManager_removeConnection(UA_TL_Connection *connection);
-
-//getter
-UA_Int32 UA_TL_ConnectionManager_getConnectionByHandle(UA_UInt32 connectionId, UA_TL_Connection **connection);
-
-#endif /* UA_CONNECTION_MANAGER_H_ */

+ 0 - 382
src/ua_channel.c

@@ -1,382 +0,0 @@
-#include "ua_channel.h"
-#include <time.h>
-#include <stdlib.h>
-
-struct SL_Channel {
-	SL_channelState state;
-	UA_UInt32 channelId;
-	//TL_Connection* tlConnection;
-
-	UA_TL_Connection *connection;
-	UA_UInt32 requestId;
-	//UA_UInt32 lastRequestId;
-
-	UA_UInt32 sequenceNumber;
-	//UA_UInt32 lastSequenceNumber;
-
-	UA_AsymmetricAlgorithmSecurityHeader remoteAsymAlgSettings;
-	UA_AsymmetricAlgorithmSecurityHeader localAsymAlgSettings;
-
-	UA_ChannelSecurityToken securityToken;
-
-	UA_MessageSecurityMode securityMode;
-	UA_ByteString remoteNonce;
-	UA_ByteString localNonce;
-	SL_ChannelSecurityTokenProvider tokenProvider;
-	SL_ChannelIdProvider channelIdProvider;
-};
-
-UA_Int32 SL_Channel_setRemoteSecuritySettings(SL_Channel *channel,
-		UA_AsymmetricAlgorithmSecurityHeader *asymSecHeader,
-		UA_SequenceHeader *sequenceHeader) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_AsymmetricAlgorithmSecurityHeader_copy(asymSecHeader,
-			&channel->remoteAsymAlgSettings);
-	//set starting sequence number from remote partner
-	channel->sequenceNumber =
-			sequenceHeader->sequenceNumber;
-	//set starting request id from remote partner
-	channel->requestId = sequenceHeader->requestId;
-	return retval;
-}
-
-/* UA_Int32 SL_Channel_initLocalSecuritySettings(SL_Channel *channel)
-{
-	UA_Int32 retval = UA_SUCCESS;
-	channel->localAsymAlgSettings.receiverCertificateThumbprint.data = UA_NULL;
-	channel->localAsymAlgSettings.receiverCertificateThumbprint.length = 0;
-
-	retval |= UA_String_copycstring("http://opcfoundation.org/UA/SecurityPolicy#None",(UA_String*)&channel->localAsymAlgSettings.securityPolicyUri);
-
-	channel->localAsymAlgSettings.senderCertificate.data = UA_NULL;
-	channel->localAsymAlgSettings.senderCertificate.length = 0;
-	return retval;
-} */
-
-UA_Int32 SL_Channel_new(SL_Channel **channel) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_alloc((void** )channel, sizeof(SL_Channel));
-	SL_Channel *thisChannel = UA_NULL;
-	retval |= UA_alloc((void** )&thisChannel, sizeof(SL_Channel));
-	*channel = thisChannel;
-	return retval;
-}
-
-//TODO implement real nonce generator - DUMMY function
-UA_Int32 SL_Channel_generateNonce(UA_ByteString *nonce) {
-	//UA_ByteString_new(&nonce);
-	UA_alloc((void** )&(nonce->data), 1);
-	nonce->length = 1;
-	nonce->data[0] = 'a';
-	return UA_SUCCESS;
-}
-
-UA_Int32 SL_Channel_init(SL_Channel *channel, UA_TL_Connection *connection,
-		SL_ChannelIdProvider channelIdProvider,
-		SL_ChannelSecurityTokenProvider tokenProvider) {
-
-	UA_Int32 retval = UA_SUCCESS;
-
-	channel->channelIdProvider = channelIdProvider;
-	channel->tokenProvider = tokenProvider;
-
-	channel->connection = connection;
-	//generate secure channel id
-	channel->channelIdProvider(
-			&channel->channelId);
-
-	//generate local nonce
-	SL_Channel_generateNonce(&channel->localNonce);
-	//TODO get this from the local configuration file MOCK UP ---start
-	channel->localAsymAlgSettings.receiverCertificateThumbprint.data = UA_NULL;
-	channel->localAsymAlgSettings.receiverCertificateThumbprint.length = 0;
-
-	retval |= UA_String_copycstring("http://opcfoundation.org/UA/SecurityPolicy#None",(UA_String*)&channel->localAsymAlgSettings.securityPolicyUri);
-
-	channel->localAsymAlgSettings.senderCertificate.data = UA_NULL;
-	channel->localAsymAlgSettings.senderCertificate.length = 0;
-	// MOCK UP ---end
-
-
-	channel->state = UA_SL_CHANNEL_CLOSED;
-	return retval;
-}
-
-UA_Int32 SL_Channel_registerTokenProvider(SL_Channel *channel,
-		SL_ChannelSecurityTokenProvider provider) {
-	channel->tokenProvider = provider;
-	return UA_SUCCESS;
-}
-
-UA_Int32 SL_Channel_getRemainingLifetime(SL_Channel *channel, UA_Int32 *lifetime) {
-	if (channel) {
-		UA_Int64 diffInMS = (channel->securityToken.createdAt - UA_DateTime_now()) / 1e7;
-		if (diffInMS > UA_INT32_MAX) {
-			*lifetime = UA_INT32_MAX;
-		} else {
-			*lifetime = (UA_Int32) diffInMS;
-		}
-		return UA_SUCCESS;
-	} else {
-		printf(
-				"SL_Channel_getRemainingLifetime - no valid channel object, null pointer");
-		return UA_ERROR;
-	}
-}
-
-UA_Int32 SL_Channel_getChannelId(SL_Channel *channel, UA_UInt32 *channelId) {
-	if (channel) {
-		*channelId = channel->channelId;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_getTokenId(SL_Channel *channel, UA_UInt32 *tokenId) {
-	if (channel) {
-		*tokenId = channel->securityToken.tokenId;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_getLocalAsymAlgSettings(SL_Channel *channel,
-		UA_AsymmetricAlgorithmSecurityHeader **asymAlgSettings) {
-	UA_Int32 retval = 0;
-
-	retval |= UA_alloc((void** )asymAlgSettings,
-			UA_AsymmetricAlgorithmSecurityHeader_calcSizeBinary(UA_NULL));
-
-	retval |=
-			UA_ByteString_copy(
-					&(channel->localAsymAlgSettings.receiverCertificateThumbprint),
-					&(*asymAlgSettings)->receiverCertificateThumbprint);
-	retval |=
-			UA_ByteString_copy(
-					&(channel->localAsymAlgSettings.securityPolicyUri),
-					&(*asymAlgSettings)->securityPolicyUri);
-	retval |=
-			UA_ByteString_copy(
-					&(channel->localAsymAlgSettings.senderCertificate),
-					&(*asymAlgSettings)->senderCertificate);
-
-	return UA_SUCCESS;
-}
-
-UA_Int32 SL_Channel_getConnection(SL_Channel *channel,
-		UA_TL_Connection **connection) {
-	if (channel) {
-		*connection = channel->connection;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_getRequestId(SL_Channel *channel, UA_UInt32 *requestId) {
-	if (channel) {
-		*requestId = channel->requestId;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_getSequenceNumber(SL_Channel *channel,
-		UA_UInt32 *sequenceNumber) {
-	if (channel) {
-		*sequenceNumber = channel->sequenceNumber;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_getState(SL_Channel *channel, SL_channelState *channelState) {
-	if (channel) {
-		*channelState = channel->state;
-		return UA_SUCCESS;
-	}
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_getRevisedLifetime(SL_Channel *channel, UA_UInt32 *revisedLifetime) {
-	if(!channel)
-		return UA_ERROR;
-
-	*revisedLifetime = channel->securityToken.revisedLifetime;
-	return UA_SUCCESS;
-}
-
-//setters
-UA_Int32 SL_Channel_setId(SL_Channel *channel, UA_UInt32 id) {
-	channel->channelId = id;
-	return UA_SUCCESS;
-}
-
-//private function
-UA_Int32 SL_Channel_setState(SL_Channel *channel, SL_channelState channelState) {
-	channel->state = channelState;
-	return UA_SUCCESS;
-}
-
-
-
-UA_Boolean SL_Channel_compare(SL_Channel *channel1, SL_Channel *channel2) {
-	return (((SL_Channel*) channel1)->channelId == ((SL_Channel*) channel2)->channelId) ?
-			UA_TRUE : UA_FALSE;
-}
-
-UA_Int32 SL_Channel_bind(SL_Channel *channel, UA_TL_Connection *connection) {
-	if (!channel || !connection)
-		return UA_ERROR;
-
-	channel->connection = connection;
-	return UA_SUCCESS;
-}
-
-UA_Int32 SL_Channel_deleteMembers(SL_Channel *channel) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->localAsymAlgSettings);
-	retval |= UA_ByteString_deleteMembers(&channel->localNonce);
-	retval |= UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->remoteAsymAlgSettings);
-	retval |= UA_ByteString_deleteMembers(&channel->remoteNonce);
-	retval |= UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
-	return retval;
-}
-UA_Int32 SL_Channel_delete(SL_Channel *channel) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval = SL_Channel_deleteMembers(channel);
-	retval = UA_free(channel);
-	return retval;
-}
-
-UA_Int32 SL_Channel_processTokenRequest(SL_Channel *channel, UA_UInt32 requestedLifetime, UA_SecurityTokenRequestType requestType) {
-	if (channel->tokenProvider)
-		return channel->tokenProvider(channel, requestedLifetime, requestType, &channel->securityToken);
-	printf("SL_Channel_processTokenRequest - no Token provider registered");
-	return UA_ERROR;
-}
-UA_Int32 SL_Channel_renewToken(SL_Channel *channel, UA_UInt32 tokenId,
-		UA_DateTime revisedLifetime, UA_DateTime createdAt) {
-	channel->securityToken.tokenId = tokenId;
-	channel->securityToken.createdAt = createdAt;
-	channel->securityToken.revisedLifetime = revisedLifetime;
-	return UA_SUCCESS;
-}
-
-UA_Int32 SL_Channel_checkSequenceNumber(SL_Channel *channel, UA_UInt32 sequenceNumber) {
-	//TODO review checking of sequence
-	if (channel->sequenceNumber+1  == sequenceNumber) {
-		channel->sequenceNumber++;
-		return UA_SUCCESS;
-	}
-	printf("SL_Channel_checkSequenceNumber - ERROR, wrong SequenceNumber expected: %i, received: %i",
-			channel->sequenceNumber + 1, sequenceNumber);
-	return UA_ERROR;
-
-}
-
-UA_Int32 SL_Channel_checkRequestId(SL_Channel *channel, UA_UInt32 requestId) {
-	//TODO review checking of request id
-	if (channel->requestId+1  == requestId) {
-		channel->requestId++;
-		return UA_SUCCESS;
-	}
-	printf("SL_Channel_requestId - ERROR, wrong requestId expected: %i, received: %i",
-			channel->requestId + 1, requestId);
-	return UA_ERROR;
-}
-
-UA_Int32 SL_Channel_processOpenRequest(SL_Channel *channel, const UA_OpenSecureChannelRequest* request,
-									   UA_OpenSecureChannelResponse* response) {
-	UA_UInt32 protocolVersion;
-	SL_Channel* thisChannel = channel;
-	UA_Int32 retval = UA_SUCCESS;
-
-	UA_TL_Connection_getProtocolVersion(thisChannel->connection, &protocolVersion);
-
-	if (request->clientProtocolVersion != protocolVersion) {
-		printf("SL_Channel_processOpenRequest - error protocol version \n");
-		//TODO ERROR_Bad_ProtocolVersionUnsupported
-	}
-
-	switch (request->requestType) {
-	case UA_SECURITYTOKEN_ISSUE:
-		if (thisChannel->state == UA_SL_CHANNEL_OPEN) {
-			printf(
-					"SL_Channel_processOpenRequest - multiple security token request");
-			//TODO return ERROR
-			retval = UA_ERROR;
-			break;
-		}
-		printf(
-				"SL_Channel_processOpenRequest - creating new token for a new SecureChannel\n");
-		SL_Channel_processTokenRequest(channel, request->requestedLifetime,
-				request->requestType);
-		//	SL_createNewToken(connection);
-		break;
-	case UA_SECURITYTOKEN_RENEW:
-		if (thisChannel->state == UA_SL_CHANNEL_CLOSED) {
-			printf(
-					"SL_Channel_processOpenRequest - renew token request received, but no secureChannel was established before");
-			//TODO return ERROR
-			retval = UA_ERROR;
-			break;
-		} else {
-			//generate new SecurityToken
-			retval = SL_Channel_processTokenRequest(channel,
-					request->requestedLifetime, request->requestType);
-			if (retval != UA_SUCCESS) {
-				printf(
-						"SL_Channel_processOpenRequest - cannot create new token for an existing SecureChannel\n");
-
-			} else {
-				printf(
-						"SL_Channel_processOpenRequest - creating new token for an existing SecureChannel\n");
-			}
-
-			break;
-		}
-	}
-	switch (request->securityMode) {
-	case UA_SECURITYMODE_INVALID:
-		thisChannel->remoteNonce.data = UA_NULL;
-		thisChannel->remoteNonce.length = -1;
-		printf("SL_Channel_processOpenRequest - client demands no security \n");
-		break;
-
-	case UA_SECURITYMODE_SIGN:
-		printf("SL_Channel_processOpenRequest - client demands signed \n");
-		//TODO check if senderCertificate and ReceiverCertificateThumbprint are present
-		break;
-
-	case UA_SECURITYMODE_SIGNANDENCRYPT:
-		printf(
-				"SL_Channel_processOpenRequest - client demands signed & encrypted \n");
-		//TODO check if senderCertificate and ReceiverCertificateThumbprint are present
-		break;
-	}
-	UA_ByteString_copy(&request->clientNonce, &thisChannel->remoteNonce);
-	thisChannel->state = UA_SL_CHANNEL_OPEN;
-
-	if (request->requestHeader.returnDiagnostics != 0) {
-		printf("SL_openSecureChannel - diagnostics demanded by the client\n");
-		printf(
-				"SL_openSecureChannel - retrieving diagnostics not implemented!\n");
-		//TODO fill with demanded information part 4, 7.8 - Table 123
-		response->responseHeader.serviceDiagnostics.encodingMask = 0;
-	} else {
-		response->responseHeader.serviceDiagnostics.encodingMask = 0;
-	}
-
-	response->serverProtocolVersion = protocolVersion;
-	UA_ChannelSecurityToken_copy(&channel->securityToken, &(response->securityToken));
-	UA_ByteString_copy(&thisChannel->localNonce, &response->serverNonce);
-
-	return retval;
-}
-
-UA_Int32 SL_Channel_processCloseRequest(SL_Channel *channel,
-		const UA_CloseSecureChannelRequest* request) {
-	SL_Channel_setState(channel, UA_SL_CHANNEL_CLOSED);
-	return UA_SUCCESS;
-}
-

+ 0 - 65
src/ua_channel.h

@@ -1,65 +0,0 @@
-#ifndef UA_CHANNEL_H_
-#define UA_CHANNEL_H_
-
-#include <stdio.h>
-#include <memory.h> // memcpy
-
-#include "ua_transport_connection.h"
-
-typedef enum ChannelState {
-	UA_SL_CHANNEL_CLOSING,
-	UA_SL_CHANNEL_CLOSED,
-	UA_SL_CHANNEL_OPENING,
-	UA_SL_CHANNEL_OPEN
-} SL_channelState;
-
-//hide object behind typedef
-struct SL_Channel;
-typedef struct SL_Channel SL_Channel;
-
-typedef UA_Int32 (*SL_ChannelSecurityTokenProvider)(SL_Channel*, UA_Int32,
-		         SecurityTokenRequestType, UA_ChannelSecurityToken*);
-typedef UA_Int32 (*SL_ChannelIdProvider)(UA_UInt32*);
-UA_Int32 SL_Channel_new(SL_Channel **channel);
-
-UA_Int32 SL_Channel_init(SL_Channel *channel, UA_TL_Connection *connection,
-		SL_ChannelIdProvider channelIdProvider,
-		SL_ChannelSecurityTokenProvider tokenProvider);
-
-UA_Int32 SL_Channel_bind(SL_Channel *channel, UA_TL_Connection *connection);
-UA_Int32 SL_Channel_setRemoteSecuritySettings(SL_Channel *channel,
-		UA_AsymmetricAlgorithmSecurityHeader *asymSecHeader,
-		UA_SequenceHeader *sequenceHeader);
-
-UA_Int32 SL_Channel_initLocalSecuritySettings(SL_Channel *channel);
-UA_Int32 SL_Channel_delete(SL_Channel *channel);
-UA_Int32 SL_Channel_deleteMembers(SL_Channel *channel);
-UA_Int32 SL_Channel_renewToken(SL_Channel *channel, UA_UInt32 tokenId,
-		UA_DateTime revisedLifetime, UA_DateTime createdAt);
-
-UA_Int32 SL_Channel_processOpenRequest(SL_Channel *channel, const UA_OpenSecureChannelRequest* request,
-									   UA_OpenSecureChannelResponse* response);
-UA_Int32 SL_Channel_processCloseRequest(SL_Channel *channel, const UA_CloseSecureChannelRequest* request);
-UA_Int32 SL_Channel_registerTokenProvider(SL_Channel *channel, SL_ChannelSecurityTokenProvider provider);
-UA_Int32 SL_Channel_registerChannelIdProvider(SL_ChannelIdProvider provider);
-UA_Int32 SL_Channel_checkRequestId(SL_Channel *channel, UA_UInt32 requestId);
-UA_Int32 SL_Channel_checkSequenceNumber(SL_Channel *channel, UA_UInt32 sequenceNumber);
-UA_Boolean SL_Channel_compare(SL_Channel *channel1, SL_Channel *channel2);
-
-//getters
-UA_Int32 SL_Channel_getChannelId(SL_Channel *channel, UA_UInt32 *channelId);
-UA_Int32 SL_Channel_getTokenId(SL_Channel *channel, UA_UInt32 *tokenlId);
-UA_Int32 SL_Channel_getSequenceNumber(SL_Channel *channel, UA_UInt32 *sequenceNumber);
-UA_Int32 SL_Channel_getRequestId(SL_Channel *channel, UA_UInt32 *requestId);
-UA_Int32 SL_Channel_getConnectionId(SL_Channel *channel, UA_UInt32 *connectionId);
-UA_Int32 SL_Channel_getConnection(SL_Channel *channel, UA_TL_Connection **connection);
-UA_Int32 SL_Channel_getState(SL_Channel *channel, SL_channelState *channelState);
-UA_Int32 SL_Channel_getLocalAsymAlgSettings(SL_Channel *channel,
-		UA_AsymmetricAlgorithmSecurityHeader **asymAlgSettings);
-UA_Int32 SL_Channel_getRemainingLifetime(SL_Channel *channel, UA_Int32 *lifetime);
-UA_Int32 SL_Channel_getRevisedLifetime(SL_Channel *channel, UA_UInt32 *revisedLifetime);
-
-//setters
-UA_Int32 SL_Channel_setId(SL_Channel *channel, UA_UInt32 id);
-
-#endif /* UA_CHANNEL_H_ */

+ 44 - 0
src/ua_connection.c

@@ -0,0 +1,44 @@
+#include "ua_connection.h"
+
+UA_ConnectionConfig UA_ConnectionConfig_standard = {.protocolVersion = 0, .sendBufferSize = 8192,
+													.recvBufferSize = 8192, .maxMessageSize = 8192,
+													.maxChunkCount = 1};
+
+UA_Int32 UA_ByteStringArray_init(UA_ByteStringArray *stringarray, UA_UInt32 length) {
+	if(!stringarray || length == 0)
+		return UA_ERROR;
+	if(UA_alloc((void**)&stringarray->strings, sizeof(UA_String) * length) != UA_SUCCESS)
+		return UA_ERROR;
+	for(UA_UInt32 i=0;i<length;i++)
+		UA_String_init(&stringarray->strings[i]);
+	stringarray->stringsSize = length;
+	return UA_ERROR;
+}
+
+UA_Int32 UA_ByteStringArray_deleteMembers(UA_ByteStringArray *stringarray) {
+	if(!stringarray)
+		return UA_ERROR;
+	for(UA_UInt32 i=0;i<stringarray->stringsSize;i++)
+		UA_String_deleteMembers(&stringarray->strings[i]);
+	UA_free(stringarray);
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_Connection_init(UA_Connection *connection,
+								  UA_ConnectionConfig localConf,
+								  void *callbackHandle,
+								  UA_Int32 (*close)(void *handle),
+								  UA_Int32 (*write)(void *handle, UA_ByteStringArray *buf)) {
+	connection->state = UA_CONNECTION_OPENING;
+	connection->localConf = localConf;
+	connection->channel = UA_NULL;
+	connection->callbackHandle = callbackHandle;
+	connection->close = close;
+	connection->write = write;
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_Connection_deleteMembers(UA_Connection *connection) {
+	UA_free(connection->callbackHandle);
+	return UA_SUCCESS;
+}

+ 56 - 0
src/ua_connection.h

@@ -0,0 +1,56 @@
+#ifndef UA_CONNECTION_H_
+#define UA_CONNECTION_H_
+
+#include "ua_transport.h"
+
+/* used for zero-copy communication. the array of bytestrings is sent over the
+   network as a single buffer. */
+typedef struct UA_ByteStringArray {
+	UA_UInt32 stringsSize;
+	UA_ByteString *strings;
+} UA_ByteStringArray;
+
+UA_Int32 UA_ByteStringArray_init(UA_ByteStringArray *stringarray, UA_UInt32 length);
+UA_Int32 UA_ByteStringArray_deleteMembers(UA_ByteStringArray *stringarray);
+
+typedef enum UA_ConnectionState {
+	UA_CONNECTION_OPENING,
+	UA_CONNECTION_CLOSING,
+	UA_CONNECTION_ESTABLISHED
+} UA_ConnectionState;
+
+typedef struct UA_ConnectionConfig {
+	UA_UInt32 protocolVersion;
+	UA_UInt32 sendBufferSize;
+	UA_UInt32 recvBufferSize;
+	UA_UInt32 maxMessageSize;
+	UA_UInt32 maxChunkCount;
+} UA_ConnectionConfig;
+
+extern UA_ConnectionConfig UA_ConnectionConfig_standard;
+
+/* Forward declaration */
+struct UA_SecureChannel;
+typedef struct UA_SecureChannel UA_SecureChannel;
+
+typedef UA_Int32 (*UA_Connection_writeCallback)(void *handle, UA_ByteStringArray *buf);
+typedef UA_Int32 (*UA_Connection_closeCallback)(void *handle);
+
+typedef struct UA_Connection {
+	UA_ConnectionState state;
+	UA_ConnectionConfig localConf;
+	UA_ConnectionConfig remoteConf;
+	UA_SecureChannel *channel;
+	void *callbackHandle;
+	UA_Connection_writeCallback write;
+	UA_Connection_closeCallback close;
+} UA_Connection;
+
+UA_Int32 UA_Connection_init(UA_Connection *connection, UA_ConnectionConfig localConf,
+							void *callbackHandle, UA_Int32 (*close)(void *handle),
+							UA_Int32 (*write)(void *handle, UA_ByteStringArray *buf));
+UA_Int32 UA_Connection_deleteMembers(UA_Connection *connection);
+
+// todo: closing a binaryconnection that was closed on the network level
+	
+#endif /* UA_CONNECTION_H_ */

+ 63 - 0
src/ua_securechannel.c

@@ -0,0 +1,63 @@
+#include <time.h>
+#include <stdlib.h>
+#include "ua_securechannel.h"
+
+UA_Int32 UA_SecureChannel_init(UA_SecureChannel *channel) {
+	UA_AsymmetricAlgorithmSecurityHeader_init(&channel->clientAsymAlgSettings);
+	UA_AsymmetricAlgorithmSecurityHeader_init(&channel->serverAsymAlgSettings);
+	UA_ByteString_init(&channel->clientNonce);
+	UA_ByteString_init(&channel->serverNonce);
+	channel->connection = UA_NULL;
+	channel->session = UA_NULL;
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_SecureChannel_deleteMembers(UA_SecureChannel *channel) {
+	UA_Int32 retval = UA_SUCCESS;
+	retval |= UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->serverAsymAlgSettings);
+	retval |= UA_ByteString_deleteMembers(&channel->serverNonce);
+	retval |= UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->clientAsymAlgSettings);
+	retval |= UA_ByteString_deleteMembers(&channel->clientNonce);
+	retval |= UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
+	return retval;
+}
+UA_Int32 UA_SecureChannel_delete(UA_SecureChannel *channel) {
+	UA_Int32 retval = UA_SUCCESS;
+	retval = UA_SecureChannel_deleteMembers(channel);
+	retval = UA_free(channel);
+	return retval;
+}
+
+UA_Boolean UA_SecureChannel_compare(UA_SecureChannel *sc1, UA_SecureChannel *sc2) {
+	return (sc1->securityToken.channelId == sc2->securityToken.channelId) ?
+			UA_TRUE : UA_FALSE;
+}
+
+//TODO implement real nonce generator - DUMMY function
+UA_Int32 UA_SecureChannel_generateNonce(UA_ByteString *nonce) {
+	//UA_ByteString_new(&nonce);
+	UA_alloc((void** )&nonce->data, 1);
+	nonce->length = 1;
+	nonce->data[0] = 'a';
+	return UA_SUCCESS;
+}
+
+UA_Int32 UA_SecureChannel_updateRequestId(UA_SecureChannel *channel, UA_UInt32 requestId) {
+	//TODO review checking of request id
+	if (channel->requestId+1  == requestId) {
+		channel->requestId++;
+		return UA_SUCCESS;
+	}
+	return UA_ERROR;
+}
+
+UA_Int32 UA_SecureChannel_updateSequenceNumber(UA_SecureChannel *channel,
+											  UA_UInt32 sequenceNumber) {
+	//TODO review checking of sequence
+	if (channel->sequenceNumber+1  == sequenceNumber) {
+		channel->sequenceNumber++;
+		return UA_SUCCESS;
+	}
+	return UA_ERROR;
+
+}

+ 42 - 0
src/ua_securechannel.h

@@ -0,0 +1,42 @@
+#ifndef UA_SECURECHANNEL_H_
+#define UA_SECURECHANNEL_H_
+
+#include <stdio.h>
+#include <memory.h> // memcpy
+
+#include "ua_types_generated.h"
+#include "ua_transport.h"
+#include "ua_connection.h"
+
+/**
+ *  @ingroup internal
+ *
+ *  @defgroup securechannel SecureChannel
+ */
+
+struct UA_Session;
+typedef struct UA_Session UA_Session;
+
+struct UA_SecureChannel {
+	UA_MessageSecurityMode securityMode;
+	UA_ChannelSecurityToken securityToken; // the channelId is contained in the securityToken
+	UA_AsymmetricAlgorithmSecurityHeader clientAsymAlgSettings;
+	UA_AsymmetricAlgorithmSecurityHeader serverAsymAlgSettings;
+	UA_ByteString clientNonce;
+	UA_ByteString serverNonce;
+	UA_UInt32 requestId;
+	UA_UInt32 sequenceNumber;
+	UA_Connection *connection; // make this more generic when http connections exist
+	UA_Session *session;
+};
+
+UA_Int32 UA_SecureChannel_init(UA_SecureChannel *channel);
+UA_Int32 UA_SecureChannel_deleteMembers(UA_SecureChannel *channel);
+UA_Int32 UA_SecureChannel_delete(UA_SecureChannel *channel);
+UA_Boolean UA_SecureChannel_compare(UA_SecureChannel *sc1, UA_SecureChannel *sc2);
+
+UA_Int32 UA_SecureChannel_generateNonce(UA_ByteString *nonce);
+UA_Int32 UA_SecureChannel_updateRequestId(UA_SecureChannel *channel, UA_UInt32 requestId);
+UA_Int32 UA_SecureChannel_updateSequenceNumber(UA_SecureChannel *channel, UA_UInt32 sequenceNumber);
+
+#endif /* UA_SECURECHANNEL_H_ */

+ 23 - 112
src/ua_session.c

@@ -3,18 +3,13 @@
 
 #include "ua_session.h"
 
-struct UA_Session {
-	UA_NodeId authenticationToken;
-	UA_NodeId sessionId;
-	UA_String name;
-	UA_Application *application;
-//	UA_list_List pendingRequests;
-	SL_Channel *channel;
-	UA_UInt32 maxRequestMessageSize;
-	UA_UInt32 maxResponseMessageSize;
-	UA_Int64 timeout;
-	UA_DateTime validTill;
-};
+UA_Int32 UA_Session_new(UA_Session **session) {
+	UA_Int32 retval = UA_SUCCESS;
+	retval |= UA_alloc((void**)session, sizeof(UA_Session));
+	if(retval == UA_SUCCESS)
+		UA_Session_init(*session);
+	return retval;
+}
 
 /* mock up function to generate tokens for authentication */
 UA_Int32 UA_Session_generateToken(UA_NodeId *newToken) {
@@ -43,31 +38,27 @@ UA_Int32 UA_Session_generateToken(UA_NodeId *newToken) {
 	return retval;
 }
 
-UA_Int32 UA_Session_bind(UA_Session *session, SL_Channel *channel) {
-	if(!channel || !session)
+UA_Int32 UA_Session_init(UA_Session *session){
+	if(!session)
 		return UA_ERROR;
-
-	session->channel = channel;
+	
+	UA_NodeId_init(&session->authenticationToken);
+	UA_NodeId_init(&session->sessionId);
+	UA_String_init(&session->sessionName);
+	session->maxRequestMessageSize = 0;
+	session->maxResponseMessageSize = 0;
+	session->timeout = 0;
+	UA_DateTime_init(&session->validTill);
+	session->channel = UA_NULL;
 	return UA_SUCCESS;
 }
 
-UA_Int32 UA_Session_new(UA_Session **newSession) {
-	UA_Int32 retval = UA_SUCCESS;
-	UA_Session *session;
-
-	retval |= UA_alloc((void**)&session,sizeof(UA_Session));
-	retval |= UA_alloc((void**)session,sizeof(UA_Session));
-	*newSession = session;
-	**newSession = *session;
-	//get memory for request list
-	return retval;
-}
-
 UA_Int32 UA_Session_deleteMembers(UA_Session *session) {
 	UA_Int32 retval = UA_SUCCESS;
 	retval |= UA_NodeId_deleteMembers(&session->authenticationToken);
-	retval |= UA_String_deleteMembers(&session->name);
 	retval |= UA_NodeId_deleteMembers(&session->sessionId);
+	retval |= UA_String_deleteMembers(&session->sessionName);
+	session->channel = UA_NULL;
 	return retval;
 }
 
@@ -78,60 +69,13 @@ UA_Int32 UA_Session_delete(UA_Session *session) {
 	return retval;
 }
 
-UA_Int32 UA_Session_init(UA_Session *session, UA_String *sessionName, UA_Double requestedSessionTimeout,
-		UA_UInt32 maxRequestMessageSize,
-		UA_UInt32 maxResponseMessageSize,
-		UA_Session_idProvider idProvider,
-		UA_Int64 timeout){
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_String_copy(sessionName, &session->name);
-	session->maxRequestMessageSize = maxRequestMessageSize;
-	session->maxResponseMessageSize = maxResponseMessageSize;
-
-	UA_Session_generateToken(&session->authenticationToken);
-
-	idProvider(&session->sessionId);
-	session->timeout = requestedSessionTimeout > timeout ? timeout : requestedSessionTimeout;
-
-	UA_Session_updateLifetime(session);
-	return retval;
-}
-
 UA_Boolean UA_Session_compare(UA_Session *session1, UA_Session *session2) {
-	if(session1 && session2) {
-		if (UA_NodeId_equal(&session1->sessionId, &session2->sessionId) == UA_EQUAL) {
+	if(session1 && session2 &&
+	   UA_NodeId_equal(&session1->sessionId, &session2->sessionId) == UA_EQUAL)
 			return UA_TRUE;
-		}
-	}
 	return UA_FALSE;
 }
 
-UA_Boolean UA_Session_compareByToken(UA_Session *session, UA_NodeId *token) {
-	if(session && token) {
-		return UA_NodeId_equal(&session->authenticationToken, token);
-	}
-	return UA_NOT_EQUAL;
-}
-
-UA_Boolean UA_Session_compareById(UA_Session *session, UA_NodeId *sessionId) {
-	if(session && sessionId) {
-		return UA_NodeId_equal(&session->sessionId, sessionId);
-	}
-	return UA_NOT_EQUAL;
-}
-
-UA_Int32 UA_Session_getId(UA_Session *session, UA_NodeId *sessionId) {
-	if(!session)
-		return UA_ERROR;
-	return UA_NodeId_copy(&session->sessionId, sessionId);
-}
-
-UA_Int32 UA_Session_getToken(UA_Session *session, UA_NodeId *authenticationToken) {
-	if(!session)
-		return UA_ERROR;
-	return UA_NodeId_copy(&session->authenticationToken, authenticationToken);
-}
-
 UA_Int32 UA_Session_updateLifetime(UA_Session *session) {
 	if(!session)
 		return UA_ERROR;
@@ -140,43 +84,10 @@ UA_Int32 UA_Session_updateLifetime(UA_Session *session) {
 	return UA_SUCCESS;
 }
 
-UA_Int32 UA_Session_getChannel(UA_Session *session, SL_Channel **channel) {
-	if(!session)
-		return UA_ERROR;
-
-	*channel = session->channel;
-	return UA_SUCCESS;
-}
-
 UA_Int32 UA_Session_getPendingLifetime(UA_Session *session, UA_Double *pendingLifetime_ms) {
 	if(!session)
 		return UA_ERROR;
 
-	*pendingLifetime_ms = (session->validTill- UA_DateTime_now() ) / 10000000; //difference in ms
-	return UA_SUCCESS;
-}
-
-UA_Boolean UA_Session_verifyChannel(UA_Session *session, SL_Channel *channel) {
-	if(!session || !channel)
-		return UA_FALSE;
-
-	return SL_Channel_compare(session->channel, channel);
-}
-
-UA_Int32 UA_Session_getApplicationPointer(UA_Session *session, UA_Application** application) {
-	if(!session) {
-		*application = UA_NULL;
-		return UA_ERROR;
-	}
-
-	*application = session->application;
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_Session_setApplicationPointer(UA_Session *session, UA_Application* application) {
-	if(!session)
-		return UA_ERROR;
-
-	session->application = application;
+	*pendingLifetime_ms = (session->validTill - UA_DateTime_now())/10000000; //difference in ms
 	return UA_SUCCESS;
 }

+ 22 - 114
src/ua_session.h

@@ -1,131 +1,39 @@
 #ifndef UA_SESSION_H_
 #define UA_SESSION_H_
 
-#include "ua_channel.h"
-
-struct UA_Session;
-typedef struct UA_Session UA_Session;
-typedef UA_Int32(*UA_Session_idProvider)(UA_NodeId *newSessionId);
+#include "ua_types.h"
+#include "ua_securechannel.h"
 
 /**
- * @brief creates a session object
- * @param newSession
- * @return error code
+ *  @ingroup internal
+ *
+ *  @defgroup session Session
  */
-UA_Int32 UA_Session_new(UA_Session **newSession);
 
-/**
- * @brief inits a session object
- * @param session
- * @param sessionName
- * @param requestedSessionTimeout
- * @param maxRequestMessageSize
- * @param maxResponseMessageSize
- * @param idProvider
- * @param timeout
- * @return error code
- */
-UA_Int32 UA_Session_init(UA_Session *session, UA_String *sessionName, UA_Double requestedSessionTimeout,
-		UA_UInt32 maxRequestMessageSize,
-		UA_UInt32 maxResponseMessageSize,
-		UA_Session_idProvider idProvider,
-		UA_Int64 timeout);
+struct UA_Session {
+	UA_ApplicationDescription clientDescription;
+	UA_String sessionName;
+	UA_NodeId authenticationToken;
+	UA_NodeId sessionId;
+	UA_UInt32 maxRequestMessageSize;
+	UA_UInt32 maxResponseMessageSize;
+	UA_Int64 timeout;
+	UA_DateTime validTill;
+	UA_SecureChannel *channel;
+};
 
+UA_Int32 UA_Session_new(UA_Session **session);
+UA_Int32 UA_Session_init(UA_Session *session);
 UA_Int32 UA_Session_delete(UA_Session *session);
+UA_Int32 UA_Session_deleteMembers(UA_Session *session);
 
-/**
- * @brief compares two session objects
- * @param session1
- * @param session2
- * @return UA_TRUE if it is the same session, UA_FALSE else
- */
+/** Compares two session objects */
 UA_Boolean UA_Session_compare(UA_Session *session1, UA_Session *session2);
 
-/**
- * @brief compares two sessions by their authentication token
- * @param session
- * @param token
- * @return UA_EQUAL if the session token matches the session UA_NOT_EQUAL
- */
-UA_Boolean UA_Session_compareByToken(UA_Session *session, UA_NodeId *token);
-
-/**
- * @brief compares two sessions by their session id
- * @param session
- * @param sessionId
- * @return UA_EQUAL if the session identifier matches the session UA_NOT_EQUAL
- */
-UA_Boolean UA_Session_compareById(UA_Session *session, UA_NodeId *sessionId);
-
-/**
- * @brief binds a channel to a session
- * @param session
- * @param channel
- * @return error code
- */
-UA_Int32 UA_Session_bind(UA_Session *session, SL_Channel *channel);
-
-/**
- * @brief checks if the given channel is related to the session
- * @param session
- * @param channel
- * @return UA_TRUE if there is a relation between session and given channel
- */
-UA_Boolean UA_Session_verifyChannel(UA_Session *session, SL_Channel *channel);
-
-/**
- * @brief If any activity on a session happens, the timeout must be extended
- * @param session
- * @return error code
- */
+/** If any activity on a session happens, the timeout must be extended */
 UA_Int32 UA_Session_updateLifetime(UA_Session *session);
 
-/**
- * @brief Gets the session identifier (UA_NodeId)
- * @param session session from which the identifier should be returned
- * @param sessionId return value
- * @return error code
- */
-UA_Int32 UA_Session_getId(UA_Session *session, UA_NodeId *sessionId);
-
-/**
- * @brief Gets the session authentication token
- * @param session session from which the token should be returned
- * @param authenticationToken return value
- * @return error code
- */
-UA_Int32 UA_Session_getToken(UA_Session *session, UA_NodeId *authenticationToken);
-
-/**
- * @brief Gets the channel on which the session is currently running
- * @param session session from which the channel should be returned
- * @param channel return value
- * @return
- */
-UA_Int32 UA_Session_getChannel(UA_Session *session, SL_Channel **channel);
-
-/**
- * @brief Gets the sessions pending lifetime (calculated from the timeout which was set)
- * @param session session from which the lifetime should be returned
- * @param pendingLifetime return value
- * @return error code
- */
+/** Gets the sessions pending lifetime (calculated from the timeout which was set) */
 UA_Int32 UA_Session_getPendingLifetime(UA_Session *session,UA_Double *pendingLifetime);
 
-/**
- * @brief Gets the pointer to the application
- * @param session session from which the application pointer should be returned
- * @param application return value
- * @return  error code
- */
-UA_Int32 UA_Session_getApplicationPointer(UA_Session *session, UA_Application** application);
-
-/**
- * @brief Sets the application pointer to the application
- * @param session session of which the application pointer should be set
- * @param application return value
- * @return error code
- */
-UA_Int32 UA_Session_setApplicationPointer(UA_Session *session, UA_Application* application);
-
 #endif /* UA_SESSION_H_ */

+ 7 - 8
src/ua_transport.c

@@ -1,15 +1,15 @@
+#include <stdio.h>
 #include "ua_transport.h"
-#include "ua_types_encoding_binary.h"
-#include "stdio.h"
+#include "ua_namespace_0.h" // for the vtable UA_
 
 UA_TYPE_DEFAULT(UA_MessageType)
-UA_Int32 UA_MessageType_calcSize(UA_MessageType const * ptr){
-	if(ptr==UA_NULL){return sizeof(UA_MessageType);}
+UA_Int32 UA_MessageType_calcSize(UA_MessageType const * ptr) {
+	if(ptr==UA_NULL) {return sizeof(UA_MessageType);}
 	return 0
 	 + 3 * sizeof(UA_Byte);
 }
 
-UA_Int32 UA_MessageType_encodeBinary(UA_MessageType const * src, UA_ByteString* dst, UA_UInt32 *offset){
+UA_Int32 UA_MessageType_encodeBinary(UA_MessageType const * src, UA_ByteString* dst, UA_UInt32 *offset) {
 	UA_Int32 retval = UA_SUCCESS;
 	UA_Byte tmpBuf[3];
 	tmpBuf[0] = (UA_Byte)((((UA_Int32)*src) >> 16) );
@@ -22,7 +22,7 @@ UA_Int32 UA_MessageType_encodeBinary(UA_MessageType const * src, UA_ByteString*
 	return retval;
 }
 
-UA_Int32 UA_MessageType_decodeBinary(UA_ByteString const * src, UA_UInt32 *offset, UA_MessageType* dst){
+UA_Int32 UA_MessageType_decodeBinary(UA_ByteString const * src, UA_UInt32 *offset, UA_MessageType* dst) {
 	UA_Int32 retval = UA_SUCCESS;
 	UA_Byte tmpBuf[3];
 	retval |= UA_Byte_decodeBinary(src,offset,&(tmpBuf[0])); //messageType to Byte representation
@@ -429,8 +429,7 @@ UA_Int32 UA_SequenceHeader_copy(const UA_SequenceHeader *src,UA_SequenceHeader *
 
 UA_Int32 UA_SecureConversationMessageFooter_calcSizeBinary(UA_SecureConversationMessageFooter const * ptr) {
     	if(ptr==UA_NULL) return sizeof(UA_SecureConversationMessageFooter);
-    	return 0
-		+ UA_Array_calcSizeBinary(ptr->paddingSize,&UA_.types[UA_BYTE],ptr->padding)
+    	return 0 + UA_Array_calcSizeBinary(ptr->paddingSize, &UA_.types[UA_BYTE],ptr->padding)
 	 + sizeof(UA_Byte) // signature
 	;
 }

+ 1 - 16
src/ua_transport.h

@@ -3,21 +3,6 @@
 
 #include "ua_types.h"
 #include "ua_types_encoding_binary.h"
-#include "ua_application.h"
-
-static const UA_Int32 SL_HEADER_LENGTH = 0;
-
-typedef enum UA_ConnectionState {
-	CONNECTIONSTATE_CLOSED,
-	CONNECTIONSTATE_OPENING,
-	CONNECTIONSTATE_ESTABLISHED,
-	CONNECTIONSTATE_CLOSE
-} UA_ConnectionState;
-
-typedef struct Session {
-	UA_Int32 sessionId;
-	UA_Application *application;
-} Session;
 
 typedef enum SecurityTokenRequestType {
 	UA_SECURITYTOKEN_ISSUE = 0,
@@ -26,7 +11,7 @@ typedef enum SecurityTokenRequestType {
 
 typedef enum {
 	UA_SECURITYMODE_INVALID = 0,
-	UA_SECURITYMODE_SIGN = 1,
+	UA_SECURITYMODE_NONE = 1,
 	UA_SECURITYMODE_SIGNANDENCRYPT = 2
 } SecurityMode;
 

+ 0 - 181
src/ua_transport_binary.c

@@ -1,181 +0,0 @@
-#include "ua_transport_connection.h"
-#include <memory.h>
-#include "ua_transport_binary.h"
-#include "ua_transport.h"
-#include "ua_transport_binary_secure.h"
-#include "ua_log.h"
-
-static UA_Int32 TL_handleHello(UA_TL_Connection *connection, const UA_ByteString* msg, UA_UInt32* pos){
-	UA_Int32 retval = UA_SUCCESS;
-	UA_UInt32 tmpPos = 0;
-	UA_Int32 connectionState;
-	UA_OPCUATcpHelloMessage helloMessage;
-
-	UA_TL_Connection_getState(connection, &connectionState);
-	if (connectionState == CONNECTIONSTATE_CLOSED){
-		LOG_DEBUG(UA_LOGGERCATEGORY_CONNECTION, "TL_handleHello - extracting header information",1);
-		UA_OPCUATcpHelloMessage_decodeBinary(msg,pos,&helloMessage);
-
-		UA_TL_Connection_configByHello(connection, &helloMessage);
-		DBG_VERBOSE(printf("TL_handleHello - protocolVersion = %d \n",connection->remoteConf.protocolVersion));
-		DBG_VERBOSE(printf("TL_handleHello - recvBufferSize = %d \n",connection->remoteConf.recvBufferSize));
-		DBG_VERBOSE(printf("TL_handleHello - sendBufferSize = %d \n",connection->remoteConf.sendBufferSize));
-		DBG_VERBOSE(printf("TL_handleHello - maxMessageSize = %d \n",connection->remoteConf.maxMessageSize));
-		DBG_VERBOSE(printf("TL_handleHello - maxChunkCount = %d \n",connection->remoteConf.maxChunkCount));
-
-		// build acknowledge response
-		UA_OPCUATcpAcknowledgeMessage ackMessage;
-		TL_Buffer localConfig;
-		UA_TL_Connection_getLocalConfig(connection, &localConfig);
-		ackMessage.protocolVersion = localConfig.protocolVersion;
-		ackMessage.receiveBufferSize = localConfig.recvBufferSize;
-		ackMessage.sendBufferSize = localConfig.sendBufferSize;
-		ackMessage.maxMessageSize = localConfig.maxMessageSize;
-		ackMessage.maxChunkCount = localConfig.maxChunkCount;
-
-		UA_OPCUATcpMessageHeader ackHeader;
-		ackHeader.messageType = UA_MESSAGETYPE_ACK;
-		ackHeader.isFinal = 'F';
-
-		// encode header and message to buffer
-		tmpPos = 0;
-
-		ackHeader.messageSize = UA_OPCUATcpAcknowledgeMessage_calcSizeBinary(&ackMessage) + UA_OPCUATcpMessageHeader_calcSizeBinary(&ackHeader);
-		UA_ByteString *ack_msg;
-		UA_alloc((void **)&ack_msg, sizeof(UA_ByteString));
-		UA_ByteString_newMembers(ack_msg, ackHeader.messageSize);
-		UA_OPCUATcpMessageHeader_encodeBinary(&ackHeader,ack_msg,&tmpPos);
-		UA_OPCUATcpAcknowledgeMessage_encodeBinary(&ackMessage, ack_msg,&tmpPos);
-
-		DBG_VERBOSE(printf("TL_handleHello - Size messageToSend = %d, pos=%d\n",ackHeader.messageSize, tmpPos));
-		DBG_VERBOSE(UA_ByteString_printx("_handleHello - ack=", ack_msg));
-		TL_Send(connection, (const UA_ByteString **) &ack_msg, 1);
-		DBG_VERBOSE(printf("TL_handleHello - finished writing\n"));
-		UA_ByteString_delete(ack_msg);
-	} else {
-		DBG_ERR(printf("TL_handleHello - wrong connection state \n"));
-		retval = UA_ERROR_MULTIPLE_HEL;
-	}
-	return retval;
-}
-
-static UA_Int32 TL_handleOpen(UA_TL_Connection *connection, UA_Server *server, const UA_ByteString* msg, UA_UInt32* pos) {
-	UA_Int32 retval = UA_SUCCESS;
-	UA_Int32 state;
-	SL_Channel *channel;
-	UA_UInt32 secureChannelId;
-	retval |= UA_TL_Connection_getState(connection, &state);
-	if (state == CONNECTIONSTATE_ESTABLISHED) {
-		UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
-		SL_ChannelManager_getChannel(secureChannelId, &channel);
-		if(channel == UA_NULL)
-		{
-			SL_Channel *newChannel;
-			//create new channel
-			retval |= SL_Channel_new(&newChannel);//just create channel
-			retval |= SL_Channel_init(newChannel, connection,SL_ChannelManager_generateChannelId, SL_ChannelManager_generateToken);
-			retval |= SL_Channel_bind(newChannel,connection);
-			retval |= SL_ProcessOpenChannel(newChannel, server, msg, pos);
-			retval |= SL_ChannelManager_addChannel(newChannel);
-			return retval;
-		}
-		// channel already exists, renew token?
-		retval |= SL_ProcessOpenChannel(channel, server, msg, pos);
-		return retval;
-	}else{
-		printf("TL_handleOpen - ERROR: could not create new secureChannel");
-	}
-
-	return UA_ERR_INVALID_VALUE;
-}
-
-static UA_Int32 TL_handleMsg(UA_TL_Connection *connection, UA_Server *server, const UA_ByteString* msg, UA_UInt32* pos) {
-	UA_Int32 state;
-	UA_TL_Connection_getState(connection,&state);
-	if (state == CONNECTIONSTATE_ESTABLISHED) {
-		return SL_Process(server, msg, pos);
-	}
-	return UA_ERR_INVALID_VALUE;
-}
-
-static UA_Int32 TL_handleClo(UA_TL_Connection *connection, UA_Server *server, const UA_ByteString* msg, UA_UInt32* pos) {
-	UA_Int32 retval = UA_SUCCESS;
-	SL_Process(server, msg,pos);
-	// just prepare closing, closing and freeing structures is done elsewhere
-	// UA_TL_Connection_close(connection);
-	UA_TL_Connection_setState(connection, CONNECTIONSTATE_CLOSE);
-	return retval;
-}
-
-UA_Int32 TL_Process(UA_TL_Connection *connection, UA_Server *server, const UA_ByteString* msg) {
-	UA_Int32 retval = UA_SUCCESS;
-	UA_UInt32 pos = 0;
-	UA_OPCUATcpMessageHeader tcpMessageHeader;
-
-	DBG_VERBOSE(printf("TL_Process - entered \n"));
-	UA_Int32 messageCounter = 0;
-
-	do{
-
-		if ((retval = UA_OPCUATcpMessageHeader_decodeBinary(msg,&pos,&tcpMessageHeader)) == UA_SUCCESS) {
-			printf("TL_Process - messageType=%.*s\n",3,msg->data);
-			switch(tcpMessageHeader.messageType) {
-			case UA_MESSAGETYPE_HEL:
-				retval = TL_handleHello(connection, msg, &pos);
-				break;
-			case UA_MESSAGETYPE_OPN:
-				retval = TL_handleOpen(connection, server, msg, &pos);
-				break;
-			case UA_MESSAGETYPE_MSG:
-				retval = TL_handleMsg(connection, server, msg, &pos);
-				break;
-			case UA_MESSAGETYPE_CLO:
-				retval = TL_handleClo(connection, server, msg, &pos);
-				break;
-			default: // dispatch processing to secureLayer
-				//Invalid packet was received which could have led to a wrong offset (pos).
-				//It was not possible to extract the following packet from the buffer
-				retval = UA_ERR_INVALID_VALUE;
-				break;
-			}
-		}
-		else
-		{
-			printf("TL_Process - ERROR:decoding of header failed \n");
-		}
-
-		messageCounter++;
-		printf("TL_Process - multipleMessage in Buffer: %i \n",messageCounter);
-
-
-	}while(msg->length > (UA_Int32)pos);
-	/* if (retval != UA_SUCCESS) { */
-	/* 	// FIXME: compose real error message */
-	/* 	UA_ByteString errorMsg; */
-	/* 	UA_ByteString *errorMsg_ptr = &errorMsg; */
-	/* 	UA_ByteString_newMembers(&errorMsg,10); */
-	/* 	TL_Send(connection,(const UA_ByteString **)&errorMsg_ptr, 1); */
-	/* 	UA_ByteString_deleteMembers(&errorMsg); */
-	/* } */
-	UA_OPCUATcpMessageHeader_deleteMembers(&tcpMessageHeader);
-	return retval;
-}
-
-/** respond to client request */
-UA_Int32 TL_Send(UA_TL_Connection *connection, const UA_ByteString** gather_buf, UA_UInt32 gather_len) {
-	UA_Int32 retval = UA_SUCCESS;
-
-
-	DBG_VERBOSE(printf("TL_send - entered \n"));
-	//	if (TL_check(connection,msg,TL_CHECK_REMOTE) == UA_SUCCESS) {
-
-	retval = UA_TL_Connection_callWriter(connection, gather_buf, gather_len);
-	DBG_VERBOSE(printf("TL_send - exited \n"));
-		//}
-	/* else */
-	/* { */
-	/* 	DBG_ERR(printf("TL_send - ERROR: packet size greater than remote buffer size")); */
-	/* 	retval = UA_ERROR; */
-	/* } */
-	return retval;
-}

+ 0 - 41
src/ua_transport_binary.h

@@ -1,41 +0,0 @@
-#ifndef OPCUA_TRANSPORT_BINARY_H_
-#define OPCUA_TRANSPORT_BINARY_H_
-#include <stdio.h>
-
-
-#include "ua_transport_binary.h"
-#include "ua_transport_connection.h"
-#include "ua_server.h"
-
-//transport errors begin at 1000
-#define UA_ERROR_MULTIPLE_HEL 1000
-#define UA_ERROR_RCV_ERROR 1001
-
-//variables which belong to layer
-#define TL_SERVER_PROTOCOL_VERSION  0
-#define TL_SERVER_MAX_CHUNK_COUNT 1
-#define TL_SERVER_MAX_MESSAGE_SIZE  8192
-
-
-
-/* Transport Layer Connection */
-//struct TL_Connection_T; // forward declaration
-
-//typedef UA_Int32 (*TL_Writer)(struct TL_Connection_T* connection, const UA_ByteString** gather_bufs, UA_Int32 gather_len); // send mutiple buffer concatenated into one msg (zero copy)
-/*
-typedef struct TL_Connection_T {
-	UA_Int32 connectionHandle;
-	UA_UInt32 connectionState;
-	TL_Buffer localConf;
-	TL_Buffer remoteConf;
-	TL_Writer writerCallback;
-	UA_String localEndpointUrl;
-	UA_String remoteEndpointUrl;
-	struct SL_Channel_T* secureChannel;
-} TL_Connection;
-*/
-
-UA_Int32 TL_Send(UA_TL_Connection *connection, const UA_ByteString** gather_buf, UA_UInt32 gather_len);
-UA_Int32 TL_Process(UA_TL_Connection *connection, UA_Server *server, const UA_ByteString* msg);
-
-#endif /* OPCUA_TRANSPORT_BINARY_H_ */

+ 0 - 376
src/ua_transport_binary_secure.c

@@ -1,376 +0,0 @@
-#include <stdio.h>
-#include <memory.h> // memcpy
-
-#include "ua_transport_binary.h"
-#include "ua_transport_binary_secure.h"
-#include "ua_transport.h"
-#include "ua_statuscodes.h"
-#include "ua_services.h"
-#include "ua_session_manager.h"
-#include "ua_session.h"
-
-#define SIZE_SECURECHANNEL_HEADER 12
-#define SIZE_SEQHEADER_HEADER 8
-
-static UA_Int32 SL_Send(SL_Channel *channel, const UA_ByteString * responseMessage, UA_Int32 type) {
-	UA_UInt32 pos = 0;
-	UA_Int32 isAsym = (type == UA_OPENSECURECHANNELRESPONSE_NS0); // FIXME: this is a to dumb method to determine asymmetric algorithm setting
-	UA_UInt32 channelId;
-	UA_UInt32 sequenceNumber;
-	UA_UInt32 requestId;
-	UA_NodeId resp_nodeid;
-	UA_TL_Connection *connection;
-	UA_AsymmetricAlgorithmSecurityHeader *asymAlgSettings = UA_NULL;
-
-	resp_nodeid.namespaceIndex = 0;
-	resp_nodeid.identifierType = UA_NODEIDTYPE_NUMERIC;
-	resp_nodeid.identifier.numeric = type + 2; // binary encoding
-
-	const UA_ByteString *response_gather[2]; // securechannel_header, seq_header, security_encryption_header, message_length (eventually + padding + size_signature);
-	UA_alloc((void ** )&response_gather[0], sizeof(UA_ByteString));
-	if (isAsym) {
-		SL_Channel_getLocalAsymAlgSettings(channel, &asymAlgSettings);
-		UA_ByteString_newMembers((UA_ByteString *) response_gather[0],
-				SIZE_SECURECHANNEL_HEADER + SIZE_SEQHEADER_HEADER
-						+ UA_AsymmetricAlgorithmSecurityHeader_calcSizeBinary(
-								asymAlgSettings)
-						+ UA_NodeId_calcSizeBinary(&resp_nodeid));
-	} else {
-		UA_ByteString_newMembers((UA_ByteString *) response_gather[0], 8 + 16 + // normal header + 4*32bit secure channel information
-				UA_NodeId_calcSizeBinary(&resp_nodeid));
-	}
-
-	// sizePadding = 0;
-	// sizeSignature = 0;
-	UA_ByteString *header = (UA_ByteString *) response_gather[0];
-
-	/*---encode Secure Conversation Message Header  ---*/
-	if (isAsym) {
-		header->data[0] = 'O';
-		header->data[1] = 'P';
-		header->data[2] = 'N';
-	} else {
-		header->data[0] = 'M';
-		header->data[1] = 'S';
-		header->data[2] = 'G';
-	}
-	pos += 3;
-	header->data[pos] = 'F';
-	pos += 1;
-
-	UA_Int32 packetSize = response_gather[0]->length + responseMessage->length;
-	UA_Int32_encodeBinary(&packetSize, header,&pos);
-
-	//use get accessor to read the channel Id
-	SL_Channel_getChannelId(channel, &channelId);
-
-	UA_UInt32_encodeBinary(&channelId, header,&pos);
-
-	/*---encode Algorithm Security Header ---*/
-	if (isAsym) {
-		UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(asymAlgSettings, header,&pos);
-		UA_free(asymAlgSettings);
-	} else {
-		UA_UInt32 tokenId = 0;
-		SL_Channel_getTokenId(channel, &tokenId);
-		UA_UInt32_encodeBinary(&tokenId, header,&pos);
-	}
-
-	/*---encode Sequence Header ---*/
-	SL_Channel_getSequenceNumber(channel, &sequenceNumber);
-	UA_UInt32_encodeBinary(&sequenceNumber, header, &pos);
-	SL_Channel_getRequestId(channel, &requestId);
-	UA_UInt32_encodeBinary(&requestId, header,&pos);
-
-	/*---add payload type---*/
-	UA_NodeId_encodeBinary(&resp_nodeid, header,&pos);
-
-	/*---add encoded Message ---*/
-	response_gather[1] = responseMessage; // is deleted in the calling function
-
-	/* sign Data*/
-
-	/* encrypt Data*/
-
-	/* send Data */
-	SL_Channel_getConnection(channel, &connection);
-	TL_Send(connection, response_gather, 2);
-
-	UA_ByteString_delete((UA_ByteString *) response_gather[0]);
-	return UA_SUCCESS;
-}
-
-static void init_response_header(UA_RequestHeader const * p, UA_ResponseHeader * r) {
-	r->requestHandle = p->requestHandle;
-	r->serviceResult = UA_STATUSCODE_GOOD;
-	r->stringTableSize = 0;
-	r->timestamp = UA_DateTime_now();
-}
-
-#define RESPONSE_PREPARE(TYPE) \
-	UA_##TYPE##Request p; \
-	UA_##TYPE##Response r; \
-	UA_Session *session = UA_NULL; \
-	UA_##TYPE##Request_decodeBinary(msg, &recvOffset, &p); \
-	UA_##TYPE##Response_init(&r); \
-	init_response_header(&p.requestHeader, &r.responseHeader); \
-	UA_SessionManager_getSessionByToken(&p.requestHeader.authenticationToken, &session); \
-	DBG_VERBOSE(printf("Invoke Service: %s\n", #TYPE)); \
-
-#define INVOKE_SERVICE(TYPE) \
-	UA_##TYPE##Request p; \
-	UA_##TYPE##Response r; \
-	UA_Session session = UA_NULL; \
-	UA_##TYPE##Request_decodeBinary(msg, &recvOffset, &p); \
-	UA_##TYPE##Response_init(&r); \
-	init_response_header(&p.requestHeader, &r.responseHeader); \
-	UA_SessionManager_getSessionByToken(&p.requestHeader.authenticationToken, &session); \
-	DBG_VERBOSE(printf("Invoke Service: %s\n", #TYPE)); \
-	Service_##TYPE(session, &p, &r); \
-	DBG_VERBOSE(printf("Finished Service: %s\n", #TYPE)); \
-    sendOffset = 0; \
-	UA_ByteString_newMembers(&response_msg, UA_##TYPE##Response_calcSizeBinary(&r)); \
-	UA_##TYPE##Response_encodeBinary(&r, &sendOffset, &response_msg); \
-	UA_##TYPE##Request_deleteMembers(&p); \
-	UA_##TYPE##Response_deleteMembers(&r); \
-/*
-#define INVOKE_SERVICE(TYPE) \
-		DBG_VERBOSE(printf("Invoke Service: %s\n", #TYPE)); \
-		Service_##TYPE(session, &p, &r); \
-		DBG_VERBOSE(printf("Finished Service: %s\n", #TYPE)); \
-*/
-#define RESPONSE_CLEANUP(TYPE) \
-	DBG_VERBOSE(printf("Finished Service: %s\n", #TYPE)); \
-	sendOffset = 0; \
-	UA_ByteString_newMembers(&response_msg, UA_##TYPE##Response_calcSizeBinary(&r)); \
-	UA_##TYPE##Response_encodeBinary(&r, &response_msg,&sendOffset); \
-	UA_##TYPE##Request_deleteMembers(&p); \
-	UA_##TYPE##Response_deleteMembers(&r); \
-
-
-UA_Int32 SL_handleRequest(SL_Channel *channel, UA_Server *server, const UA_ByteString* msg, UA_UInt32 *pos) {
-	UA_Int32 retval = UA_SUCCESS;
-	UA_UInt32 recvOffset = *pos;
-	UA_UInt32 sendOffset = 0;
-	// Every Message starts with a NodeID which names the serviceRequestType
-	UA_NodeId serviceRequestType;
-	UA_NodeId_decodeBinary(msg, &recvOffset,&serviceRequestType);
-#ifdef DEBUG
-	UA_NodeId_printf("SL_processMessage - serviceRequestType=",
-			&serviceRequestType);
-#endif
-	UA_ByteString response_msg;
-	UA_Int32 serviceid = serviceRequestType.identifier.numeric - 2; // binary encoding has 2 added to the id
-	UA_Int32 responsetype;
-/* stack related services which only need information about the secure Channel */
-	if (serviceid == UA_GETENDPOINTSREQUEST_NS0) {
-		RESPONSE_PREPARE(GetEndpoints);
-		Service_GetEndpoints(channel,&p, &r);
-		RESPONSE_CLEANUP(GetEndpoints);
-		//INVOKE_SERVICE(GetEndpoints);
-		responsetype = UA_GETENDPOINTSRESPONSE_NS0;
-	} else if (serviceid == UA_OPENSECURECHANNELREQUEST_NS0) {
-		RESPONSE_PREPARE(OpenSecureChannel);
-		Service_OpenSecureChannel(channel,&p, &r);
-		RESPONSE_CLEANUP(OpenSecureChannel);
-		responsetype = UA_OPENSECURECHANNELRESPONSE_NS0;
-	} else if (serviceid == UA_CLOSESECURECHANNELREQUEST_NS0) {
-		RESPONSE_PREPARE(CloseSecureChannel);
-		Service_CloseSecureChannel(channel,&p,&r);
-		RESPONSE_CLEANUP(CloseSecureChannel);
-		responsetype = UA_CLOSESECURECHANNELRESPONSE_NS0;
-	} else if (serviceid == UA_CREATESESSIONREQUEST_NS0) {
-		RESPONSE_PREPARE(CreateSession);
-		Service_CreateSession(channel, server, &p, &r);
-		RESPONSE_CLEANUP(CreateSession);
-		responsetype = UA_CREATESESSIONRESPONSE_NS0;
-	}
-/* services which need a session object */
-	else if (serviceid == UA_ACTIVATESESSIONREQUEST_NS0) {
-		RESPONSE_PREPARE(ActivateSession);
-		UA_Session_updateLifetime(session); //renew session timeout
-		Service_ActivateSession(channel, session,&p, &r);
-		RESPONSE_CLEANUP(ActivateSession);
-		responsetype = UA_ACTIVATESESSIONRESPONSE_NS0;
-	} else if (serviceid == UA_CLOSESESSIONREQUEST_NS0) {
-		RESPONSE_PREPARE(CloseSession);
-		if (UA_Session_verifyChannel(session,channel)){
-			UA_Session_updateLifetime(session); //renew session timeout
-			Service_CloseSession(session,&p, &r);
-		RESPONSE_CLEANUP(CloseSession);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		responsetype = UA_CLOSESESSIONRESPONSE_NS0;
-	} else if (serviceid == UA_READREQUEST_NS0) {
-
-		RESPONSE_PREPARE(Read);
-		UA_Session_updateLifetime(session); //renew session timeout
-		DBG_VERBOSE(printf("Finished Service: %s\n", Read));
-		if (UA_Session_verifyChannel(session,channel)){
-			UA_Session_updateLifetime(session); //renew session timeout
-			Service_Read(session,&p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", Read));
-		RESPONSE_CLEANUP(Read);
-
-		responsetype = UA_READRESPONSE_NS0;
-	} else if (serviceid == UA_WRITEREQUEST_NS0) {
-
-		RESPONSE_PREPARE(Write);
-		DBG_VERBOSE(printf("Finished Service: %s\n", Write));
-		if (UA_Session_verifyChannel(session,channel)){
-			UA_Session_updateLifetime(session); //renew session timeout
-			Service_Write(session,&p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", Write));
-		RESPONSE_CLEANUP(Write);
-		responsetype = UA_WRITERESPONSE_NS0;
-	} else if (serviceid == UA_BROWSEREQUEST_NS0) {
-		RESPONSE_PREPARE(Browse);
-		DBG_VERBOSE(printf("Finished Service: %s\n", Browse));
-		if (UA_Session_verifyChannel(session,channel)){
-			Service_Browse(session,&p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", Browse));
-		RESPONSE_CLEANUP(Browse);
-		responsetype = UA_BROWSERESPONSE_NS0;
-	} else if (serviceid == UA_CREATESUBSCRIPTIONREQUEST_NS0) {
-		RESPONSE_PREPARE(CreateSubscription);
-		DBG_VERBOSE(printf("Finished Service: %s\n", CreateSubscription));
-		if (UA_Session_verifyChannel(session,channel)){
-			Service_CreateSubscription(session, &p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", CreateSubscription));
-		RESPONSE_CLEANUP(CreateSubscription);
-		responsetype = UA_CREATESUBSCRIPTIONRESPONSE_NS0;
-	} else if (serviceid == UA_TRANSLATEBROWSEPATHSTONODEIDSREQUEST_NS0) {
-		RESPONSE_PREPARE(TranslateBrowsePathsToNodeIds);
-		DBG_VERBOSE(printf("Finished Service: %s\n", TranslateBrowsePathsToNodeIds));
-		if (UA_Session_verifyChannel(session,channel)){
-			Service_TranslateBrowsePathsToNodeIds(session, &p, &r);
-		} else {
-				DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", TranslateBrowsePathsToNodeIds));
-		RESPONSE_CLEANUP(TranslateBrowsePathsToNodeIds);
-		responsetype = UA_TRANSLATEBROWSEPATHSTONODEIDSRESPONSE_NS0;
-	} else if (serviceid == UA_PUBLISHREQUEST_NS0) {
-
-		RESPONSE_PREPARE(Publish);
-		DBG_VERBOSE(printf("Finished Service: %s\n", Publish));
-		if (UA_Session_verifyChannel(session,channel)) {
-			Service_Publish(session, &p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", Publish));
-		RESPONSE_CLEANUP(Publish);
-		responsetype = UA_PUBLISHRESPONSE_NS0;
-	} else if (serviceid == UA_CREATEMONITOREDITEMSREQUEST_NS0) {
-		RESPONSE_PREPARE(CreateMonitoredItems);
-		DBG_VERBOSE(printf("Finished Service: %s\n", CreateMonitoredItems));
-		if (UA_Session_verifyChannel(session,channel)) {
-			Service_CreateMonitoredItems(session, &p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", CreateMonitoredItems));
-		RESPONSE_CLEANUP(CreateMonitoredItems);
-		responsetype = UA_CREATEMONITOREDITEMSRESPONSE_NS0;
-	} else if (serviceid == UA_SETPUBLISHINGMODEREQUEST_NS0) {
-		RESPONSE_PREPARE(SetPublishingMode);
-		DBG_VERBOSE(printf("Finished Service: %s\n",SetPublishingMode));
-		if (UA_Session_verifyChannel(session,channel)) {
-			Service_SetPublishingMode(session, &p, &r);
-		} else {
-			DBG_VERBOSE(printf("session does not match secure channel"));
-		}
-		DBG_VERBOSE(printf("Finished Service: %s\n", SetPublishingMode));
-		RESPONSE_CLEANUP(SetPublishingMode);
-		responsetype = UA_SETPUBLISHINGMODERESPONSE_NS0;
-	} else {
-		printf("SL_processMessage - unknown request, namespace=%d, request=%d\n",
-			   serviceRequestType.namespaceIndex, serviceRequestType.identifier.numeric);
-		retval = UA_ERROR;
-		UA_RequestHeader p;
-		UA_ResponseHeader r;
-
-		UA_RequestHeader_decodeBinary(msg, &recvOffset, &p);
-		UA_ResponseHeader_init(&r);
-		r.requestHandle = p.requestHandle;
-		r.serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
-		sendOffset = 0;
-		UA_ByteString_newMembers(&response_msg, UA_ResponseHeader_calcSizeBinary(&r));
-		UA_ResponseHeader_encodeBinary(&r, &response_msg,&sendOffset);
-		responsetype = UA_RESPONSEHEADER_NS0;
-	}
-
-	if(serviceid != UA_CLOSESECURECHANNELREQUEST_NS0)
-		SL_Send(channel, &response_msg, responsetype);
-
-	UA_ByteString_deleteMembers(&response_msg);
-	*pos = recvOffset;
-	return retval;
-}
-
-UA_Int32 SL_ProcessOpenChannel(SL_Channel *channel, UA_Server *server, const UA_ByteString* msg, UA_UInt32 *pos) {
-	UA_Int32 retval = UA_SUCCESS;
-	UA_SequenceHeader sequenceHeader;
-	UA_AsymmetricAlgorithmSecurityHeader asymHeader;
-	UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg,pos,&asymHeader);
-	UA_SequenceHeader_decodeBinary(msg,pos,&sequenceHeader);
-
-	//init remote security settings from the security header
-	SL_Channel_setRemoteSecuritySettings(channel,&asymHeader,&sequenceHeader);
-	return SL_handleRequest(channel, server, msg, pos) | retval;
-}
-
-/* not used anymore */
-//UA_Int32 SL_ProcessCloseChannel(SL_Channel *channel, const UA_ByteString* msg,
-//		UA_UInt32 *pos)
-//{
-//	return SL_handleRequest(channel, msg, pos);
-//}
-
-UA_Int32 SL_Process(UA_Server *server, const UA_ByteString* msg, UA_UInt32* pos) {
-	DBG_VERBOSE(printf("SL_process - entered \n"));
-	UA_UInt32 secureChannelId;
-	UA_UInt32 foundChannelId;
-	SL_Channel *channel;
-	UA_SequenceHeader sequenceHeader;
-
-	UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
-
-	//FIXME: we assume SAS, need to check if AAS or SAS
-	UA_SymmetricAlgorithmSecurityHeader symAlgSecHeader;
-	// if (connection->securityMode == UA_MESSAGESECURITYMODE_NONE) {
-	UA_SymmetricAlgorithmSecurityHeader_decodeBinary(msg, pos, &symAlgSecHeader);
-
- 	if (SL_ChannelManager_getChannel(secureChannelId, &channel) == UA_SUCCESS) {
-		SL_Channel_getChannelId(channel, &foundChannelId);
-		printf("SL_process - received msg, with channel id: %i \n", foundChannelId);
-
-		//sequence number processing
-		UA_SequenceHeader_decodeBinary(msg, pos, &sequenceHeader);
-		SL_Channel_checkSequenceNumber(channel,sequenceHeader.sequenceNumber);
-		SL_Channel_checkRequestId(channel,sequenceHeader.requestId);
-		//request id processing
-
-		SL_handleRequest(channel, server, msg, pos);
-	} else {
-		printf("SL_process - ERROR could not find channel with id: %i \n",
-				secureChannelId);
-		//TODO generate ERROR_Bad_SecureChannelUnkown
-	}
-
-	return UA_SUCCESS;
-}

+ 0 - 22
src/ua_transport_binary_secure.h

@@ -1,22 +0,0 @@
-#ifndef OPCUA_TRANSPORT_BINARY_SECURE_H_
-#define OPCUA_TRANSPORT_BINARY_SECURE_H_
-#include "ua_types.h"
-#include "ua_transport.h"
-#include "ua_transport_binary.h"
-#include "ua_channel.h"
-#include "ua_channel_manager.h"
-#include "ua_server.h"
-
-UA_Int32 SL_Process(UA_Server *server, const UA_ByteString* msg, UA_UInt32* pos);
-
-/**
- * @brief Wrapper function, to encapsulate handleRequest for openSecureChannel requests
- * @param channel A secure Channel structure, which receives the information for the new created secure channel
- * @param msg Message which holds the binary encoded request
- * @param pos Position in the message at which the request begins
- * @return Returns UA_SUCCESS if successful executed, UA_ERROR in any other case
- */
-UA_Int32 SL_ProcessOpenChannel(SL_Channel *channel, UA_Server *server, const UA_ByteString* msg, UA_UInt32 *pos);
-UA_Int32 SL_ProcessCloseChannel(SL_Channel *channel, const UA_ByteString* msg, UA_UInt32 *pos);
-
-#endif /* OPCUA_TRANSPORT_BINARY_SECURE_H_ */

+ 0 - 143
src/ua_transport_connection.c

@@ -1,143 +0,0 @@
-#include "ua_transport_connection.h"
-#include "ua_transport.h"
-
-struct UA_TL_Connection {
-	UA_Int32 connectionHandle;
-	UA_UInt32 state;
-	TL_Buffer localConf;
-	TL_Buffer remoteConf;
-	TL_Writer writer;
-	UA_String localEndpointUrl;
-	UA_String remoteEndpointUrl;
-	TL_Closer closeCallback;
-	void *networkLayerData;
-};
-
-UA_Int32 UA_TL_Connection_new(UA_TL_Connection **connection, TL_Buffer localBuffers,TL_Writer writer,
-		                      TL_Closer closeCallback,UA_Int32 handle, void* networkLayerData) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_alloc((void**)connection,sizeof(UA_TL_Connection));
-	if(retval == UA_SUCCESS) {
-		(*connection)->connectionHandle = handle;
-		(*connection)->localConf = localBuffers;
-		(*connection)->writer = writer;
-		(*connection)->closeCallback = closeCallback;
-		(*connection)->state = CONNECTIONSTATE_CLOSED;
-		(*connection)->networkLayerData = networkLayerData;
-	}
-	return retval;
-}
-
-UA_Int32 UA_TL_Connection_delete(UA_TL_Connection *connection) {
-	UA_Int32 retval = UA_SUCCESS;
-	retval |= UA_free((void*)connection);
-	return retval;
-}
-
-UA_Int32 UA_TL_Connection_close(UA_TL_Connection *connection) {
-	connection->state = CONNECTIONSTATE_CLOSED;
-	connection->closeCallback(connection);
-	return UA_SUCCESS;
-}
-
-UA_Boolean UA_TL_Connection_compare(UA_TL_Connection *connection1, UA_TL_Connection *connection2) {
-	if(!connection1 || !connection2)
-		return UA_FALSE;
-	return ((*(UA_TL_Connection**)connection1)->connectionHandle == (*(UA_TL_Connection**)connection2)->connectionHandle);
-}
-
-
-UA_Int32 UA_TL_Connection_configByHello(UA_TL_Connection *connection, UA_OPCUATcpHelloMessage *helloMessage) {
-	UA_Int32 retval = UA_SUCCESS;
-	connection->remoteConf.maxChunkCount = helloMessage->maxChunkCount;
-	connection->remoteConf.maxMessageSize = helloMessage->maxMessageSize;
-	connection->remoteConf.protocolVersion = helloMessage->protocolVersion;
-	connection->remoteConf.recvBufferSize = helloMessage->receiveBufferSize;
-	connection->remoteConf.sendBufferSize = helloMessage->sendBufferSize;
-	connection->state = CONNECTIONSTATE_ESTABLISHED;
-	retval |= UA_String_copy(&helloMessage->endpointUrl,&connection->remoteEndpointUrl);
-
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_Connection_callWriter(UA_TL_Connection *connection, const UA_ByteString** gather_bufs, UA_Int32 gather_len) {
-	return connection->writer(connection->connectionHandle,gather_bufs, gather_len);
-}
-
-//setters
-UA_Int32 UA_TL_Connection_setWriter(UA_TL_Connection *connection, TL_Writer writer) {
-	connection->writer = writer;
-	return UA_SUCCESS;
-}
-
-/* UA_Int32 UA_TL_Connection_setConnectionHandle(UA_TL_Connection *connection, UA_Int32 connectionHandle)
-{
-	connection->connectionHandle = connectionHandle;
-	return UA_SUCCESS;
-} */
-
-UA_Int32 UA_TL_Connection_setState(UA_TL_Connection *connection, UA_Int32 connectionState) {
-	if(!connection)
-		return UA_ERROR;
-
-	connection->state = connectionState;
-	return UA_SUCCESS;
-}
-
-//getters
-UA_Int32 UA_TL_Connection_getState(UA_TL_Connection *connection, UA_Int32 *connectionState) {
-	if(!connection) {
-		*connectionState = -1;
-		return UA_ERROR;
-	}
-
-	*connectionState = connection->state;
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_Connection_getNetworkLayerData(UA_TL_Connection *connection,void** networkLayerData) {
-	if(!connection) {
-		*networkLayerData = UA_NULL;
-		return UA_ERROR;
-	}
-
-	*networkLayerData = connection->networkLayerData;
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_Connection_getProtocolVersion(UA_TL_Connection *connection, UA_UInt32 *protocolVersion) {
-	if(!connection) {
-		*protocolVersion = 0xFF;
-		return UA_ERROR;
-	}
-
-	*protocolVersion = connection->localConf.protocolVersion;
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_Connection_getLocalConfig(UA_TL_Connection *connection, TL_Buffer *localConfiguration) {
-	if(!connection) {
-		localConfiguration = UA_NULL;
-		return UA_ERROR;
-	}
-
-	return UA_memcpy(localConfiguration,&connection->localConf, sizeof(TL_Buffer));
-}
-
-UA_Int32 UA_TL_Connection_getHandle(UA_TL_Connection *connection, UA_UInt32 *connectionHandle) {
-	if(!connection) {
-		connectionHandle = 0;
-		return UA_ERROR;
-	}
-
-	*connectionHandle = connection->connectionHandle;
-	return UA_SUCCESS;
-}
-
-UA_Int32 UA_TL_Connection_bind(UA_TL_Connection *connection, UA_Int32 handle) {
-	if(!connection)
-		return UA_ERROR;
-
-	connection->connectionHandle = handle;
-	return UA_SUCCESS;
-}

+ 0 - 39
src/ua_transport_connection.h

@@ -1,39 +0,0 @@
-#ifndef UA_TRANSPORT_CONNECTION_H_
-#define UA_TRANSPORT_CONNECTION_H_
-
-#include "ua_transport.h"
-
-typedef struct TL_Buffer{
-	UA_UInt32 protocolVersion;
-	UA_UInt32 sendBufferSize;
-	UA_UInt32 recvBufferSize;
-	UA_UInt32 maxMessageSize;
-	UA_UInt32 maxChunkCount;
-} TL_Buffer;
-struct UA_TL_Connection;
-typedef struct UA_TL_Connection UA_TL_Connection;
-
-typedef UA_Int32 (*TL_Closer)(UA_TL_Connection*);
-typedef UA_Int32 (*TL_Writer)(UA_Int32 connectionHandle, const UA_ByteString** gather_bufs, UA_Int32 gather_len); // send mutiple buffer concatenated into one msg (zero copy)
-
-UA_Int32 UA_TL_Connection_configByHello(UA_TL_Connection *connection, UA_OPCUATcpHelloMessage *helloMessage);
-UA_Int32 UA_TL_Connection_delete(UA_TL_Connection *connection);
-UA_Int32 UA_TL_Connection_callWriter(UA_TL_Connection *connection, const UA_ByteString** gather_bufs, UA_Int32 gather_len);
-UA_Int32 UA_TL_Connection_close(UA_TL_Connection *connection);
-UA_Int32 UA_TL_Connection_new(UA_TL_Connection **connection, TL_Buffer localBuffers,TL_Writer writer, TL_Closer closeCallback,UA_Int32 handle, void* networkLayerData);
-UA_Int32 UA_TL_Connection_bind(UA_TL_Connection *connection, UA_Int32 handle);
-UA_Boolean UA_TL_Connection_compare(UA_TL_Connection *connection1, UA_TL_Connection *connection2);
-
-//setters
-UA_Int32 UA_TL_Connection_setState(UA_TL_Connection *connection, UA_Int32 connectionState);
-UA_Int32 UA_TL_Connection_setWriter(UA_TL_Connection *connection, TL_Writer writer);
-//UA_Int32 UA_TL_Connection_setConnectionHandle(UA_TL_Connection *connection, UA_Int32 connectionHandle);
-
-//getters
-UA_Int32 UA_TL_Connection_getHandle(UA_TL_Connection *connection, UA_UInt32 *connectionId);
-UA_Int32 UA_TL_Connection_getProtocolVersion(UA_TL_Connection *connection, UA_UInt32 *protocolVersion);
-UA_Int32 UA_TL_Connection_getState(UA_TL_Connection *connection, UA_Int32 *connectionState);
-UA_Int32 UA_TL_Connection_getLocalConfig(UA_TL_Connection *connection, TL_Buffer *localConfiguration);
-UA_Int32 UA_TL_Connection_getNetworkLayerData(UA_TL_Connection *connection,void** networkLayerData);
-
-#endif /* UA_TRANSPORT_CONNECTION_H_ */

+ 0 - 2
src/ua_types.c

@@ -1,4 +1,3 @@
-#include <stdio.h>  // printf
 #include <stdlib.h> // alloc, free, vsnprintf
 #include <string.h>
 #include <stdarg.h> // va_start, va_end
@@ -14,7 +13,6 @@
 #include "ua_types.h"
 #include "ua_types_encoding_binary.h"
 #include "ua_namespace_0.h"
-#include "inttypes.h"
 
 /************/
 /* Built-In */

+ 1 - 3
src/ua_types.h

@@ -125,12 +125,10 @@ typedef struct UA_String UA_ByteString;
 typedef struct UA_String UA_XmlElement;
 
 /** @brief An identifier for a node in the address space of an OPC UA Server. */
+/* The shortened numeric types are introduced during encoding. */
 typedef struct UA_NodeId {
 	UA_UInt16 namespaceIndex;
 	enum {
-		/* The shortened numeric types are introduced during encoding.
-		   UA_NODEIDTYPE_TWOBYTE = 0,
-		   UA_NODEIDTYPE_FOURBYTE = 1, */
 		UA_NODEIDTYPE_NUMERIC = 2,
 		UA_NODEIDTYPE_STRING = 3,
 		UA_NODEIDTYPE_GUID = 4,

+ 0 - 23
src/util/ua_list.h

@@ -2,29 +2,6 @@
 #define UA_LIST_H_
 
 #include "ua_types.h"
-#include <stddef.h> /* Needed for sys/queue.h */
-#ifndef MSVC
-#include <sys/queue.h>
-#else
-#include "queue.h"
-#endif
-
-/**********************/
-/* Singly Linked List */
-/**********************/
-
-#define UA_SLIST_HEAD(name, type) SLIST_HEAD(name, type)
-#define UA_SLIST_HEAD_INITIALIZER(head) SLIST_HEAD_INITILIZER(head)
-#define UA_SLIST_ENTRY(type) SLIST_ENTRY(type)
-#define UA_SLIST_INIT(head) SLIST_INIT(head)
-#define UA_SLIST_INSERT_AFTER(slistelm, elm, field) SLIST_INSERT_AFTER(slistelm, elm, field)
-#define UA_SLIST_INSERT_HEAD(head, elm, field) SLIST_INSERT_HEAD(head, elm, field)
-#define UA_SLIST_REMOVE_HEAD(head, field) SLIST_REMOVE_HEAD(head, field)
-#define UA_SLIST_REMOVE(head, elm, type, field) SLIST_REMOVE(head, elm, type, field)
-#define UA_SLIST_FOREACH(var, head, field) SLIST_FOREACH(var, head, field)
-#define UA_SLIST_EMPTY(head) SLIST_EMPTY(head)
-#define UA_SLIST_FIRST(head) SLIST_FIRST(head)
-#define UA_SLIST_NEXT(elm, field) SLIST_NEXT(elm, field)
 
 /**********************/
 /* Doubly Linked List */

+ 17 - 28
src/util/ua_log.h

@@ -5,21 +5,14 @@
    @defgroup logging Logging
 
    @brief Logging functionality is externally provided to the open62541 libary.
-   That is, every thread that wants logging to take place fills a global
-   variable "logger" with the appropriate callback functions. The UA_LOGLEVEL
-   preprocessor definition indicates which severity of events (trance, debug,
-   info, warning, error, fatal) shall be reported. Enabling logs at a certain
-   level enables all logs at the higher levels also. Furthermore, every
-   log-message has a category that can be used for filtering or to select the
-   output medium (file, stdout, ..).
+   The server contains a logger-struct with function callbacks
 */
 
 typedef enum UA_LoggerCategory {
-	UA_LOGGERCATEGORY_CONNECTION,
-	UA_LOGGERCATEGORY_SESSION,
-	UA_LOGGERCATEGORY_SUBSCRIPTION,
-	UA_LOGGERCATEGORY_MAINTENANCE,
-	UA_LOGGERCATEGORY_LOAD,
+	UA_LOGGINGCATEGORY_CONNECTION,
+	UA_LOGGINGCATEGORY_SESSION,
+	UA_LOGGINGCATEGORY_SUBSCRIPTION,
+	UA_LOGGINGCATEGORY_SERVER
 } UA_LoggerCategory;
 
 typedef struct UA_Logger {
@@ -31,44 +24,40 @@ typedef struct UA_Logger {
 	void (*log_fatal)(UA_LoggerCategory category, const char *msg, ...);
 } UA_Logger;
 
-/** The logger is a global variable on the stack. So every thread needs to
-	initialise its own logger. */
-static UA_Logger logger;
-
 #if UA_LOGLEVEL <= 100
-#define LOG_TRACE(CATEGORY, MSG, ...) do{ logger.log_trace(CATEGORY, MSG, __VA_ARGS__); } while(0)
+#define UA_LOG_TRACE(CATEGORY, MSG, ...) do{ logger.log_trace(CATEGORY, MSG, __VA_ARGS__); } while(0)
 #else
-#define LOG_TRACE(CATEGORY, MSG, ...) do {} while(0)
+#define UA_LOG_TRACE(CATEGORY, MSG, ...) do {} while(0)
 #endif
 
 #if UA_LOGLEVEL <= 200
-#define LOG_DEBUG(CATEGORY, MSG, ...) do{ logger.log_debug(CATEGORY, MSG, __VA_ARGS__); } while(0)
+#define UA_LOG_DEBUG(CATEGORY, MSG, ...) do{ logger.log_debug(CATEGORY, MSG, __VA_ARGS__); } while(0)
 #else
-#define LOG_DEBUG(CATEGORY, MSG, ...) do {} while(0)
+#define UA_LOG_DEBUG(CATEGORY, MSG, ...) do {} while(0)
 #endif
 
 #if UA_LOGLEVEL <= 300
-#define LOG_INFO(CATEGORY, MSG, ...) do{ logger.log_info(CATEGORY, MSG, __VA_ARGS__); } while(0)
+#define UA_LOG_INFO(CATEGORY, MSG, ...) do{ logger.log_info(CATEGORY, MSG, __VA_ARGS__); } while(0)
 #else
-#define LOG_INFO(CATEGORY, MSG, ...) do {} while(0)
+#define UA_LOG_INFO(CATEGORY, MSG, ...) do {} while(0)
 #endif
 
 #if UA_LOGLEVEL <= 400
-#define LOG_WARNING(CATEGORY, MSG, ...) do{ logger.log_warning(CATEGORY, MSG, __VA_ARGS__); } while(0)
+#define UA_LOG_WARNING(CATEGORY, MSG, ...) do{ logger.log_warning(CATEGORY, MSG, __VA_ARGS__); } while(0)
 #else
-#define LOG_WARNING(CATEGORY, MSG, ...) do {} while(0)
+#define UA_LOG_WARNING(CATEGORY, MSG, ...) do {} while(0)
 #endif
 
 #if UA_LOGLEVEL <= 500
-#define LOG_ERROR(CATEGORY, MSG, ...) do{ logger.log_error(CATEGORY, MSG, __VA_ARGS__); } while(0)
+#define UA_LOG_ERROR(CATEGORY, MSG, ...) do{ logger.log_error(CATEGORY, MSG, __VA_ARGS__); } while(0)
 #else
-#define LOG_ERROR(CATEGORY, MSG, ...) do {} while(0)
+#define UA_LOG_ERROR(CATEGORY, MSG, ...) do {} while(0)
 #endif
 
 #if UA_LOGLEVEL <= 600
-#define LOG_FATAL(CATEGORY, MSG, ...) do{ logger.log_fatal(CATEGORY, MSG, __VA_ARGS__); } while(0)
+#define UA_LOG_FATAL(CATEGORY, MSG, ...) do{ logger.log_fatal(CATEGORY, MSG, __VA_ARGS__); } while(0)
 #else
-#define LOG_FATAL(CATEGORY, MSG, ...) do {} while(0)
+#define UA_LOG_FATAL(CATEGORY, MSG, ...) do {} while(0)
 #endif
 
 #endif /* UA_LOG_H_ */

+ 8 - 0
src/util/ua_util.h

@@ -13,6 +13,14 @@
 #include <malloc.h> // MinGW alloca
 #endif
 #endif
+
+#include <stddef.h> /* Needed for sys/queue.h */
+#ifndef MSVC
+#include <sys/queue.h>
+#else
+#include "queue.h"
+#endif
+
 #include "ua_types.h"
 
 /* Debug macros */

+ 1 - 0
tests/check_builtin.c

@@ -2,6 +2,7 @@
 #include <stdlib.h>
 #include "ua_types.h"
 #include "ua_types_encoding_binary.h"
+#include "ua_namespace_0.h"
 #include "ua_transport.h"
 #include "check.h"
 

+ 87 - 87
tests/check_namespace.c

@@ -3,7 +3,7 @@
 #include <time.h>
 
 #include "ua_types.h"
-#include "ua_namespace.h"
+#include "server/ua_namespace.h"
 #include "check.h"
 
 #ifdef MULTITHREADING
@@ -22,10 +22,10 @@ void printVisitor(const UA_Node* node) {
 	printf("%d\n", node->nodeId.identifier.numeric);
 }
 
-START_TEST(test_Namespace) {
-	Namespace *ns = UA_NULL;
-	Namespace_new(&ns, 0);
-	Namespace_delete(ns);
+START_TEST(test_UA_Namespace) {
+	UA_Namespace *ns = UA_NULL;
+	UA_Namespace_new(&ns);
+	UA_Namespace_delete(ns);
 }
 END_TEST
 
@@ -38,115 +38,115 @@ UA_Int32 createNode(UA_Node** p, UA_Int16 nsid, UA_Int32 id) {
 	return UA_SUCCESS;
 }
 
-START_TEST(findNodeInNamespaceWithSingleEntry) {
+START_TEST(findNodeInUA_NamespaceWithSingleEntry) {
 #ifdef MULTITHREADING
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns;
-	Namespace_new(&ns, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
 	UA_Node* n1; createNode(&n1,0,2253);
-	Namespace_insert(ns, &n1, NAMESPACE_INSERT_UNIQUE | NAMESPACE_INSERT_GETMANAGED);
+	UA_Namespace_insert(ns, &n1, UA_NAMESPACE_INSERT_UNIQUE | UA_NAMESPACE_INSERT_GETMANAGED);
 	const UA_Node* nr = UA_NULL;
 	UA_Int32 retval;
 	// when
-	retval = Namespace_get(ns,&n1->nodeId,&nr);
+	retval = UA_Namespace_get(ns,&n1->nodeId,&nr);
 	// then
 	ck_assert_int_eq(retval, UA_SUCCESS);
 	ck_assert_ptr_eq(nr,n1);
 	// finally
-	Namespace_releaseManagedNode(n1);
-	Namespace_releaseManagedNode(nr);
-	Namespace_delete(ns);
+	UA_Namespace_releaseManagedNode(n1);
+	UA_Namespace_releaseManagedNode(nr);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
 }
 END_TEST
 
-START_TEST(failToFindNodeInOtherNamespace) {
+START_TEST(failToFindNodeInOtherUA_Namespace) {
 #ifdef MULTITHREADING
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns = UA_NULL;
-	Namespace_new(&ns, 0);
+	UA_Namespace *ns = UA_NULL;
+	UA_Namespace_new(&ns);
 
-	UA_Node* n1; createNode(&n1,0,2253); Namespace_insert(ns, &n1, 0);
-	UA_Node* n2; createNode(&n2,0,2253); Namespace_insert(ns, &n2, 0);
+	UA_Node* n1; createNode(&n1,0,2253); UA_Namespace_insert(ns, &n1, 0);
+	UA_Node* n2; createNode(&n2,0,2253); UA_Namespace_insert(ns, &n2, 0);
 
 	const UA_Node* nr = UA_NULL;
 	// when
 	UA_Node* n; createNode(&n,1,2255);
-	UA_Int32 retval = Namespace_get(ns,&n->nodeId, &nr);
+	UA_Int32 retval = UA_Namespace_get(ns,&n->nodeId, &nr);
 	// then
 	ck_assert_int_ne(retval, UA_SUCCESS);
 	// finally
 	UA_Node_delete(n);
-	Namespace_releaseManagedNode(nr);
-	Namespace_delete(ns);
+	UA_Namespace_releaseManagedNode(nr);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
 }
 END_TEST
 
-START_TEST(findNodeInNamespaceWithSeveralEntries) {
+START_TEST(findNodeInUA_NamespaceWithSeveralEntries) {
 #ifdef MULTITHREADING
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns;
-	Namespace_new(&ns, 0);
-	UA_Node* n1; createNode(&n1,0,2253); Namespace_insert(ns, &n1, 0);
-	UA_Node* n2; createNode(&n2,0,2255); Namespace_insert(ns, &n2, 0);
-	UA_Node* n3; createNode(&n3,0,2257); Namespace_insert(ns, &n3, NAMESPACE_INSERT_GETMANAGED);
-	UA_Node* n4; createNode(&n4,0,2200); Namespace_insert(ns, &n4, 0);
-	UA_Node* n5; createNode(&n5,0,1); Namespace_insert(ns, &n5, 0);
-	UA_Node* n6; createNode(&n6,0,12); Namespace_insert(ns, &n6, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
+	UA_Node* n1; createNode(&n1,0,2253); UA_Namespace_insert(ns, &n1, 0);
+	UA_Node* n2; createNode(&n2,0,2255); UA_Namespace_insert(ns, &n2, 0);
+	UA_Node* n3; createNode(&n3,0,2257); UA_Namespace_insert(ns, &n3, UA_NAMESPACE_INSERT_GETMANAGED);
+	UA_Node* n4; createNode(&n4,0,2200); UA_Namespace_insert(ns, &n4, 0);
+	UA_Node* n5; createNode(&n5,0,1); UA_Namespace_insert(ns, &n5, 0);
+	UA_Node* n6; createNode(&n6,0,12); UA_Namespace_insert(ns, &n6, 0);
 
 	const UA_Node* nr = UA_NULL;
 	UA_Int32 retval;
 	// when
-	retval = Namespace_get(ns,&(n3->nodeId),&nr);
+	retval = UA_Namespace_get(ns,&(n3->nodeId),&nr);
 	// then
 	ck_assert_int_eq(retval, UA_SUCCESS);
 	ck_assert_ptr_eq(nr,n3);
 	// finally
-	Namespace_releaseManagedNode(n3);
-	Namespace_releaseManagedNode(nr);
-	Namespace_delete(ns);
+	UA_Namespace_releaseManagedNode(n3);
+	UA_Namespace_releaseManagedNode(nr);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
 }
 END_TEST
 
-START_TEST(iterateOverNamespaceShallNotVisitEmptyNodes) {
+START_TEST(iterateOverUA_NamespaceShallNotVisitEmptyNodes) {
 #ifdef MULTITHREADING
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns;
-	Namespace_new(&ns, 0);
-	UA_Node* n1; createNode(&n1,0,2253); Namespace_insert(ns, &n1, 0);
-	UA_Node* n2; createNode(&n2,0,2255); Namespace_insert(ns, &n2, 0);
-	UA_Node* n3; createNode(&n3,0,2257); Namespace_insert(ns, &n3, 0);
-	UA_Node* n4; createNode(&n4,0,2200); Namespace_insert(ns, &n4, 0);
-	UA_Node* n5; createNode(&n5,0,1); Namespace_insert(ns, &n5, 0);
-	UA_Node* n6; createNode(&n6,0,12); Namespace_insert(ns, &n6, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
+	UA_Node* n1; createNode(&n1,0,2253); UA_Namespace_insert(ns, &n1, 0);
+	UA_Node* n2; createNode(&n2,0,2255); UA_Namespace_insert(ns, &n2, 0);
+	UA_Node* n3; createNode(&n3,0,2257); UA_Namespace_insert(ns, &n3, 0);
+	UA_Node* n4; createNode(&n4,0,2200); UA_Namespace_insert(ns, &n4, 0);
+	UA_Node* n5; createNode(&n5,0,1); UA_Namespace_insert(ns, &n5, 0);
+	UA_Node* n6; createNode(&n6,0,12); UA_Namespace_insert(ns, &n6, 0);
 
 	UA_Int32 retval;
 	// when
 	zeroCnt = 0;
 	visitCnt = 0;
-	retval = Namespace_iterate(ns,checkZeroVisitor);
+	retval = UA_Namespace_iterate(ns,checkZeroVisitor);
 	// then
 	ck_assert_int_eq(retval, UA_SUCCESS);
 	ck_assert_int_eq(zeroCnt, 0);
 	ck_assert_int_eq(visitCnt, 6);
 	// finally
-	Namespace_delete(ns);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
@@ -158,25 +158,25 @@ START_TEST(findNodeInExpandedNamespace) {
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns;
-	Namespace_new(&ns, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
 	UA_Node* n;
 	UA_Int32 i=0;
 	for (; i<200; i++) {
-		createNode(&n,0,i); Namespace_insert(ns, &n, 0);
+		createNode(&n,0,i); UA_Namespace_insert(ns, &n, 0);
 	}
 	const UA_Node* nr = UA_NULL;
 	UA_Int32 retval;
 	// when
 	createNode(&n,0,25);
-	retval = Namespace_get(ns,&(n->nodeId),&nr);
+	retval = UA_Namespace_get(ns,&(n->nodeId),&nr);
 	// then
 	ck_assert_int_eq(retval, UA_SUCCESS);
 	ck_assert_int_eq(nr->nodeId.identifier.numeric,n->nodeId.identifier.numeric);
 	// finally
 	UA_free((void*)n);
-	Namespace_releaseManagedNode(nr);
-	Namespace_delete(ns);
+	UA_Namespace_releaseManagedNode(nr);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
@@ -188,53 +188,53 @@ START_TEST(iterateOverExpandedNamespaceShallNotVisitEmptyNodes) {
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns;
-	Namespace_new(&ns, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
 	UA_Node* n;
 	UA_Int32 i=0;
 	for (; i<200; i++) {
-		createNode(&n,0,i); Namespace_insert(ns, &n, 0);
+		createNode(&n,0,i); UA_Namespace_insert(ns, &n, 0);
 	}
 	// when
 	UA_Int32 retval;
 	zeroCnt = 0;
 	visitCnt = 0;
-	retval = Namespace_iterate(ns,checkZeroVisitor);
+	retval = UA_Namespace_iterate(ns,checkZeroVisitor);
 	// then
 	ck_assert_int_eq(retval, UA_SUCCESS);
 	ck_assert_int_eq(zeroCnt, 0);
 	ck_assert_int_eq(visitCnt, 200);
 	// finally
-	Namespace_delete(ns);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
 }
 END_TEST
 
-START_TEST(failToFindNonExistantNodeInNamespaceWithSeveralEntries) {
+START_TEST(failToFindNonExistantNodeInUA_NamespaceWithSeveralEntries) {
 #ifdef MULTITHREADING
    	rcu_register_thread();
 #endif
 	// given
-	Namespace *ns;
-	Namespace_new(&ns, 0);
-	UA_Node* n1; createNode(&n1,0,2253); Namespace_insert(ns, &n1, 0);
-	UA_Node* n2; createNode(&n2,0,2255); Namespace_insert(ns, &n2, 0);
-	UA_Node* n3; createNode(&n3,0,2257); Namespace_insert(ns, &n3, 0);
-	UA_Node* n4; createNode(&n4,0,2200); Namespace_insert(ns, &n4, 0);
-	UA_Node* n5; createNode(&n5,0,1); Namespace_insert(ns, &n5, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
+	UA_Node* n1; createNode(&n1,0,2253); UA_Namespace_insert(ns, &n1, 0);
+	UA_Node* n2; createNode(&n2,0,2255); UA_Namespace_insert(ns, &n2, 0);
+	UA_Node* n3; createNode(&n3,0,2257); UA_Namespace_insert(ns, &n3, 0);
+	UA_Node* n4; createNode(&n4,0,2200); UA_Namespace_insert(ns, &n4, 0);
+	UA_Node* n5; createNode(&n5,0,1); UA_Namespace_insert(ns, &n5, 0);
 	UA_Node* n6; createNode(&n6,0,12); 
 
 	const UA_Node* nr = UA_NULL;
 	UA_Int32 retval;
 	// when
-	retval = Namespace_get(ns, &(n6->nodeId), &nr);
+	retval = UA_Namespace_get(ns, &(n6->nodeId), &nr);
 	// then
 	ck_assert_int_ne(retval, UA_SUCCESS);
 	// finally
 	UA_free((void *)n6);
-	Namespace_delete(ns);
+	UA_Namespace_delete(ns);
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
 #endif
@@ -246,8 +246,8 @@ END_TEST
 /************************************/
 
 #ifdef MULTITHREADING
-struct NamespaceProfileTest {
-	Namespace *ns;
+struct UA_NamespaceProfileTest {
+	UA_Namespace *ns;
 	UA_Int32 min_val;
 	UA_Int32 max_val;
 	UA_Int32 rounds;
@@ -255,16 +255,16 @@ struct NamespaceProfileTest {
 
 void *profileGetThread(void *arg) {
    	rcu_register_thread();
-	struct NamespaceProfileTest *test = (struct NamespaceProfileTest*) arg;
+	struct UA_NamespaceProfileTest *test = (struct UA_NamespaceProfileTest*) arg;
 	UA_NodeId id = NS0NODEID(0);
 	const UA_Node *cn;
 	UA_Int32 max_val = test->max_val;
-	Namespace *ns = test->ns;
+	UA_Namespace *ns = test->ns;
 	for(UA_Int32 x = 0; x<test->rounds; x++) {
 		for (UA_Int32 i=test->min_val; i<max_val; i++) {
 			id.identifier.numeric = i;
-			Namespace_get(ns,&id, &cn);
-			Namespace_releaseManagedNode(cn);
+			UA_Namespace_get(ns,&id, &cn);
+			UA_Namespace_releaseManagedNode(cn);
 		}
 	}
 	rcu_unregister_thread();
@@ -279,21 +279,21 @@ START_TEST(profileGetDelete) {
 #endif
 
 #define N 1000000
-	Namespace *ns;
-	Namespace_new(&ns, 0);
+	UA_Namespace *ns;
+	UA_Namespace_new(&ns);
 	UA_Int32 i=0;
 	UA_Node *n;
 	for (; i<N; i++) {
-		createNode(&n,0,i); Namespace_insert(ns, &n, 0);
+		createNode(&n,0,i); UA_Namespace_insert(ns, &n, 0);
 	}
 	clock_t begin, end;
 	begin = clock();
 #ifdef MULTITHREADING
 #define THREADS 4
     pthread_t t[THREADS];
-	struct NamespaceProfileTest p[THREADS];
+	struct UA_NamespaceProfileTest p[THREADS];
 	for (int i = 0; i < THREADS; i++) {
-		p[i] = (struct NamespaceProfileTest){ns, i*(N/THREADS), (i+1)*(N/THREADS), 50};
+		p[i] = (struct UA_NamespaceProfileTest){ns, i*(N/THREADS), (i+1)*(N/THREADS), 50};
 		pthread_create(&t[i], NULL, profileGetThread, &p[i]);
 	}
 	for (int i = 0; i < THREADS; i++)
@@ -306,15 +306,15 @@ START_TEST(profileGetDelete) {
 	for(UA_Int32 x = 0; x<50; x++) {
 	    for(i=0; i<N; i++) {
 	        id.identifier.numeric = i;
-			Namespace_get(ns,&id, &cn);
-			Namespace_releaseManagedNode(cn);
+			UA_Namespace_get(ns,&id, &cn);
+			UA_Namespace_releaseManagedNode(cn);
         }
     }
 	end = clock();
 	printf("Time for single-threaded %d create/get/delete in a namespace: %fs.\n", N, (double)(end - begin) / CLOCKS_PER_SEC);
 #endif
 
-	Namespace_delete(ns);
+	UA_Namespace_delete(ns);
 
 #ifdef MULTITHREADING
 	rcu_unregister_thread();
@@ -323,22 +323,22 @@ START_TEST(profileGetDelete) {
 END_TEST
 
 Suite * namespace_suite (void) {
-	Suite *s = suite_create ("Namespace");
+	Suite *s = suite_create ("UA_Namespace");
 
 	TCase *tc_cd = tcase_create ("Create/Delete");
-	tcase_add_test (tc_cd, test_Namespace);
+	tcase_add_test (tc_cd, test_UA_Namespace);
 	suite_add_tcase (s, tc_cd);
 
 	TCase* tc_find = tcase_create ("Find");
-	tcase_add_test (tc_find, findNodeInNamespaceWithSingleEntry);
-	tcase_add_test (tc_find, findNodeInNamespaceWithSeveralEntries);
+	tcase_add_test (tc_find, findNodeInUA_NamespaceWithSingleEntry);
+	tcase_add_test (tc_find, findNodeInUA_NamespaceWithSeveralEntries);
 	tcase_add_test (tc_find, findNodeInExpandedNamespace);
-	tcase_add_test (tc_find, failToFindNonExistantNodeInNamespaceWithSeveralEntries);
-	tcase_add_test (tc_find, failToFindNodeInOtherNamespace);
+	tcase_add_test (tc_find, failToFindNonExistantNodeInUA_NamespaceWithSeveralEntries);
+	tcase_add_test (tc_find, failToFindNodeInOtherUA_Namespace);
 	suite_add_tcase (s, tc_find);
 
 	TCase* tc_iterate = tcase_create ("Iterate");
-	tcase_add_test (tc_iterate, iterateOverNamespaceShallNotVisitEmptyNodes);
+	tcase_add_test (tc_iterate, iterateOverUA_NamespaceShallNotVisitEmptyNodes);
 	tcase_add_test (tc_iterate, iterateOverExpandedNamespaceShallNotVisitEmptyNodes);
 	suite_add_tcase (s, tc_iterate);
 	

+ 4 - 14
tests/check_services_view.c

@@ -1,22 +1,12 @@
-/*
- ============================================================================
- Name        : check_stack.c
- Author      :
- Version     :
- Copyright   : Your copyright notice
- Description :
- ============================================================================
- */
-
 #include <stdio.h>
 #include <stdlib.h>
 
 #include "ua_types.h"
-#include "ua_services.h"
+#include "server/ua_services.h"
 #include "ua_statuscodes.h"
 #include "check.h"
 
-START_TEST(Service_TranslateBrowsePathsToNodeIds_SmokeTest)
+/* START_TEST(Service_TranslateBrowsePathsToNodeIds_SmokeTest)
 {
 	UA_TranslateBrowsePathsToNodeIdsRequest request;
 	UA_TranslateBrowsePathsToNodeIdsRequest_init(&request);
@@ -36,13 +26,13 @@ START_TEST(Service_TranslateBrowsePathsToNodeIds_SmokeTest)
 	UA_TranslateBrowsePathsToNodeIdsRequest_deleteMembers(&request);
 	UA_TranslateBrowsePathsToNodeIdsResponse_deleteMembers(&response);
 }
-END_TEST
+END_TEST */
 
 Suite* testSuite_Service_TranslateBrowsePathsToNodeIds()
 {
 	Suite *s = suite_create("Service_TranslateBrowsePathsToNodeIds");
 	TCase *tc_core = tcase_create("Core");
-	tcase_add_test(tc_core, Service_TranslateBrowsePathsToNodeIds_SmokeTest);
+	//tcase_add_test(tc_core, Service_TranslateBrowsePathsToNodeIds_SmokeTest);
 	suite_add_tcase(s,tc_core);
 	return s;
 }

+ 23 - 40
tests/check_stack.c

@@ -3,11 +3,9 @@
 
 #include "ua_types.h"
 #include "ua_transport.h"
-#include "ua_transport_binary.h"
-#include "ua_transport_binary_secure.h"
-#include "ua_transport_connection.h"
-#include "ua_channel_manager.h"
-#include "ua_session_manager.h"
+#include "ua_connection.h"
+#include "server/ua_securechannel_manager.h"
+#include "server/ua_session_manager.h"
 #include "check.h"
 
 #define MAXMSG 512
@@ -20,11 +18,9 @@ typedef struct stackTestFixture {
 	/** @brief the management structure (initialized to point to respMsgBuffer in create */
 	UA_ByteString respMsg;
 	/** @brief the management data structure for the fake connection */
-	UA_TL_Connection *connection;
-
+	UA_Connection *connection;
 } stackTestFixture;
 
-
 /** @brief the maximum number of parallel fixtures.
  * ( MAX_FIXTURES needs to match the number of bytes of fixturesMap )*/
 #define MAX_FIXTURES 32
@@ -35,9 +31,8 @@ stackTestFixture *fixtures[MAX_FIXTURES];
 
 /** @brief search first free handle, set and return */
 UA_Int32 stackTestFixture_getAndMarkFreeHandle() {
-	UA_Int32 freeFixtureHandle = 0;
-
-	for(freeFixtureHandle = 0;freeFixtureHandle < MAX_FIXTURES;++freeFixtureHandle) {
+	UA_UInt32 freeFixtureHandle = 0;
+	for(freeFixtureHandle = 0;freeFixtureHandle < MAX_FIXTURES;freeFixtureHandle++) {
 		if(!(fixturesMap & (1 << freeFixtureHandle))) { // when free
 			fixturesMap |= (1 << freeFixtureHandle);    // then set
 			return freeFixtureHandle;
@@ -54,34 +49,22 @@ UA_Int32 stackTestFixture_markHandleAsFree(UA_Int32 fixtureHandle) {
 	}
 	return UA_ERR_INVALID_VALUE;
 }
-UA_Int32 closerCallback(UA_TL_Connection *connection)
-{
+
+UA_Int32 closerCallback(UA_Connection *connection) {
 	return UA_SUCCESS;
 }
-/** @brief get a handle to a free slot and create a new stackTestFixture */
-UA_Int32 stackTestFixture_create(TL_Writer writerCallback, TL_Closer closerCallback) {
-	UA_String endpointUrl;
-	UA_String_copycstring("no url",&endpointUrl);
-	SL_ChannelManager_init(4,36000,25,22,&endpointUrl);
-	UA_SessionManager_init(4,220000,222);
 
+/** @brief get a handle to a free slot and create a new stackTestFixture */
+UA_Int32 stackTestFixture_create(UA_Connection_writeCallback write, UA_Connection_closeCallback close) {
 	UA_UInt32 fixtureHandle = stackTestFixture_getAndMarkFreeHandle();
-	if(fixtureHandle < MAX_FIXTURES) {
-		UA_alloc((void **)&fixtures[fixtureHandle], sizeof(stackTestFixture));
-		stackTestFixture *fixture = fixtures[fixtureHandle];
-		fixture->respMsg.data   = fixture->respMsgBuffer;
-		fixture->respMsg.length = 0;
-		TL_Buffer buffer;
-		buffer.maxChunkCount   = 1;
-		buffer.maxMessageSize  = BUFFER_SIZE;
-		buffer.protocolVersion = 0;
-		buffer.recvBufferSize  = BUFFER_SIZE;
-		buffer.recvBufferSize  = BUFFER_SIZE;
-		UA_TL_Connection_new(&fixture->connection,buffer,writerCallback,closerCallback,fixtureHandle,UA_NULL);
-
-	}
+	stackTestFixture *fixture = fixtures[fixtureHandle];
+	UA_alloc((void**)&fixture->connection, sizeof(UA_Connection));
+	fixture->respMsg.data   = fixture->respMsgBuffer;
+	fixture->respMsg.length = 0;
+	UA_Connection_init(fixture->connection, UA_ConnectionConfig_standard, fixture, close, write);
 	return fixtureHandle;
 }
+
 /** @brief free the allocated memory of the stackTestFixture associated with the handle */
 UA_Int32 stackTestFixture_delete(UA_UInt32 fixtureHandle) {
 	if(fixtureHandle < MAX_FIXTURES) {
@@ -101,7 +84,6 @@ stackTestFixture *stackTestFixture_getFixture(UA_UInt32 fixtureHandle) {
 
 /** @brief write message provided in the gather buffers to the buffer of the fixture */
 UA_Int32 responseMsg(UA_Int32 connectionHandle, UA_ByteString const **gather_buf, UA_Int32 gather_len) {
-
 	stackTestFixture *fixture = stackTestFixture_getFixture(connectionHandle);
 	UA_Int32  retval    = UA_SUCCESS;
 	UA_UInt32 total_len = 0;
@@ -118,7 +100,6 @@ UA_Int32 responseMsg(UA_Int32 connectionHandle, UA_ByteString const **gather_buf
 }
 
 void indicateMsg(UA_Int32 handle, UA_ByteString *slMessage) {
-
 	printf("indicate: %d", TL_Process((stackTestFixture_getFixture(handle)->connection), slMessage));
 }
 
@@ -361,7 +342,6 @@ START_TEST(emptyIndicationShallYieldNoResponse) {
 }
 END_TEST
 
-
 START_TEST(validHELIndicationShallYieldACKResponse) {
 	// given
 	UA_Int32 handle = stackTestFixture_create(responseMsg, closerCallback);
@@ -475,6 +455,7 @@ START_TEST(UA_OPCUATcpMessageHeader_copyShallWorkOnInputExample) {
 	ck_assert_int_eq(2, dst.isFinal);
 }
 END_TEST
+
 START_TEST(UA_AsymmetricAlgorithmSecurityHeader_copyShallWorkOnInputExample) {
 	// given
 	UA_AsymmetricAlgorithmSecurityHeader src;
@@ -501,6 +482,7 @@ START_TEST(UA_AsymmetricAlgorithmSecurityHeader_copyShallWorkOnInputExample) {
 
 }
 END_TEST
+
 START_TEST(UA_SecureConversationMessageHeader_copyShallWorkOnInputExample) {
 	// given
 	UA_SecureConversationMessageHeader src;
@@ -528,6 +510,7 @@ START_TEST(UA_SecureConversationMessageHeader_copyShallWorkOnInputExample) {
 	ck_assert_int_eq(UA_MESSAGETYPE_CLO, dst.messageHeader.messageType);
 }
 END_TEST
+
 START_TEST(UA_SequenceHeader_copyShallWorkOnInputExample) {
 	// given
 	UA_SequenceHeader src;
@@ -548,6 +531,7 @@ START_TEST(UA_SequenceHeader_copyShallWorkOnInputExample) {
 	ck_assert_int_eq(1345, dst.sequenceNumber);
 }
 END_TEST
+
 START_TEST(UA_SecureConversationMessageFooter_copyShallWorkOnInputExample) {
 	// given
 	UA_SecureConversationMessageFooter src;
@@ -573,6 +557,7 @@ START_TEST(UA_SecureConversationMessageFooter_copyShallWorkOnInputExample) {
 	ck_assert_int_eq(87, dst.padding[2]);
 }
 END_TEST
+
 START_TEST(UA_SecureConversationMessageFooter_calcSizeBinaryShallWorkOnInputExample) {
 	// given
 	UA_SecureConversationMessageFooter src;
@@ -592,6 +577,7 @@ START_TEST(UA_SecureConversationMessageFooter_calcSizeBinaryShallWorkOnInputExam
 	ck_assert_int_eq(ret, 8);
 }
 END_TEST
+
 START_TEST(UA_SecureConversationMessageFooter_encodeBinaryShallWorkOnInputExample) {
 //	// given
 //	UA_SecureConversationMessageFooter src = {3, (UA_Byte*)"447", 5};;
@@ -615,6 +601,7 @@ START_TEST(UA_SecureConversationMessageFooter_encodeBinaryShallWorkOnInputExampl
 //	ck_assert_int_eq(dst.data[7], 6);
 }
 END_TEST
+
 START_TEST(UA_SecureConversationMessageAbortBody_copyShallWorkOnInputExample) {
 	// given
 	UA_SecureConversationMessageAbortBody src;
@@ -623,7 +610,6 @@ START_TEST(UA_SecureConversationMessageAbortBody_copyShallWorkOnInputExample) {
 	src.reason = (UA_String){6, (UA_Byte*)"reAson"};
 
 	const UA_SecureConversationMessageAbortBody srcConst = src;
-
 	UA_SecureConversationMessageAbortBody dst;
 	UA_Int32 ret;
 
@@ -662,7 +648,6 @@ Suite *testSuite() {
 
 int main(void) {
 	int      number_failed = 0;
-
 	Suite   *s;
 	SRunner *sr;
 
@@ -676,5 +661,3 @@ int main(void) {
 
 	return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
 }
-
-