Browse Source

Merge remote-tracking branch 'origin/master' into monitoring_mode

Stefan Profanter 7 years ago
parent
commit
26086913e6
98 changed files with 1479 additions and 296 deletions
  1. 1 0
      .gitignore
  2. 15 2
      CMakeLists.txt
  3. 7 2
      doc/CMakeLists.txt
  4. 2 0
      doc/tutorials.rst
  5. 1 1
      examples/client.c
  6. 6 6
      examples/client_subscription_loop.c
  7. 2 9
      examples/custom_datatype/server_types_custom.c
  8. 0 1
      examples/encryption/server_basic128rsa15.c
  9. 10 10
      examples/server_instantiation.c
  10. 1 1
      examples/tutorial_datatypes.c
  11. 1 1
      examples/tutorial_server_datasource.c
  12. 2 2
      examples/tutorial_server_object.c
  13. 12 1
      include/ua_client.h
  14. 9 1
      include/ua_client_highlevel.h
  15. 17 4
      include/ua_config.h.in
  16. 7 1
      include/ua_constants.h
  17. 7 1
      include/ua_plugin_access_control.h
  18. 5 1
      include/ua_plugin_log.h
  19. 12 6
      include/ua_plugin_network.h
  20. 6 1
      include/ua_plugin_nodestore.h
  21. 4 1
      include/ua_plugin_pki.h
  22. 6 1
      include/ua_plugin_securitypolicy.h
  23. 13 3
      include/ua_server.h
  24. 39 5
      include/ua_server_config.h
  25. 12 1
      include/ua_types.h
  26. 6 2
      plugins/ua_accesscontrol_default.c
  27. 5 1
      plugins/ua_accesscontrol_default.h
  28. 20 1
      plugins/ua_clock.c
  29. 9 2
      plugins/ua_config_default.c
  30. 7 2
      plugins/ua_config_default.h
  31. 4 1
      plugins/ua_debug_dump_pkgs.c
  32. 4 1
      plugins/ua_log_socket_error.h
  33. 5 1
      plugins/ua_log_stdout.c
  34. 4 1
      plugins/ua_log_stdout.h
  35. 132 67
      plugins/ua_network_tcp.c
  36. 7 3
      plugins/ua_network_tcp.h
  37. 18 8
      plugins/ua_network_udp.c
  38. 4 1
      plugins/ua_network_udp.h
  39. 5 1
      plugins/ua_nodestore_default.c
  40. 5 1
      plugins/ua_nodestore_default.h
  41. 4 1
      plugins/ua_pki_certificate.c
  42. 4 1
      plugins/ua_pki_certificate.h
  43. 6 3
      plugins/ua_securitypolicy_basic128rsa15.c
  44. 4 1
      plugins/ua_securitypolicy_basic128rsa15.h
  45. 5 1
      plugins/ua_securitypolicy_none.c
  46. 5 1
      plugins/ua_securitypolicy_none.h
  47. 15 1
      src/client/ua_client.c
  48. 10 3
      src/client/ua_client_connect.c
  49. 6 1
      src/client/ua_client_discovery.c
  50. 8 1
      src/client/ua_client_highlevel.c
  51. 16 7
      src/client/ua_client_highlevel_subscriptions.c
  52. 10 2
      src/client/ua_client_internal.h
  53. 7 3
      src/server/ua_mdns.c
  54. 4 1
      src/server/ua_mdns_internal.h
  55. 10 1
      src/server/ua_nodes.c
  56. 9 1
      src/server/ua_securechannel_manager.c
  57. 8 2
      src/server/ua_securechannel_manager.h
  58. 14 1
      src/server/ua_server.c
  59. 14 2
      src/server/ua_server_binary.c
  60. 5 1
      src/server/ua_server_discovery.c
  61. 10 1
      src/server/ua_server_internal.h
  62. 9 2
      src/server/ua_server_ns0.c
  63. 9 1
      src/server/ua_server_utils.c
  64. 16 5
      src/server/ua_server_worker.c
  65. 12 2
      src/server/ua_services.h
  66. 18 2
      src/server/ua_services_attribute.c
  67. 12 2
      src/server/ua_services_call.c
  68. 10 1
      src/server/ua_services_discovery.c
  69. 7 2
      src/server/ua_services_discovery_multicast.c
  70. 17 3
      src/server/ua_services_nodemanagement.c
  71. 8 1
      src/server/ua_services_securechannel.c
  72. 10 1
      src/server/ua_services_session.c
  73. 28 14
      src/server/ua_services_subscription.c
  74. 18 4
      src/server/ua_services_view.c
  75. 4 1
      src/server/ua_session.c
  76. 5 2
      src/server/ua_session.h
  77. 8 1
      src/server/ua_session_manager.c
  78. 9 2
      src/server/ua_session_manager.h
  79. 13 1
      src/server/ua_subscription.c
  80. 15 2
      src/server/ua_subscription.h
  81. 52 20
      src/server/ua_subscription_datachange.c
  82. 9 1
      src/ua_connection.c
  83. 7 1
      src/ua_connection_internal.h
  84. 26 12
      src/ua_securechannel.c
  85. 8 2
      src/ua_securechannel.h
  86. 5 1
      src/ua_timer.c
  87. 5 1
      src/ua_timer.h
  88. 14 2
      src/ua_types.c
  89. 38 3
      src/ua_types_encoding_binary.c
  90. 8 1
      src/ua_types_encoding_binary.h
  91. 6 1
      src/ua_util.c
  92. 11 2
      src/ua_util.h
  93. 9 1
      tests/client/check_client.c
  94. 206 2
      tests/server/check_services_subscriptions.c
  95. 2 2
      tools/c2rst.py
  96. 4 3
      tools/certs/create_self-signed.py
  97. 1 1
      tools/generate_datatypes.py
  98. 234 0
      tools/update_copyright_header.py

+ 1 - 0
.gitignore

@@ -80,3 +80,4 @@ Makefile
 /build
 /.idea
 /cmake-build*
+/tools/certs/certs/*

+ 15 - 2
CMakeLists.txt

@@ -114,6 +114,9 @@ mark_as_advanced(UA_ENABLE_UNIT_TEST_FAILURE_HOOKS)
 set(UA_VXWORKS_WRS_KERNEL OFF CACHE BOOL "Enable if you want to compile for VxWorks as kernel Module")
 mark_as_advanced(UA_VXWORKS_WRS_KERNEL)
 
+set(UA_FREERTOS OFF CACHE BOOL "Enable if you want to compile for freeRTOS")
+mark_as_advanced(UA_FREERTOS)
+
 # Build options for debugging
 option(UA_DEBUG "Enable assertions and additional functionality that should not be included in release builds" OFF)
 mark_as_advanced(UA_DEBUG)
@@ -234,6 +237,16 @@ if(NOT UA_COMPILE_AS_CXX AND (CMAKE_COMPILER_IS_GNUCC OR "x${CMAKE_C_COMPILER_ID
         remove_definitions(-Werror -Wpedantic -Wno-static-in-inline -fPIC)
         add_definitions(-D_WRS_KERNEL)
     endif()
+    
+    if(UA_FREERTOS)
+       SET(UA_FREERTOS_INCLUDES "" CACHE STRING "Folders to include from the freeRTOS OS")
+       include_directories(${UA_FREERTOS_INCLUDES})
+        # Disable flags for freeRTOS
+        remove_definitions(-fPIC -Wconversion )
+        add_definitions(-DUA_FREERTOS -DLWIP_TIMEVAL_PRIVATE=0 -DLWIP_COMPAT_MUTEX=0 -DLWIP_POSIX_SOCKETS_IO_NAMES=0 -mcpu=cortex-m3 -mthumb -g -Wall -O0 -specs=nano.specs 
+                        -ffunction-sections -fdata-sections  -fno-exceptions -fstack-usage -Wno-unused-variable -Wno-format -Wno-format-security -Wno-format-nonliteral)
+        list(APPEND open62541_LIBRARIES c m stdc++ supc++)
+    endif(UA_FREERTOS)
 
     # Linker
     set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") # cmake sets -rdynamic by default
@@ -272,7 +285,7 @@ if(APPLE)
 endif()
 
 if(MSVC)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3 /WX") # Compiler warnings, error on warning
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3 /WX /w44996") # Compiler warnings, error on warning
 
   if(NOT BUILD_SHARED_LIB)
     set(CompilerFlags CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_C_FLAGS
@@ -310,8 +323,8 @@ set(exported_headers ${PROJECT_BINARY_DIR}/src_generated/ua_config.h
                      ${PROJECT_BINARY_DIR}/src_generated/ua_types_generated.h
                      ${PROJECT_BINARY_DIR}/src_generated/ua_types_generated_handling.h
                      ${PROJECT_SOURCE_DIR}/include/ua_server.h
-                     ${PROJECT_SOURCE_DIR}/include/ua_plugin_network.h
                      ${PROJECT_SOURCE_DIR}/include/ua_plugin_log.h
+                     ${PROJECT_SOURCE_DIR}/include/ua_plugin_network.h
                      ${PROJECT_SOURCE_DIR}/include/ua_plugin_access_control.h
                      ${PROJECT_SOURCE_DIR}/include/ua_plugin_pki.h
                      ${PROJECT_SOURCE_DIR}/include/ua_plugin_securitypolicy.h

+ 7 - 2
doc/CMakeLists.txt

@@ -21,6 +21,7 @@ generate_rst(${PROJECT_SOURCE_DIR}/include/ua_types.h ${DOC_SRC_DIR}/types.rst)
 generate_rst(${PROJECT_SOURCE_DIR}/include/ua_constants.h ${DOC_SRC_DIR}/constants.rst)
 generate_rst(${PROJECT_BINARY_DIR}/src_generated/ua_types_generated.h ${DOC_SRC_DIR}/types_generated.rst)
 generate_rst(${PROJECT_SOURCE_DIR}/include/ua_server.h ${DOC_SRC_DIR}/server.rst)
+generate_rst(${PROJECT_SOURCE_DIR}/include/ua_server_config.h ${DOC_SRC_DIR}/server_config.rst)
 generate_rst(${PROJECT_SOURCE_DIR}/include/ua_client.h ${DOC_SRC_DIR}/client.rst)
 generate_rst(${PROJECT_SOURCE_DIR}/include/ua_client_highlevel.h ${DOC_SRC_DIR}/client_highlevel.rst)
 generate_rst(${PROJECT_SOURCE_DIR}/include/ua_plugin_log.h ${DOC_SRC_DIR}/plugin_log.rst)
@@ -42,10 +43,12 @@ generate_rst(${PROJECT_SOURCE_DIR}/examples/tutorial_client_firststeps.c ${DOC_S
 add_custom_target(doc_latex ${SPHINX_EXECUTABLE}
   -b latex "${DOC_SRC_DIR}" "${DOC_LATEX_DIR}"
   DEPENDS ${DOC_SRC_DIR}/types.rst ${DOC_SRC_DIR}/constants.rst ${DOC_SRC_DIR}/types_generated.rst
-          ${DOC_SRC_DIR}/server.rst ${DOC_SRC_DIR}/client.rst ${DOC_SRC_DIR}/client_highlevel.rst
+          ${DOC_SRC_DIR}/server.rst ${DOC_SRC_DIR}/server_config.rst
+          ${DOC_SRC_DIR}/client.rst ${DOC_SRC_DIR}/client_highlevel.rst
           ${DOC_SRC_DIR}/plugin_log.rst ${DOC_SRC_DIR}/plugin_network.rst
           ${DOC_SRC_DIR}/services.rst ${DOC_SRC_DIR}/plugin_access_control.rst
           ${DOC_SRC_DIR}/nodestore.rst
+          ${DOC_SRC_DIR}/tutorials.rst
           ${DOC_SRC_DIR}/tutorial_datatypes.rst
           ${DOC_SRC_DIR}/tutorial_client_firststeps.rst
           ${DOC_SRC_DIR}/tutorial_server_firststeps.rst
@@ -68,10 +71,12 @@ add_dependencies(doc_pdf doc_latex)
 add_custom_target(doc ${SPHINX_EXECUTABLE}
   -b html "${DOC_SRC_DIR}" "${DOC_HTML_DIR}"
   DEPENDS ${DOC_SRC_DIR}/types.rst ${DOC_SRC_DIR}/constants.rst ${DOC_SRC_DIR}/types_generated.rst
-          ${DOC_SRC_DIR}/server.rst ${DOC_SRC_DIR}/client.rst ${DOC_SRC_DIR}/client_highlevel.rst
+          ${DOC_SRC_DIR}/server.rst ${DOC_SRC_DIR}/server_config.rst
+          ${DOC_SRC_DIR}/client.rst ${DOC_SRC_DIR}/client_highlevel.rst
           ${DOC_SRC_DIR}/plugin_log.rst ${DOC_SRC_DIR}/plugin_network.rst
           ${DOC_SRC_DIR}/services.rst ${DOC_SRC_DIR}/plugin_access_control.rst
           ${DOC_SRC_DIR}/nodestore.rst
+          ${DOC_SRC_DIR}/tutorials.rst
           ${DOC_SRC_DIR}/tutorial_datatypes.rst
           ${DOC_SRC_DIR}/tutorial_client_firststeps.rst
           ${DOC_SRC_DIR}/tutorial_server_firststeps.rst

+ 2 - 0
doc/tutorials.rst

@@ -1,3 +1,5 @@
+.. _tutorials:
+
 Tutorials
 =========
 

+ 1 - 1
examples/client.c

@@ -103,7 +103,7 @@ int main(int argc, char *argv[]) {
     UA_Client_Subscriptions_addMonitoredItem(client, subId, monitorThis, UA_ATTRIBUTEID_VALUE,
                                              &handler_TheAnswerChanged, NULL, &monId, 250);
     if(monId)
-        printf("Monitoring 'the.answer', id %u\n", subId);
+        printf("Monitoring 'the.answer', id %u\n", monId);
     /* The first publish request should return the initial value of the variable */
     UA_Client_Subscriptions_manuallySendPublishRequest(client);
 #endif

+ 6 - 6
examples/client_subscription_loop.c

@@ -59,13 +59,13 @@ stateCallback (UA_Client *client, UA_ClientState clientState) {
     switch(clientState) {
         case UA_CLIENTSTATE_DISCONNECTED:
             UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "The client is disconnected");
-        break; 
+        break;
         case UA_CLIENTSTATE_CONNECTED:
             UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "A TCP connection to the server is open");
-        break; 
+        break;
         case UA_CLIENTSTATE_SECURECHANNEL:
             UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "A SecureChannel to the server is open");
-        break; 
+        break;
         case UA_CLIENTSTATE_SESSION:{
             UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "A session with the server is open");
             /* A new session was created. We need to create the subscription. */
@@ -83,13 +83,13 @@ stateCallback (UA_Client *client, UA_ClientState clientState) {
             UA_Client_Subscriptions_addMonitoredItem(client, subId, monitorThis, UA_ATTRIBUTEID_VALUE,
                                                      &handler_currentTimeChanged, NULL, &monId, 250);
             if(monId)
-                UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Monitoring UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME', id %u", subId);
+                UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Monitoring UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME', id %u", monId);
         }
-        break; 
+        break;
         case UA_CLIENTSTATE_SESSION_RENEWED:
             UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "A session with the server is open (renewed)");
             /* The session was renewed. We don't need to recreate the subscription. */
-        break; 
+        break;
     }
     return;
 }

+ 2 - 9
examples/custom_datatype/server_types_custom.c

@@ -26,15 +26,12 @@ add3PointDataType(UA_Server *server) {
     p.z = 0.0;
     UA_Variant_setScalar(&dattr.value, &p, &PointType);
 
-
     UA_Server_addVariableTypeNode(server, PointType.typeId,
                                   UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE),
                                   UA_NODEID_NUMERIC(0, UA_NS0ID_HASSUBTYPE),
                                   UA_QUALIFIEDNAME(1, "3D.Point"),
                                   UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE),
-                                  dattr,
-                                  NULL, NULL
-    );
+                                  dattr, NULL, NULL);
 
 }
 
@@ -55,11 +52,7 @@ add3DPointVariable(UA_Server *server) {
                               UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
                               UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
                               UA_QUALIFIEDNAME(1, "3D.Point"),
-                              PointType.typeId,
-                              vattr,
-                              NULL,
-                              NULL
-    );
+                              PointType.typeId, vattr, NULL, NULL);
 }
 
 int main(void) {

+ 0 - 1
examples/encryption/server_basic128rsa15.c

@@ -4,7 +4,6 @@
 #include <signal.h>
 #include <stdio.h>
 #include <errno.h>
-#include <open62541.h>
 #include "open62541.h"
 
 static UA_ByteString loadFile(const char *const path) {

+ 10 - 10
examples/server_instantiation.c

@@ -15,7 +15,7 @@ int main(void) {
 
     UA_ServerConfig *config = UA_ServerConfig_new_default();
     UA_Server *server = UA_Server_new(config);
-    
+
     /* Create a rudimentary objectType
      * 
      * BaseObjectType
@@ -30,43 +30,43 @@ int main(void) {
     UA_ObjectTypeAttributes otAttr = UA_ObjectTypeAttributes_default;
     otAttr.description = UA_LOCALIZEDTEXT("en-US", "A mamal");
     otAttr.displayName = UA_LOCALIZEDTEXT("en-US", "MamalType");
-    UA_Server_addObjectTypeNode(server, UA_NODEID_NUMERIC(1, 10000), 
+    UA_Server_addObjectTypeNode(server, UA_NODEID_NUMERIC(1, 10000),
                                 UA_NODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),
                                 UA_NODEID_NUMERIC(0, UA_NS0ID_HASSUBTYPE),
                                 UA_QUALIFIEDNAME(1, "MamalType"), otAttr, NULL, NULL);
-  
+
     UA_VariableAttributes vAttr = UA_VariableAttributes_default;
     vAttr.description =  UA_LOCALIZEDTEXT("en-US", "This mamals Age in months");
     vAttr.displayName =  UA_LOCALIZEDTEXT("en-US", "Age");
     UA_UInt32 ageVar = 0;
     UA_Variant_setScalar(&vAttr.value, &ageVar, &UA_TYPES[UA_TYPES_UINT32]);
-    UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, 10001), 
+    UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, 10001),
                               UA_NODEID_NUMERIC(1, 10000), UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
                               UA_QUALIFIEDNAME(1, "Age"), UA_NODEID_NULL, vAttr, NULL, NULL);
-  
+
     otAttr = UA_ObjectTypeAttributes_default;
     otAttr.description = UA_LOCALIZEDTEXT("en-US", "A dog, subtype of mamal");
     otAttr.displayName = UA_LOCALIZEDTEXT("en-US", "DogType");
     UA_Server_addObjectTypeNode(server, UA_NODEID_NUMERIC(1, 10002),
                                 UA_NODEID_NUMERIC(1, 10000), UA_NODEID_NUMERIC(0, UA_NS0ID_HASSUBTYPE),
                                 UA_QUALIFIEDNAME(1, "DogType"), otAttr, NULL, NULL);
-    
+
     vAttr = UA_VariableAttributes_default;
     vAttr.description =  UA_LOCALIZEDTEXT("en-US", "This mamals Age in months");
     vAttr.displayName =  UA_LOCALIZEDTEXT("en-US", "Name");
     UA_String defaultName = UA_STRING("unnamed dog");
     UA_Variant_setScalar(&vAttr.value, &defaultName, &UA_TYPES[UA_TYPES_STRING]);
-    UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, 10003), 
+    UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, 10003),
                               UA_NODEID_NUMERIC(1, 10002), UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
                               UA_QUALIFIEDNAME(1, "Name"), UA_NODEID_NULL, vAttr, NULL, NULL);
-    
+
     /* Instatiate a dog named bello:
      * (O) Objects
      *   + O Bello <DogType>
      *     + Age 
      *     + Name
      */
-    
+
     UA_ObjectAttributes oAttr = UA_ObjectAttributes_default;
     oAttr.description = UA_LOCALIZEDTEXT("en-US", "A dog named Bello");
     oAttr.displayName = UA_LOCALIZEDTEXT("en-US", "Bello");
@@ -75,7 +75,7 @@ int main(void) {
                             UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
                             UA_QUALIFIEDNAME(1, "Bello"), UA_NODEID_NUMERIC(1, 10002),
                             oAttr, NULL, NULL);
-    
+
     retval = UA_Server_run(server, &running);
     UA_Server_delete(server);
     UA_ServerConfig_delete(config);

+ 1 - 1
examples/tutorial_datatypes.c

@@ -47,7 +47,7 @@ variables_basic(void) {
     UA_String_deleteMembers(&s4);
     if(!eq)
         return;
-    
+
     /* Structured Type */
     UA_CallRequest cr;
     UA_init(&cr, &UA_TYPES[UA_TYPES_CALLREQUEST]); /* Generic method */

+ 1 - 1
examples/tutorial_server_datasource.c

@@ -70,7 +70,7 @@ addCurrentTimeVariable(UA_Server *server) {
 static void
 beforeReadTime(UA_Server *server,
                const UA_NodeId *sessionId, void *sessionContext,
-               const UA_NodeId *nodeid, void *nodeContext, 
+               const UA_NodeId *nodeid, void *nodeContext,
                const UA_NumericRange *range, const UA_DataValue *data) {
     UA_DateTime now = UA_DateTime_now();
     UA_Variant value;

+ 2 - 2
examples/tutorial_server_object.c

@@ -270,13 +270,13 @@ pumpTypeConstructor(UA_Server *server,
     rpe.isInverse = false;
     rpe.includeSubtypes = false;
     rpe.targetName = UA_QUALIFIEDNAME(1, "Status");
-    
+
     UA_BrowsePath bp;
     UA_BrowsePath_init(&bp);
     bp.startingNode = *nodeId;
     bp.relativePath.elementsSize = 1;
     bp.relativePath.elements = &rpe;
-    
+
     UA_BrowsePathResult bpr =
         UA_Server_translateBrowsePathToNodeIds(server, &bp);
     if(bpr.statusCode != UA_STATUSCODE_GOOD ||

+ 12 - 1
include/ua_client.h

@@ -1,6 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015-2017 (c) Florian Palm
+ *    Copyright 2015 (c) Holger Jeromin
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2018 (c) Thomas Stalder
+ */
 
 #ifndef UA_CLIENT_H_
 #define UA_CLIENT_H_

+ 9 - 1
include/ua_client_highlevel.h

@@ -1,6 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Florian Palm
+ *    Copyright 2016 (c) Chris Iatrou
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Frank Meerkötter
+ */
 
 #ifndef UA_CLIENT_HIGHLEVEL_H_
 #define UA_CLIENT_HIGHLEVEL_H_

+ 17 - 4
include/ua_config.h.in

@@ -110,10 +110,23 @@ extern "C" {
 # include <malloc.h>
 #endif
 
-#define UA_free(ptr) free(ptr)
-#define UA_malloc(size) malloc(size)
-#define UA_calloc(num, size) calloc(num, size)
-#define UA_realloc(ptr, size) realloc(ptr, size)
+#if !defined(UA_FREERTOS)
+
+# define UA_free(ptr) free(ptr)
+# define UA_malloc(size) malloc(size)
+# define UA_calloc(num, size) calloc(num, size)
+# define UA_realloc(ptr, size) realloc(ptr, size)
+
+#else
+
+# include <FreeRTOS.h>
+
+# define UA_free(ptr) vPortFree(ptr)
+# define UA_malloc(size) pvPortMalloc(size)
+# define UA_calloc(num, size) pvPortCalloc(num, size)
+# define UA_realloc(ptr, size) pvPortRealloc(ptr, size)
+
+#endif
 
 #if defined(__GNUC__) || defined(__clang__)
 # define UA_alloca(size) __builtin_alloca (size)

+ 7 - 1
include/ua_constants.h

@@ -1,6 +1,12 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2016 (c) Sten Grüner
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Florian Palm
+ */
 
 #ifndef UA_CONSTANTS_H_
 #define UA_CONSTANTS_H_

+ 7 - 1
include/ua_plugin_access_control.h

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_PLUGIN_ACCESS_CONTROL_H_
 #define UA_PLUGIN_ACCESS_CONTROL_H_
@@ -12,6 +16,8 @@ extern "C" {
 #include "ua_types.h"
 
 /**
+ * .. _access-control:
+ *
  * Access Control Plugin API
  * =========================
  * The access control callback is used to authenticate sessions and grant access

+ 5 - 1
include/ua_plugin_log.h

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this 
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_PLUGIN_LOG_H_
 #define UA_PLUGIN_LOG_H_

+ 12 - 6
include/ua_plugin_network.h

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_PLUGIN_NETWORK_H_
 #define UA_PLUGIN_NETWORK_H_
@@ -10,6 +14,7 @@ extern "C" {
 #endif
 
 #include "ua_server.h"
+#include "ua_plugin_log.h"
 
 /* Forward declarations */
 struct UA_Connection;
@@ -46,12 +51,12 @@ typedef struct {
 } UA_ConnectionConfig;
 
 typedef enum {
+    UA_CONNECTION_CLOSED,      /* The socket has been closed and the connection
+                                * will be deleted */
     UA_CONNECTION_OPENING,     /* The socket is open, but the HEL/ACK handshake
                                 * is not done */
-    UA_CONNECTION_ESTABLISHED, /* The socket is open and the connection
+    UA_CONNECTION_ESTABLISHED  /* The socket is open and the connection
                                 * configured */
-    UA_CONNECTION_CLOSED       /* The socket has been closed and the connection
-                                * will be deleted */
 } UA_ConnectionState;
 
 struct UA_Connection {
@@ -189,10 +194,11 @@ struct UA_ServerNetworkLayer {
 
 /* @param localConf the connection config for this client
  * @param endpointUrl to where to connect
- * @param timeout in ms until the connection try times out if remote not reachable */
+ * @param timeout in ms until the connection try times out if remote not reachable
+ * @param logger the logger to use */
 typedef UA_Connection
 (*UA_ConnectClientConnection)(UA_ConnectionConfig localConf, const char *endpointUrl,
-                              const UA_UInt32 timeout);
+                              const UA_UInt32 timeout, UA_Logger logger);
 
 /**
  * Endpoint URL Parser

+ 6 - 1
include/ua_plugin_nodestore.h

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_SERVER_NODES_H_
 #define UA_SERVER_NODES_H_

+ 4 - 1
include/ua_plugin_pki.h

@@ -1,6 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_PLUGIN_PKI_H_
 #define UA_PLUGIN_PKI_H_

+ 6 - 1
include/ua_plugin_securitypolicy.h

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_PLUGIN_SECURITYPOLICY_H_
 #define UA_PLUGIN_SECURITYPOLICY_H_

+ 13 - 3
include/ua_server.h

@@ -1,6 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2014-2015, 2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_SERVER_H_
 #define UA_SERVER_H_
@@ -25,6 +33,8 @@ typedef struct UA_Server UA_Server;
  * Server
  * ======
  *
+ * .. include:: server_config.rst
+ *
  * .. _server-lifecycle:
  *
  * Server Lifecycle
@@ -123,7 +133,7 @@ UA_Server_removeRepeatedCallback(UA_Server *server, UA_UInt64 callbackId);
 UA_DataValue UA_EXPORT
 UA_Server_read(UA_Server *server, const UA_ReadValueId *item,
                UA_TimestampsToReturn timestamps);
-    
+
 /* Don't use this function. There are typed versions for every supported
  * attribute. */
 UA_StatusCode UA_EXPORT
@@ -943,7 +953,7 @@ UA_Server_addMethodNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
                         const UA_NodeId referenceTypeId,
                         const UA_QualifiedName browseName,
                         const UA_MethodAttributes attr, UA_MethodCallback method,
-                        size_t inputArgumentsSize, const UA_Argument* inputArguments, 
+                        size_t inputArgumentsSize, const UA_Argument* inputArguments,
                         size_t outputArgumentsSize, const UA_Argument* outputArguments,
                         void *nodeContext, UA_NodeId *outNewNodeId);
 

+ 39 - 5
include/ua_server_config.h

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Henrik Norrman
+ */
 
 #ifndef UA_SERVER_CONFIG_H_
 #define UA_SERVER_CONFIG_H_
@@ -18,9 +23,26 @@ extern "C" {
 #include "ua_plugin_nodestore.h"
 
 /**
+ * .. _server-configuration:
+ *
  * Server Configuration
- * ====================
- * The configuration structure is passed to the server during initialization. */
+ * --------------------
+
+ * The configuration structure is passed to the server during initialization.
+ * The server expects that the configuration is not modified during runtime.
+ * Currently, only one server can use a configuration at a time. During
+ * shutdown, the server will clean up the parts of the configuration that are
+ * modified at runtime through the provided API.
+ *
+ * Examples for configurations are provided in the ``/plugins`` folder.
+ * The usual usage is as follows:
+ *
+ * 1. Create a server configuration with default settings as a starting point
+ * 2. Modifiy the configuration, e.g. by adding a server certificate
+ * 3. Instantiate a server with it
+ * 4. After shutdown of the server, clean up the configuration (free memory)
+ *
+ * The :ref:`tutorials` provide a good starting point for this. */
 
 typedef struct {
     UA_UInt32 min;
@@ -40,6 +62,8 @@ struct UA_ServerConfig {
     UA_BuildInfo buildInfo;
     UA_ApplicationDescription applicationDescription;
     UA_ByteString serverCertificate;
+
+    /* MDNS Discovery */
 #ifdef UA_ENABLE_DISCOVERY
     UA_String mdnsServerName;
     size_t serverCapabilitiesSize;
@@ -49,6 +73,10 @@ struct UA_ServerConfig {
     /* Custom DataTypes */
     size_t customDataTypesSize;
     UA_DataType *customDataTypes;
+    /**
+     * .. note:: See the section on :ref:`generic-types`. Examples for working
+     *    with custom data types are provided in
+     *    ``/examples/custom_datatype/``. */
 
     /* Nodestore */
     UA_Nodestore nodestore;
@@ -57,16 +85,22 @@ struct UA_ServerConfig {
     size_t networkLayersSize;
     UA_ServerNetworkLayer *networkLayers;
     UA_String customHostname;
-    
+
     /* Available endpoints */
     size_t endpointsSize;
     UA_Endpoint *endpoints;
 
-    /* Global Node Lifecycle */
+    /* Node Lifecycle callbacks */
     UA_GlobalNodeLifecycle nodeLifecycle;
+    /**
+     * .. note:: See the section for :ref:`node lifecycle
+     *    handling<node-lifecycle>`. */
 
     /* Access Control */
     UA_AccessControl accessControl;
+    /**
+     * .. note:: See the section for :ref:`access-control
+     *    handling<access-control>`. */
 
     /* Certificate Verification */
     UA_CertificateVerification certificateVerification;

+ 12 - 1
include/ua_types.h

@@ -1,6 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014 (c) Leon Urbas
+ *    Copyright 2014, 2016-2017 (c) Florian Palm
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015 (c) Nick Goossens
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Thomas Stalder
+ */
 
 #ifndef UA_TYPES_H_
 #define UA_TYPES_H_

+ 6 - 2
plugins/ua_accesscontrol_default.c

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_accesscontrol_default.h"
 
@@ -137,7 +141,7 @@ allowDeleteNode_default(const UA_NodeId *sessionId, void *sessionContext,
                         const UA_DeleteNodesItem *item) {
     return true;
 }
-      
+
 UA_Boolean
 allowDeleteReference_default(const UA_NodeId *sessionId, void *sessionContext,
                              const UA_DeleteReferencesItem *item) {

+ 5 - 1
plugins/ua_accesscontrol_default.h

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_ACCESSCONTROL_DEFAULT_H_
 #define UA_ACCESSCONTROL_DEFAULT_H_

+ 20 - 1
plugins/ua_clock.c

@@ -1,5 +1,10 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Thomas Stalder
+ */
 
 /* Enable POSIX features */
 #if !defined(_XOPEN_SOURCE) && !defined(_WRS_KERNEL)
@@ -40,6 +45,10 @@
 
 #include "ua_types.h"
 
+#if defined(UA_FREERTOS)
+#include <task.h>
+#endif
+
 UA_DateTime UA_DateTime_now(void) {
 #if defined(_WIN32)
     /* Windows filetime has the same definition as UA_DateTime */
@@ -96,9 +105,19 @@ UA_DateTime UA_DateTime_nowMonotonic(void) {
     mach_port_deallocate(mach_task_self(), cclock);
     return (mts.tv_sec * UA_DATETIME_SEC) + (mts.tv_nsec / 100);
 #elif !defined(CLOCK_MONOTONIC_RAW)
+# if defined(UA_FREERTOS)
+    portTickType TaskTime = xTaskGetTickCount();
+    UA_DateTimeStruct UATime;
+    UATime.milliSec = (UA_UInt16) TaskTime;
+    struct timespec ts;
+    ts.tv_sec = UATime.milliSec/1000;
+    ts.tv_nsec = (UATime.milliSec % 1000)* 1000000;
+    return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
+# else
     struct timespec ts;
     clock_gettime(CLOCK_MONOTONIC, &ts);
     return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
+# endif
 #else
     struct timespec ts;
     clock_gettime(CLOCK_MONOTONIC_RAW, &ts);

+ 9 - 2
plugins/ua_config_default.c

@@ -1,5 +1,12 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017-2018 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Thomas Stalder
+ */
 
 #include "ua_plugin_securitypolicy.h"
 #include "ua_config_default.h"
@@ -271,7 +278,7 @@ addDefaultNetworkLayers(UA_ServerConfig *conf, UA_UInt16 portNumber) {
         return UA_STATUSCODE_BADOUTOFMEMORY;
 
     conf->networkLayers[0] =
-        UA_ServerNetworkLayerTCP(UA_ConnectionConfig_default, portNumber);
+        UA_ServerNetworkLayerTCP(UA_ConnectionConfig_default, portNumber, conf->logger);
     conf->networkLayersSize = 1;
 
     return UA_STATUSCODE_GOOD;

+ 7 - 2
plugins/ua_config_default.h

@@ -1,5 +1,10 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_CONFIG_DEFAULT_H_
 #define UA_CONFIG_DEFAULT_H_
@@ -60,7 +65,7 @@ UA_ServerConfig_new_default(void) {
 UA_EXPORT void
 UA_ServerConfig_set_customHostname(UA_ServerConfig *config,
                                    const UA_String customHostname);
-  
+
 /* Frees allocated memory in the server config */
 UA_EXPORT void
 UA_ServerConfig_delete(UA_ServerConfig *config);

+ 4 - 1
plugins/ua_debug_dump_pkgs.c

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_util.h"
 

+ 4 - 1
plugins/ua_log_socket_error.h

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_LOG_SOCKET_ERROR_H_
 #define UA_LOG_SOCKET_ERROR_H_

+ 5 - 1
plugins/ua_log_stdout.c

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Thomas Stalder
+ */
 
 #include <stdio.h>
 #include "ua_log_stdout.h"

+ 4 - 1
plugins/ua_log_stdout.h

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016 (c) Julius Pfrommer, Fraunhofer IOSB
+ */
 
 #ifndef UA_LOG_STDOUT_H_
 #define UA_LOG_STDOUT_H_

+ 132 - 67
plugins/ua_network_tcp.c

@@ -1,5 +1,12 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Jose Cabral
+ *    Copyright 2017 (c) Thomas Stalder
+ */
 
 /* Enable POSIX features */
 #if !defined(_XOPEN_SOURCE) && !defined(_WRS_KERNEL)
@@ -31,11 +38,19 @@
 
 #include "ua_network_tcp.h"
 #include "ua_log_stdout.h"
-#include "queue.h"
+#include "../deps/queue.h"
 
 #include <stdio.h> // snprintf
 #include <string.h> // memset
-#include <errno.h>
+
+#if !defined(UA_FREERTOS)
+# include <errno.h>
+#else
+# define AI_PASSIVE 0x01
+# define TRUE 1
+# define FALSE 0
+# define ioctl ioctlsocket
+#endif
 
 #ifdef _WIN32
 # include <winsock2.h>
@@ -46,45 +61,68 @@
 # define OPTVAL_TYPE char
 # define ERR_CONNECTION_PROGRESS WSAEWOULDBLOCK
 # define UA_sleep_ms(X) Sleep(X)
-#else
-# define CLOSESOCKET(S) close(S)
+#else /* _WIN32 */
+# if defined(UA_FREERTOS)
+#  define UA_FREERTOS_HOSTNAME "10.200.4.114"
+static inline int gethostname_freertos(char* name, size_t len){
+  if(strlen(UA_FREERTOS_HOSTNAME) > (len))
+    return -1;
+  strcpy(name, UA_FREERTOS_HOSTNAME);
+  return 0;
+}
+#define gethostname gethostname_freertos
+#  include <lwip/tcpip.h>
+#  include <lwip/netdb.h>
+#  define CLOSESOCKET(S) lwip_close(S)
+#  define sockaddr_storage sockaddr
+#  ifdef BYTE_ORDER
+#   undef BYTE_ORDER
+#  endif
+#  define UA_sleep_ms(X) vTaskDelay(pdMS_TO_TICKS(X))
+# else /* Not freeRTOS */
+#  define CLOSESOCKET(S) close(S)
+#  include <arpa/inet.h>
+#  include <netinet/in.h>
+#  include <netdb.h>
+#  include <sys/ioctl.h>
+#  if defined(_WRS_KERNEL)
+#   include <hostLib.h>
+#   include <selectLib.h>
+#   define UA_sleep_ms(X)                            \
+    {                                                \
+    struct timespec timeToSleep;                     \
+      timeToSleep.tv_sec = X / 1000;                 \
+      timeToSleep.tv_nsec = 1000000 * (X % 1000);    \
+      nanosleep(&timeToSleep, NULL);                 \
+    }
+#  else /* defined(_WRS_KERNEL) */
+#   include <sys/select.h>
+#   define UA_sleep_ms(X) usleep(X * 1000)
+#  endif /* defined(_WRS_KERNEL) */
+# endif /* Not freeRTOS */
+
 # define SOCKET int
 # define WIN32_INT
 # define OPTVAL_TYPE int
 # define ERR_CONNECTION_PROGRESS EINPROGRESS
-# include <arpa/inet.h>
-# include <netinet/in.h>
-# ifndef _WRS_KERNEL
-#  include <sys/select.h>
-#  define UA_sleep_ms(X) usleep(X * 1000)
-# else
-#  include <hostLib.h>
-#  include <selectLib.h>
-#  define UA_sleep_ms(X)                           \
-   {                                               \
-   struct timespec timeToSleep;                    \
-   timeToSleep.tv_sec = X / 1000;                  \
-   timeToSleep.tv_nsec = 1000000 * (X % 1000);     \
-   nanosleep(&timeToSleep, NULL);                  \
-   }
-# endif
-# include <sys/ioctl.h>
+
+
 # include <fcntl.h>
 # include <unistd.h> // read, write, close
-# include <netdb.h>
+
 # ifdef __QNX__
 #  include <sys/socket.h>
 # endif
-#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
-# include <sys/param.h>
-# if defined(BSD)
-#  include<sys/socket.h>
+# if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+#  include <sys/param.h>
+#  if defined(BSD)
+#   include<sys/socket.h>
+#  endif
 # endif
-#endif
-# ifndef __CYGWIN__
+# if !defined(__CYGWIN__) && !defined(UA_FREERTOS)
 #  include <netinet/tcp.h>
 # endif
-#endif
+#endif /* _WIN32 */
 
 /* unsigned int for windows and workaround to a glibc bug */
 /* Additionally if GNU_LIBRARY is not defined, it may be using
@@ -241,7 +279,7 @@ socket_set_nonblocking(SOCKET sockfd) {
     u_long iMode = 1;
     if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
         return UA_STATUSCODE_BADINTERNALERROR;
-#elif defined(_WRS_KERNEL)
+#elif defined(_WRS_KERNEL) || defined(UA_FREERTOS)
     int on = TRUE;
     if(ioctl(sockfd, FIONBIO, &on) < 0)
       return UA_STATUSCODE_BADINTERNALERROR;
@@ -259,7 +297,7 @@ socket_set_blocking(SOCKET sockfd) {
     u_long iMode = 0;
     if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
         return UA_STATUSCODE_BADINTERNALERROR;
-#elif defined(_WRS_KERNEL)
+#elif defined(_WRS_KERNEL) || defined(UA_FREERTOS)
     int on = FALSE;
     if(ioctl(sockfd, FIONBIO, &on) < 0)
       return UA_STATUSCODE_BADINTERNALERROR;
@@ -285,6 +323,7 @@ typedef struct ConnectionEntry {
 } ConnectionEntry;
 
 typedef struct {
+    UA_Logger logger;
     UA_ConnectionConfig conf;
     UA_UInt16 port;
     UA_Int32 serverSockets[FD_SETSIZE];
@@ -319,12 +358,13 @@ ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
     if(setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
                (const char *)&dummy, sizeof(dummy)) < 0) {
         UA_LOG_SOCKET_ERRNO_WRAP(
-                UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+                UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK,
                              "Cannot set socket option TCP_NODELAY. Error: %s",
                              errno_str));
         return UA_STATUSCODE_BADUNEXPECTEDERROR;
     }
 
+#if !defined(UA_FREERTOS)
     /* Get the peer name for logging */
     char remote_name[100];
     int res = getnameinfo((struct sockaddr*)remote,
@@ -332,16 +372,16 @@ ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
                           remote_name, sizeof(remote_name),
                           NULL, 0, NI_NUMERICHOST);
     if(res == 0) {
-        UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
                     "Connection %i | New connection over TCP from %s",
                     (int)newsockfd, remote_name);
     } else {
-        UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                                                 "Connection %i | New connection over TCP, "
                                                         "getnameinfo failed with error: %s",
                                                 (int)newsockfd, errno_str));
     }
-
+#endif
     /* Allocate and initialize the connection */
     ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
     if(!e){
@@ -379,7 +419,7 @@ addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
     if(newsock < 0)
 #endif
     {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                        "Error opening the server socket");
         return;
     }
@@ -387,26 +427,29 @@ addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
     /* Some Linux distributions have net.ipv6.bindv6only not activated. So
      * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
      * AF_INET6 sockets only for IPv6. */
+
     int optval = 1;
+#if !defined(UA_FREERTOS)
     if(ai->ai_family == AF_INET6 &&
        setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
                   (const char*)&optval, sizeof(optval)) == -1) {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                        "Could not set an IPv6 socket to IPv6 only");
         CLOSESOCKET(newsock);
         return;
     }
-
+#endif
     if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
                   (const char *)&optval, sizeof(optval)) == -1) {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                        "Could not make the socket reusable");
         CLOSESOCKET(newsock);
         return;
     }
 
+
     if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                        "Could not set the server socket to nonblocking");
         CLOSESOCKET(newsock);
         return;
@@ -415,7 +458,7 @@ addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
     /* Bind socket to address */
     if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
         UA_LOG_SOCKET_ERRNO_WRAP(
-            UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+            UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                            "Error binding a server socket: %s", errno_str));
         CLOSESOCKET(newsock);
         return;
@@ -424,7 +467,7 @@ addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
     /* Start listening */
     if(listen(newsock, MAXBACKLOG) < 0) {
         UA_LOG_SOCKET_ERRNO_WRAP(
-                UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+                UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                        "Error listening on server socket: %s", errno_str));
         CLOSESOCKET(newsock);
         return;
@@ -461,7 +504,7 @@ ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHo
                                         layer->port);
 #endif
         du.data = (UA_Byte*)discoveryUrl;
-    }else{    
+    }else{
         char hostname[256];
         if(gethostname(hostname, 255) == 0) {
             char discoveryUrl[256];
@@ -490,7 +533,13 @@ ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHo
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
     hints.ai_flags = AI_PASSIVE;
+#if defined(UA_FREERTOS)
+    hints.ai_protocol = IPPROTO_TCP;
+    char hostname[] = UA_FREERTOS_HOSTNAME;
+    if(getaddrinfo(hostname, portno, &hints, &res) != 0)
+#else
     if(getaddrinfo(NULL, portno, &hints, &res) != 0)
+#endif
         return UA_STATUSCODE_BADINTERNALERROR;
 
     /* There might be serveral addrinfos (for different network cards,
@@ -502,7 +551,7 @@ ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHo
         addServerSocket(layer, ai);
     freeaddrinfo(res);
 
-    UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+    UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
                 "TCP network layer listening on %.*s",
                 (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
     return UA_STATUSCODE_GOOD;
@@ -545,7 +594,7 @@ ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
     struct timeval tmptv = {0, timeout * 1000};
     if (select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
         UA_LOG_SOCKET_ERRNO_WRAP(
-            UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+            UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                                   "Socket select failed with %s", errno_str));
         // we will retry, so do not return bad
         return UA_STATUSCODE_GOOD;
@@ -567,7 +616,7 @@ ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
 #endif
             continue;
 
-        UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
                     "Connection %i | New TCP connection on server socket %i",
                     (int)newsockfd, layer->serverSockets[i]);
 
@@ -580,7 +629,7 @@ ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
     LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
         if ((e->connection.state == UA_CONNECTION_OPENING) &&
             (now > (e->connection.openingDate + (NOHELLOTIMEOUT * UA_DATETIME_MSEC)))){
-            UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+            UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
                         "Connection %i | Closed by the server (no Hello Message)",
                          e->connection.sockfd);
             LIST_REMOVE(e, pointers);
@@ -593,7 +642,7 @@ ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
            !UA_fd_isset(e->connection.sockfd, &fdset))
           continue;
 
-        UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
                     "Connection %i | Activity on the socket",
                     e->connection.sockfd);
 
@@ -607,11 +656,11 @@ ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
         } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
             /* The socket is shutdown but not closed */
             if(e->connection.state != UA_CONNECTION_CLOSED) {
-                UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+                UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
                             "Connection %i | Closed by the client",
                             e->connection.sockfd);
             } else {
-                UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+                UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
                             "Connection %i | Closed by the server",
                             e->connection.sockfd);
             }
@@ -626,7 +675,7 @@ ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
 static void
 ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
     ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
-    UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+    UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
                 "Shutting down the TCP network layer");
 
     /* Close the server sockets */
@@ -670,7 +719,7 @@ ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
 }
 
 UA_ServerNetworkLayer
-UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
+UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port, UA_Logger logger) {
     UA_ServerNetworkLayer nl;
     memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
     ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
@@ -678,6 +727,7 @@ UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
     if(!layer)
         return nl;
 
+    layer->logger = (logger != NULL ? logger : UA_Log_Stdout);
     layer->conf = conf;
     layer->port = port;
 
@@ -704,7 +754,8 @@ ClientNetworkLayerTCP_close(UA_Connection *connection) {
 
 UA_Connection
 UA_ClientConnectionTCP(UA_ConnectionConfig conf,
-                       const char *endpointUrl, const UA_UInt32 timeout) {
+                       const char *endpointUrl, const UA_UInt32 timeout,
+                       UA_Logger logger) {
 #ifdef _WIN32
     WORD wVersionRequested;
     WSADATA wsaData;
@@ -712,9 +763,13 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
     WSAStartup(wVersionRequested, &wsaData);
 #endif
 
+    if(logger == NULL) {
+        logger = UA_Log_Stdout;
+    }
+
     UA_Connection connection;
     memset(&connection, 0, sizeof(UA_Connection));
-    connection.state = UA_CONNECTION_OPENING;
+    connection.state = UA_CONNECTION_CLOSED;
     connection.localConf = conf;
     connection.remoteConf = conf;
     connection.send = connection_write;
@@ -735,7 +790,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
         UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
                             &port, &pathString);
     if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                        "Server url is invalid: %s", endpointUrl);
         return connection;
     }
@@ -744,7 +799,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
 
     if(port == 0) {
         port = 4840;
-        UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
                     "No port defined, using default port %d", port);
     }
 
@@ -752,6 +807,9 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
     memset(&hints, 0, sizeof(hints));
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
+#if defined(UA_FREERTOS)
+    hints.ai_protocol = IPPROTO_TCP;
+#endif
     char portStr[6];
 #ifndef _MSC_VER
     snprintf(portStr, 6, "%d", port);
@@ -760,9 +818,16 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
 #endif
     int error = getaddrinfo(hostname, portStr, &hints, &server);
     if(error != 0 || !server) {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+#if !defined(UA_FREERTOS)
+        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
+
                        "DNS lookup of %s failed with error %s",
                        hostname, gai_strerror(error));
+#else
+        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
+                        "DNS lookup of %s failed with error",
+                        hostname);
+#endif
         return connection;
     }
 
@@ -775,8 +840,6 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
      * want to try to connect. So use a loop and retry until timeout is
      * reached. */
     do {
-        connection.state = UA_CONNECTION_OPENING;
-
         /* Get a socket */
         clientsockfd = socket(server->ai_family,
                               server->ai_socktype,
@@ -786,18 +849,20 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
     #else
         if(clientsockfd < 0) {
     #endif
-            UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+            UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                                                     "Could not create client socket: %s", errno_str));
             freeaddrinfo(server);
             return connection;
         }
 
+        connection.state = UA_CONNECTION_OPENING;
+
         /* Connect to the server */
         connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
 
         /* Non blocking connect to be able to timeout */
         if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
-            UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+            UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                            "Could not set the client socket to nonblocking");
             ClientNetworkLayerTCP_close(&connection);
             freeaddrinfo(server);
@@ -810,7 +875,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
         if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
             ClientNetworkLayerTCP_close(&connection);
             UA_LOG_SOCKET_ERRNO_WRAP(
-                    UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+                    UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                                           "Connection to %s failed with error: %s",
                                           endpointUrl, errno_str));
             freeaddrinfo(server);
@@ -850,7 +915,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
                     /* connection refused happens on localhost or local ip without timeout */
                     if (so_error != ECONNREFUSED) {
                         ClientNetworkLayerTCP_close(&connection);
-                        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+                        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                                        "Connection to %s failed with error: %s",
                                        endpointUrl, strerror(ret == 0 ? so_error : errno__));
                         freeaddrinfo(server);
@@ -879,7 +944,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
         /* connection timeout */
         if (connection.state != UA_CONNECTION_CLOSED)
             ClientNetworkLayerTCP_close(&connection);
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                        "Trying to connect to %s timed out",
                        endpointUrl);
         return connection;
@@ -888,7 +953,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
 
     /* We are connected. Reset socket to blocking */
     if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                        "Could not set the client socket to blocking");
         ClientNetworkLayerTCP_close(&connection);
         return connection;
@@ -899,7 +964,7 @@ UA_ClientConnectionTCP(UA_ConnectionConfig conf,
     int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
                                 SO_NOSIGPIPE, (void*)&val, sizeof(val));
     if(sso_result < 0)
-        UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
+        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
                        "Couldn't set SO_NOSIGPIPE");
 #endif
 

+ 7 - 3
plugins/ua_network_tcp.h

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016 (c) Julius Pfrommer, Fraunhofer IOSB
+ */
 
 #ifndef UA_NETWORK_TCP_H_
 #define UA_NETWORK_TCP_H_
@@ -10,12 +13,13 @@ extern "C" {
 
 #include "ua_server.h"
 #include "ua_client.h"
+#include "ua_plugin_log.h"
 
 UA_ServerNetworkLayer UA_EXPORT
-UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port);
+UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port, UA_Logger logger);
 
 UA_Connection UA_EXPORT
-UA_ClientConnectionTCP(UA_ConnectionConfig conf, const char *endpointUrl, const UA_UInt32 timeout);
+UA_ClientConnectionTCP(UA_ConnectionConfig conf, const char *endpointUrl, const UA_UInt32 timeout, UA_Logger logger);
 
 #ifdef __cplusplus
 } // extern "C"

+ 18 - 8
plugins/ua_network_udp.c

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_network_udp.h"
 #include <stdio.h>
@@ -13,17 +17,23 @@
 # include <errno.h> // errno, EINTR
 # include <fcntl.h> // fcntl
 # include <strings.h> //bzero
+
+#if defined(UA_FREERTOS)
+ # include <lwip/udp.h>
+ # include <lwip/tcpip.h>
+#else
 # ifndef _WRS_KERNEL
 #  include <sys/select.h>
 # else
-# include <selectLib.h>
+#  include <selectLib.h>
 # endif
-# include <netinet/in.h>
-# include <netinet/tcp.h>
-# include <sys/socketvar.h>
-# include <sys/ioctl.h>
-# include <unistd.h> // read, write, close
-# include <arpa/inet.h>
+#  include <netinet/in.h>
+#  include <netinet/tcp.h>
+#  include <sys/socketvar.h>
+#  include <sys/ioctl.h>
+#  include <unistd.h> // read, write, close
+#  include <arpa/inet.h>
+#endif
 #ifdef __QNX__
 #include <sys/socket.h>
 #endif

+ 4 - 1
plugins/ua_network_udp.h

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2016 (c) Julius Pfrommer, Fraunhofer IOSB
+ */
 
 #ifndef UA_NETWORK_UDP_H_
 #define UA_NETWORK_UDP_H_

+ 5 - 1
plugins/ua_nodestore_default.c

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_nodestore_default.h"
 

+ 5 - 1
plugins/ua_nodestore_default.h

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_NODESTORE_DEFAULT_H_
 #define UA_NODESTORE_DEFAULT_H_

+ 4 - 1
plugins/ua_pki_certificate.c

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_pki_certificate.h"
 

+ 4 - 1
plugins/ua_pki_certificate.h

@@ -1,5 +1,8 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_PKI_CERTIFICATE_H_
 #define UA_PKI_CERTIFICATE_H_

+ 6 - 3
plugins/ua_securitypolicy_basic128rsa15.c

@@ -1,6 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include <mbedtls/aes.h>
 #include <mbedtls/md.h>
@@ -87,7 +90,7 @@ asym_verify_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
 
     /* Set the RSA settings */
     mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
-    mbedtls_rsa_set_padding(rsaContext, MBEDTLS_RSA_PKCS_V15, 0); 
+    mbedtls_rsa_set_padding(rsaContext, MBEDTLS_RSA_PKCS_V15, 0);
 
     /* Verify */
     int mbedErr = mbedtls_pk_verify(&cc->remoteCertificate.pk,
@@ -302,7 +305,7 @@ sym_verify_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
         return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
     }
 
-    Basic128Rsa15_PolicyContext *pc = 
+    Basic128Rsa15_PolicyContext *pc =
         (Basic128Rsa15_PolicyContext*)securityPolicy->policyContext;
 
     unsigned char mac[UA_SHA1_LENGTH];

+ 4 - 1
plugins/ua_securitypolicy_basic128rsa15.h

@@ -1,6 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_SECURITYPOLICY_BASIC128RSA15_H_
 #define UA_SECURITYPOLICY_BASIC128RSA15_H_

+ 5 - 1
plugins/ua_securitypolicy_none.c

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_types.h"
 #include "ua_securitypolicy_none.h"

+ 5 - 1
plugins/ua_securitypolicy_none.h

@@ -1,5 +1,9 @@
 /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
- * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
+ * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. 
+ *
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_SECURITYPOLICY_NONE_H_
 #define UA_SECURITYPOLICY_NONE_H_

+ 15 - 1
src/client/ua_client.c

@@ -1,6 +1,20 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015 (c) hfaham
+ *    Copyright 2015-2017 (c) Florian Palm
+ *    Copyright 2017 (c) Thomas Stalder
+ *    Copyright 2015 (c) Holger Jeromin
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016 (c) TorbenD
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lykurg
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_client.h"
 #include "ua_client_internal.h"

+ 10 - 3
src/client/ua_client_connect.c

@@ -1,6 +1,12 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017-2018 (c) Thomas Stalder
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_client.h"
 #include "ua_client_internal.h"
@@ -197,7 +203,7 @@ openSecureChannel(UA_Client *client, UA_Boolean renew) {
                                     UA_DateTime_nowMonotonic() +
                                     ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC),
                                     &requestId);
-                                    
+
     if(retval != UA_STATUSCODE_GOOD) {
         UA_Client_close(client);
         return retval;
@@ -385,7 +391,8 @@ UA_Client_connectInternal(UA_Client *client, const char *endpointUrl,
     UA_StatusCode retval = UA_STATUSCODE_GOOD;
     client->connection =
         client->config.connectionFunc(client->config.localConnectionConfig,
-                                      endpointUrl, client->config.timeout);
+                                      endpointUrl, client->config.timeout,
+                                      client->config.logger);
     if(client->connection.state != UA_CONNECTION_OPENING) {
         retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
         goto cleanup;

+ 6 - 1
src/client/ua_client_discovery.c

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_client.h"
 #include "ua_client_internal.h"

+ 8 - 1
src/client/ua_client_highlevel.c

@@ -1,6 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Florian Palm
+ *    Copyright 2016 (c) Chris Iatrou
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_client.h"
 #include "ua_client_highlevel.h"

+ 16 - 7
src/client/ua_client_highlevel_subscriptions.c

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016 (c) Sten Grüner
+ *    Copyright 2017-2018 (c) Thomas Stalder
+ *    Copyright 2016-2017 (c) Florian Palm
+ *    Copyright 2017 (c) Frank Meerkötter
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_client_highlevel.h"
 #include "ua_client_internal.h"
@@ -191,7 +200,7 @@ addMonitoredItems(UA_Client *client, const UA_UInt32 subscriptionId,
         newMonitoredItemIds[i] = newMon->monitoredItemId;
         UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
                      "Created a monitored item with client handle %u",
-                     client->monitoredItemHandles);
+                     newMon->clientHandle);
     }
 
  cleanup:
@@ -207,7 +216,7 @@ addMonitoredItems(UA_Client *client, const UA_UInt32 subscriptionId,
 
 UA_StatusCode
 UA_Client_Subscriptions_addMonitoredItems(UA_Client *client, const UA_UInt32 subscriptionId,
-                                          UA_MonitoredItemCreateRequest *items, size_t itemsSize, 
+                                          UA_MonitoredItemCreateRequest *items, size_t itemsSize,
                                           UA_MonitoredItemHandlingFunction *hfs,
                                           void **hfContexts, UA_StatusCode *itemResults,
                                           UA_UInt32 *newMonitoredItemIds) {
@@ -239,7 +248,7 @@ UA_Client_Subscriptions_addMonitoredItem(UA_Client *client, UA_UInt32 subscripti
 
 UA_StatusCode
 UA_Client_Subscriptions_addMonitoredEvents(UA_Client *client, const UA_UInt32 subscriptionId,
-                                           UA_MonitoredItemCreateRequest *items, size_t itemsSize, 
+                                           UA_MonitoredItemCreateRequest *items, size_t itemsSize,
                                            UA_MonitoredEventHandlingFunction *hfs,
                                            void **hfContexts, UA_StatusCode *itemResults,
                                            UA_UInt32 *newMonitoredItemIds) {
@@ -503,7 +512,7 @@ UA_Client_Subscriptions_manuallySendPublishRequest(UA_Client *client) {
 
         UA_PublishResponse response = UA_Client_Service_publish(client, request);
         UA_Client_processPublishResponse(client, &request, &response);
-        
+
         now = UA_DateTime_nowMonotonic();
         if(now > maxDate) {
             moreNotifications = UA_FALSE;
@@ -511,11 +520,11 @@ UA_Client_Subscriptions_manuallySendPublishRequest(UA_Client *client) {
         } else {
             moreNotifications = response.moreNotifications;
         }
-        
+
         UA_PublishResponse_deleteMembers(&response);
         UA_PublishRequest_deleteMembers(&request);
     }
-    
+
     if(client->state < UA_CLIENTSTATE_SESSION)
         return UA_STATUSCODE_BADSERVERNOTCONNECTED;
 

+ 10 - 2
src/client/ua_client_internal.h

@@ -1,13 +1,21 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Florian Palm
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_CLIENT_INTERNAL_H_
 #define UA_CLIENT_INTERNAL_H_
 
 #include "ua_securechannel.h"
 #include "ua_client_highlevel.h"
-#include "queue.h"
+#include "../../deps/queue.h"
 
  /**************************/
  /* Subscriptions Handling */

+ 7 - 3
src/server/ua_mdns.c

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ */
 
 /* Enable POSIX features */
 #if !defined(_XOPEN_SOURCE) && !defined(_WRS_KERNEL)
@@ -401,7 +405,7 @@ mdns_set_address_record_if(UA_Server *server, const char *fullServiceDomain,
     // [servername]-[hostname]._opcua-tcp._tcp.local. A [ip].
     mdns_record_t *r = mdnsd_shared(server->mdnsDaemon, fullServiceDomain, QTYPE_A, 600);
     mdnsd_set_raw(server->mdnsDaemon, r, addr, addr_len);
-    
+
     // [hostname]. A [ip].
     r = mdnsd_shared(server->mdnsDaemon, localDomain, QTYPE_A, 600);
     mdnsd_set_raw(server->mdnsDaemon, r, addr, addr_len);
@@ -442,7 +446,7 @@ getInterfaces(UA_Server *server) {
             adapter_addresses = NULL;
             continue;
         }
-        
+
         /* Unexpected error */
         UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
                      "GetAdaptersAddresses returned an unexpected error. "

+ 4 - 1
src/server/ua_mdns_internal.h

@@ -1,6 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_MDNS_INTERNAL_H
 #define UA_MDNS_INTERNAL_H

+ 10 - 1
src/server/ua_nodes.c

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015, 2017 (c) Florian Palm
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Julian Grothoff
+ */
 
 #include "ua_server_internal.h"
 #include "ua_types_encoding_binary.h"

+ 9 - 1
src/server/ua_securechannel_manager.c

@@ -1,6 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_securechannel_manager.h"
 #include "ua_session.h"

+ 8 - 2
src/server/ua_securechannel_manager.h

@@ -1,6 +1,12 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_CHANNEL_MANAGER_H_
 #define UA_CHANNEL_MANAGER_H_
@@ -12,7 +18,7 @@ extern "C" {
 #include "ua_util.h"
 #include "ua_server.h"
 #include "ua_securechannel.h"
-#include "queue.h"
+#include "../../deps/queue.h"
 
 typedef struct channel_list_entry {
     UA_SecureChannel channel;

+ 14 - 1
src/server/ua_server.c

@@ -1,6 +1,19 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015 (c) LEvertz
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016 (c) Julian Grothoff
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_types.h"
 #include "ua_server_internal.h"

+ 14 - 2
src/server/ua_server_binary.c

@@ -1,6 +1,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2016 (c) Sten Grüner
+ *    Copyright 2014-2015, 2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016 (c) Joakim L. Gilje
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) TorbenD
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_util.h"
 #include "ua_server_internal.h"
@@ -547,7 +559,7 @@ processMSG(UA_Server *server, UA_SecureChannel *channel,
         /* Was processed before...*/
         retval = UA_MessageContext_encode(&mc, response, responseType);
         break;
-    case UA_SERVICETYPE_INSITU: 
+    case UA_SERVICETYPE_INSITU:
         retval = ((UA_InSituService)service)
             (server, session, &mc, request, (UA_ResponseHeader*)response);
         break;

+ 5 - 1
src/server/ua_server_discovery.c

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_server_internal.h"
 #include "ua_client.h"

+ 10 - 1
src/server/ua_server_internal.h

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Julian Grothoff
+ */
 
 #ifndef UA_SERVER_INTERNAL_H_
 #define UA_SERVER_INTERNAL_H_

+ 9 - 2
src/server/ua_server_ns0.c

@@ -1,6 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Thomas Bender
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017 (c) Henrik Norrman
+ */
 
 #include "ua_server_internal.h"
 #include "ua_namespace0.h"
@@ -613,7 +620,7 @@ UA_Server_initNS0(UA_Server *server) {
                                &enabledFlag, &UA_TYPES[UA_TYPES_BOOLEAN]);
 
     /* ServerStatus */
-    UA_DataSource serverStatus = {readStatus, NULL}; 
+    UA_DataSource serverStatus = {readStatus, NULL};
     retVal |= UA_Server_setVariableNode_dataSource(server,
                         UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS), serverStatus);
 

+ 9 - 1
src/server/ua_server_utils.c

@@ -1,6 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Florian Palm
+ *    Copyright 2017-2018 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Julian Grothoff
+ */
 
 #include "ua_server_internal.h"
 

+ 16 - 5
src/server/ua_server_worker.c

@@ -1,6 +1,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015 (c) Nick Goossens
+ *    Copyright 2015 (c) Jörg Schüler-Maroldt
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Florian Palm
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) Jonas Green
+ */
 
 #include "ua_util.h"
 #include "ua_server_internal.h"
@@ -40,7 +52,7 @@ typedef struct {
     UA_Boolean delayed;         /* Is it a delayed callback? */
     UA_Boolean countersSampled; /* Have the worker counters been sampled? */
     UA_UInt32 workerCounters[]; /* Counter value for each worker */
-} WorkerCallback; 
+} WorkerCallback;
 
 /* Forward Declaration */
 static void
@@ -74,7 +86,7 @@ workerLoop(UA_Worker *worker) {
             processDelayedCallback(server, dc);
             continue;
         }
-        
+
         dc->callback(server, dc->data);
         UA_free(dc);
     }
@@ -247,7 +259,7 @@ processDelayedCallback(UA_Server *server, WorkerCallback *dc) {
         pthread_cond_broadcast(&server->dispatchQueue_condition);
         return;
     }
-        
+
     /* Execute the callback */
     dc->callback(server, dc->data);
     UA_free(dc);
@@ -395,7 +407,6 @@ UA_Server_run_shutdown(UA_Server *server) {
     /* Execute the remaining callbacks in the dispatch queue.
      * This also executes the delayed callbacks. */
     emptyDispatchQueue(server);
-    
 #endif
 
     /* Stop multicast discovery */

+ 12 - 2
src/server/ua_services.h

@@ -1,6 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2015 (c) Sten Grüner
+ *    Copyright 2014 (c) LEvertz
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015 (c) Christian Fimmers
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_SERVICES_H_
 #define UA_SERVICES_H_
@@ -359,7 +369,7 @@ void Service_Call(UA_Server *server, UA_Session *session,
  * links to be deleted, but has no effect on the MonitoredItems referenced by
  * the triggered items. */
 void Service_CreateMonitoredItems(UA_Server *server, UA_Session *session,
-                                  const UA_CreateMonitoredItemsRequest *request, 
+                                  const UA_CreateMonitoredItemsRequest *request,
                                   UA_CreateMonitoredItemsResponse *response);
 
 /**

+ 18 - 2
src/server/ua_services_attribute.c

@@ -1,6 +1,22 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2015 (c) Christian Fimmers
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2015 (c) wuyangtang
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Thomas Bender
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017 (c) Jonas Green
+ *    Copyright 2017 (c) Henrik Norrman
+ */
 
 #include "ua_server_internal.h"
 #include "ua_types_encoding_binary.h"
@@ -1264,7 +1280,7 @@ Service_Write(UA_Server *server, UA_Session *session,
         return;
     }
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_Write, NULL,
                                            &request->nodesToWriteSize, &UA_TYPES[UA_TYPES_WRITEVALUE],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);

+ 12 - 2
src/server/ua_services_call.c

@@ -1,6 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2017 (c) Florian Palm
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016 (c) LEvertz
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Julian Grothoff
+ */
 
 #include "ua_services.h"
 #include "ua_server_internal.h"
@@ -238,7 +248,7 @@ void Service_Call(UA_Server *server, UA_Session *session,
         return;
     }
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_CallMethod, NULL,
                                            &request->methodsToCallSize, &UA_TYPES[UA_TYPES_CALLMETHODREQUEST],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_CALLMETHODRESULT]);

+ 10 - 1
src/server/ua_services_discovery.c

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2016 (c) Sten Grüner
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_server_internal.h"
 #include "ua_services.h"

+ 7 - 2
src/server/ua_services_discovery_multicast.c

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Thomas Stalder
+ */
 
 /* Enable POSIX features */
 #if !defined(_XOPEN_SOURCE) && !defined(_WRS_KERNEL)
@@ -246,7 +251,7 @@ UA_Discovery_update_MdnsForDiscoveryUrl(UA_Server *server, const UA_String *serv
                            (int)serverName->length, serverName->data);
         return;
     }
-    
+
     UA_String *capabilities = NULL;
     size_t capabilitiesSize = 0;
     if(mdnsConfig) {

+ 17 - 3
src/server/ua_services_nodemanagement.c

@@ -1,6 +1,20 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2016 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2016 (c) LEvertz
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017-2018 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Christian von Arnim
+ *    Copyright 2017 (c) Henrik Norrman
+ */
 
 #include "ua_server_internal.h"
 #include "ua_services.h"
@@ -223,7 +237,7 @@ useVariableTypeAttributes(UA_Server *server, UA_Session *session,
         UA_Nodestore_release(server, (const UA_Node*)vt);
         return UA_STATUSCODE_BADTYPEMISMATCH;
     }
-        
+
     /* If no value is set, see if the vt provides one and copy it. This needs to
      * be done before copying the datatype from the vt, as setting the datatype
      * triggers a typecheck. */
@@ -965,7 +979,7 @@ Service_AddNodes(UA_Server *server, UA_Session *session,
         return;
     }
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_addNode, NULL,
                                            &request->nodesToAddSize, &UA_TYPES[UA_TYPES_ADDNODESITEM],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_ADDNODESRESULT]);

+ 8 - 1
src/server/ua_services_securechannel.c

@@ -1,6 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_server_internal.h"
 #include "ua_services.h"

+ 10 - 1
src/server/ua_services_session.c

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2014-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_services.h"
 #include "ua_server_internal.h"

+ 28 - 14
src/server/ua_services_subscription.c

@@ -1,6 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2016-2017 (c) Florian Palm
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mattias Bornhager
+ *    Copyright 2017 (c) Henrik Norrman
+ *    Copyright 2017-2018 (c) Thomas Stalder
+ */
 
 #include "ua_server_internal.h"
 #include "ua_services.h"
@@ -135,7 +146,7 @@ Service_SetPublishingMode(UA_Server *server, UA_Session *session,
                           UA_SetPublishingModeResponse *response) {
     UA_LOG_DEBUG_SESSION(server->config.logger, session, "Processing SetPublishingModeRequest");
     UA_Boolean publishingEnabled = request->publishingEnabled; /* request is const */
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_SetPublishingMode,
                                            &publishingEnabled,
                                            &request->subscriptionIdsSize, &UA_TYPES[UA_TYPES_UINT32],
@@ -271,7 +282,7 @@ Operation_CreateMonitoredItem(UA_Server *server, UA_Session *session, struct cre
 
     /* Create the first sample */
     if(request->monitoringMode == UA_MONITORINGMODE_REPORTING)
-        UA_MoniteredItem_SampleCallback(server, newMon);
+        UA_MonitoredItem_SampleCallback(server, newMon);
 
     /* Prepare the response */
     UA_String_copy(&request->itemToMonitor.indexRange, &newMon->indexRange);
@@ -310,7 +321,7 @@ Service_CreateMonitoredItems(UA_Server *server, UA_Session *session,
     /* Reset the subscription lifetime */
     cmc.sub->currentLifetimeCount = 0;
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_CreateMonitoredItem, &cmc,
                                            &request->itemsToCreateSize, &UA_TYPES[UA_TYPES_MONITOREDITEMCREATEREQUEST],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_MONITOREDITEMCREATERESULT]);
@@ -330,6 +341,9 @@ Operation_ModifyMonitoredItem(UA_Server *server, UA_Session *session, UA_Subscri
     setMonitoredItemSettings(server, mon, mon->monitoringMode, &request->requestedParameters);
     result->revisedSamplingInterval = mon->samplingInterval;
     result->revisedQueueSize = mon->maxQueueSize;
+
+    /* Remove some notifications if the queue is now too small */
+    MonitoredItem_ensureQueueSpace(mon);
 }
 
 void Service_ModifyMonitoredItems(UA_Server *server, UA_Session *session,
@@ -358,7 +372,7 @@ void Service_ModifyMonitoredItems(UA_Server *server, UA_Session *session,
 
     sub->currentLifetimeCount = 0; /* Reset the subscription lifetime */
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session,
                                            (UA_ServiceOperation)Operation_ModifyMonitoredItem, sub,
                                            &request->itemsToModifySize, &UA_TYPES[UA_TYPES_MONITOREDITEMMODIFYREQUEST],
@@ -431,7 +445,7 @@ void Service_SetMonitoringMode(UA_Server *server, UA_Session *session,
     smc.sub->currentLifetimeCount = 0; /* Reset the subscription lifetime */
 
     smc.monitoringMode = request->monitoringMode;
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_SetMonitoringMode, &smc,
                                            &request->monitoredItemIdsSize, &UA_TYPES[UA_TYPES_UINT32],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);
@@ -526,7 +540,7 @@ Service_Publish(UA_Server *server, UA_Session *session,
 
     /* Answer immediately to a late subscription */
     UA_Subscription *immediate;
-    UA_Boolean found = true; 
+    UA_Boolean found = true;
     int loopCount = 1;
 
     if(session->lastSeenSubscriptionId > 0) {
@@ -543,8 +557,8 @@ Service_Publish(UA_Server *server, UA_Session *session,
        LIST_FOREACH(immediate, &session->serverSubscriptions, listEntry) {
             if(!found) {
                 if(session->lastSeenSubscriptionId == immediate->subscriptionId) {
-                    found = true; 
-                }     
+                    found = true;
+                }
             } else {
                 if(immediate->state == UA_SUBSCRIPTIONSTATE_LATE) {
                     session->lastSeenSubscriptionId = immediate->subscriptionId;
@@ -552,9 +566,9 @@ Service_Publish(UA_Server *server, UA_Session *session,
                                          "Response on a late subscription", immediate->subscriptionId);
                     UA_Subscription_publishCallback(server, immediate);
                     return;
-                }     
-            }     
-        }     
+                }
+            }
+        }
         /* after the first loop, we can publish the first subscription with UA_SUBSCRIPTIONSTATE_LATE */
         found = true;
     }
@@ -583,7 +597,7 @@ Service_DeleteSubscriptions(UA_Server *server, UA_Session *session,
     UA_LOG_DEBUG_SESSION(server->config.logger, session,
                          "Processing DeleteSubscriptionsRequest");
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_DeleteSubscription, NULL,
                                            &request->subscriptionIdsSize, &UA_TYPES[UA_TYPES_UINT32],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);
@@ -624,7 +638,7 @@ void Service_DeleteMonitoredItems(UA_Server *server, UA_Session *session,
     /* Reset the subscription lifetime */
     sub->currentLifetimeCount = 0;
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_DeleteMonitoredItem, sub,
                                            &request->monitoredItemIdsSize, &UA_TYPES[UA_TYPES_UINT32],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);

+ 18 - 4
src/server/ua_services_view.c

@@ -1,6 +1,20 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) LEvertz
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015 (c) Ecosmos
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) pschoppe
+ *    Copyright 2017 (c) Julian Grothoff
+ *    Copyright 2017 (c) Henrik Norrman
+ */
 
 #include "ua_server_internal.h"
 #include "ua_services.h"
@@ -362,7 +376,7 @@ Service_BrowseNext(UA_Server *server, UA_Session *session,
     UA_LOG_DEBUG_SESSION(server->config.logger, session,
                          "Processing BrowseNextRequest");
     UA_Boolean releaseContinuationPoints = request->releaseContinuationPoints; /* request is const */
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_BrowseNext,
                                            &releaseContinuationPoints,
                                            &request->continuationPointsSize, &UA_TYPES[UA_TYPES_BYTESTRING],
@@ -597,7 +611,7 @@ Operation_TranslateBrowsePathToNodeIds(UA_Server *server, UA_Session *session,
         result->statusCode = UA_STATUSCODE_BADNOTHINGTODO;
         return;
     }
-        
+
     /* RelativePath elements must not have an empty targetName */
     for(size_t i = 0; i < path->relativePath.elementsSize; ++i) {
         if(UA_QualifiedName_isNull(&path->relativePath.elements[i].targetName)) {
@@ -693,7 +707,7 @@ Service_TranslateBrowsePathsToNodeIds(UA_Server *server, UA_Session *session,
         return;
     }
 
-    response->responseHeader.serviceResult = 
+    response->responseHeader.serviceResult =
         UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_TranslateBrowsePathToNodeIds,
                                            NULL, &request->browsePathsSize, &UA_TYPES[UA_TYPES_BROWSEPATH],
                                            &response->resultsSize, &UA_TYPES[UA_TYPES_BROWSEPATHRESULT]);

+ 4 - 1
src/server/ua_session.c

@@ -1,6 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ */
 
 #include "ua_session.h"
 #ifdef UA_ENABLE_SUBSCRIPTIONS

+ 5 - 2
src/server/ua_session.h

@@ -1,6 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ */
 
 #ifndef UA_SESSION_H_
 #define UA_SESSION_H_
@@ -9,7 +12,7 @@
 extern "C" {
 #endif
 
-#include "queue.h"
+#include "../deps/queue.h"
 #include "ua_securechannel.h"
 
 #define UA_MAXCONTINUATIONPOINTS 5

+ 8 - 1
src/server/ua_session_manager.c

@@ -1,6 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2015 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_session_manager.h"
 #include "ua_server_internal.h"

+ 9 - 2
src/server/ua_session_manager.h

@@ -1,6 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2015 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_SESSION_MANAGER_H_
 #define UA_SESSION_MANAGER_H_
@@ -9,7 +16,7 @@
 extern "C" {
 #endif
 
-#include "queue.h"
+#include "../../deps/queue.h"
 #include "ua_server.h"
 #include "ua_util.h"
 #include "ua_session.h"

+ 13 - 1
src/server/ua_subscription.c

@@ -1,6 +1,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2017-2018 (c) Thomas Stalder
+ *    Copyright 2015 (c) Joakim L. Gilje
+ *    Copyright 2016-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) frax2222
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mattias Bornhager
+ */
 
 #include "ua_subscription.h"
 #include "ua_server_internal.h"

+ 15 - 2
src/server/ua_subscription.h

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2015-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Florian Palm
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mattias Bornhager
+ */
 
 #ifndef UA_SUBSCRIPTION_H_
 #define UA_SUBSCRIPTION_H_
@@ -59,10 +68,14 @@ typedef struct UA_MonitoredItem {
 
 UA_MonitoredItem * UA_MonitoredItem_new(void);
 void MonitoredItem_delete(UA_Server *server, UA_MonitoredItem *monitoredItem);
-void UA_MoniteredItem_SampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem);
+void UA_MonitoredItem_SampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem);
 UA_StatusCode MonitoredItem_registerSampleCallback(UA_Server *server, UA_MonitoredItem *mon);
 UA_StatusCode MonitoredItem_unregisterSampleCallback(UA_Server *server, UA_MonitoredItem *mon);
 
+/* Remove entries until mon->maxQueueSize is reached. Sets infobits for lost
+ * data if required. */
+void MonitoredItem_ensureQueueSpace(UA_MonitoredItem *mon);
+
 /****************/
 /* Subscription */
 /****************/

+ 52 - 20
src/server/ua_subscription_datachange.c

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2018 (c) Thomas Stalder
+ */
 
 #include "ua_subscription.h"
 #include "ua_server_internal.h"
@@ -47,30 +52,55 @@ MonitoredItem_delete(UA_Server *server, UA_MonitoredItem *monitoredItem) {
     UA_free(monitoredItem); // TODO: Use a delayed free
 }
 
-static void
-ensureSpaceInMonitoredItemQueue(UA_MonitoredItem *mon, MonitoredItem_queuedValue *newQueueItem) {
-    /* Enough space, nothing to do here */
-    if(mon->currentQueueSize < mon->maxQueueSize)
+void
+MonitoredItem_ensureQueueSpace(UA_MonitoredItem *mon) {
+    UA_Boolean valueDiscarded = false;
+    MonitoredItem_queuedValue *queueItem;
+#ifndef __clang_analyzer__
+    while(mon->currentQueueSize > mon->maxQueueSize) {
+        /* maxQueuesize is at least 1 */
+        UA_assert(mon->currentQueueSize >= 2);
+
+        /* Get the item to remove. New items are added to the end */
+        if(mon->discardOldest) {
+            /* Remove the oldest */
+            queueItem = TAILQ_FIRST(&mon->queue);
+        } else {
+            /* Keep the newest, remove the second-newest */
+            queueItem = TAILQ_LAST(&mon->queue, QueuedValueQueue);
+            queueItem = TAILQ_PREV(queueItem, QueuedValueQueue, listEntry);
+        }
+        UA_assert(queueItem);
+
+        /* Remove the item */
+        TAILQ_REMOVE(&mon->queue, queueItem, listEntry);
+        UA_DataValue_deleteMembers(&queueItem->value);
+        UA_free(queueItem);
+        --mon->currentQueueSize;
+        valueDiscarded = true;
+    }
+#endif
+
+    if(!valueDiscarded)
         return;
 
-    /* Get the item to remove */
-    MonitoredItem_queuedValue *queueItem;
+    /* Get the element that carries the infobits */
     if(mon->discardOldest)
         queueItem = TAILQ_FIRST(&mon->queue);
     else
         queueItem = TAILQ_LAST(&mon->queue, QueuedValueQueue);
     UA_assert(queueItem);
 
-    /* Remove the item */
-    TAILQ_REMOVE(&mon->queue, queueItem, listEntry);
-    UA_DataValue_deleteMembers(&queueItem->value);
-    UA_free(queueItem);
-    --mon->currentQueueSize;
-
-    if(mon->maxQueueSize > 1) {
-        newQueueItem->value.hasStatus = true;
-        newQueueItem->value.status = UA_STATUSCODE_INFOTYPE_DATAVALUE | UA_STATUSCODE_INFOBITS_OVERFLOW;
+    /* If the queue size is reduced to one, remove the infobits */
+    if(mon->maxQueueSize == 1) {
+        queueItem->value.status &= ~(UA_StatusCode)(UA_STATUSCODE_INFOTYPE_DATAVALUE |
+                                                    UA_STATUSCODE_INFOBITS_OVERFLOW);
+        return;
     }
+
+    /* Add the infobits either to the newest or the new last entry */
+    queueItem->value.hasStatus = true;
+    queueItem->value.status |= (UA_STATUSCODE_INFOTYPE_DATAVALUE | UA_STATUSCODE_INFOBITS_OVERFLOW);
 }
 
 /* Errors are returned as no change detected */
@@ -201,14 +231,16 @@ sampleCallbackWithValue(UA_Server *server, UA_Subscription *sub,
     monitoredItem->lastSampledValue = *valueEncoding;
 
     /* Add the sample to the queue for publication */
-    ensureSpaceInMonitoredItemQueue(monitoredItem, newQueueItem);
     TAILQ_INSERT_TAIL(&monitoredItem->queue, newQueueItem, listEntry);
     ++monitoredItem->currentQueueSize;
-    return true;;
+
+    /* Remove entries from the queue if required */
+    MonitoredItem_ensureQueueSpace(monitoredItem);
+    return true;
 }
 
 void
-UA_MoniteredItem_SampleCallback(UA_Server *server,
+UA_MonitoredItem_SampleCallback(UA_Server *server,
                                 UA_MonitoredItem *monitoredItem) {
     UA_Subscription *sub = monitoredItem->subscription;
     if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
@@ -252,7 +284,7 @@ UA_MoniteredItem_SampleCallback(UA_Server *server,
 UA_StatusCode
 MonitoredItem_registerSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
     UA_StatusCode retval =
-        UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_MoniteredItem_SampleCallback,
+        UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_MonitoredItem_SampleCallback,
                                       mon, (UA_UInt32)mon->samplingInterval, &mon->sampleCallbackId);
     if(retval == UA_STATUSCODE_GOOD)
         mon->sampleCallbackIsRegistered = true;

+ 9 - 1
src/ua_connection.c

@@ -1,6 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2016-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_util.h"
 #include "ua_connection_internal.h"

+ 7 - 1
src/ua_connection_internal.h

@@ -1,6 +1,12 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Florian Palm
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_CONNECTION_INTERNAL_H_
 #define UA_CONNECTION_INTERNAL_H_

+ 26 - 12
src/ua_securechannel.c

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2016-2017 (c) Florian Palm
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Oleksiy Vasylyev
+ *    Copyright 2016 (c) TorbenD
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #include "ua_util.h"
 #include "ua_securechannel.h"
@@ -192,7 +201,7 @@ calculatePaddingAsym(const UA_SecurityPolicy *securityPolicy, const void *channe
         getLocalSignatureSize(securityPolicy, channelContext);
     size_t paddingBytes = 1;
     if(securityPolicy->asymmetricModule.cryptoModule.
-       getRemoteEncryptionKeyLength(securityPolicy, channelContext) > 2048)
+        getRemoteEncryptionKeyLength(securityPolicy, channelContext) > 2048)
         ++paddingBytes;
     size_t padding = (plainTextBlockSize - ((bytesToWrite + signatureSize + paddingBytes) %
                                             plainTextBlockSize));
@@ -294,7 +303,7 @@ UA_SecureChannel_sendAsymmetricOPNMessage(UA_SecureChannel *channel, UA_UInt32 r
             ++buf_pos;
         }
         if(securityPolicy->asymmetricModule.cryptoModule.
-           getRemoteEncryptionKeyLength(securityPolicy, channel->channelContext) > 2048) {
+            getRemoteEncryptionKeyLength(securityPolicy, channel->channelContext) > 2048) {
             *buf_pos = extraPaddingSize;
             ++buf_pos;
         }
@@ -401,7 +410,7 @@ calculatePaddingSym(const UA_SecurityPolicy *securityPolicy, const void *channel
 
 static void
 setBufPos(UA_MessageContext *mc) {
-    const UA_SecureChannel *channel= mc->channel;
+    const UA_SecureChannel *channel = mc->channel;
     const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
 
     /* Forward the data pointer so that the payload is encoded after the
@@ -481,7 +490,7 @@ sendSymmetricChunk(UA_MessageContext *mc) {
     UA_SecureConversationMessageHeader respHeader;
     respHeader.secureChannelId = channel->securityToken.channelId;
     respHeader.messageHeader.messageTypeAndChunkType = mc->messageType;
-    respHeader.messageHeader.messageSize = (UA_UInt32)total_length;
+    respHeader.messageHeader.messageSize = (UA_UInt32) total_length;
     if(mc->final)
         respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
     else
@@ -536,7 +545,7 @@ sendSymmetricChunk(UA_MessageContext *mc) {
 static UA_StatusCode
 sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos, const UA_Byte **buf_end) {
     /* Set buf values from encoding in the messagecontext */
-    UA_MessageContext *mc = (UA_MessageContext*)data;
+    UA_MessageContext *mc = (UA_MessageContext *) data;
     mc->buf_pos = *buf_pos;
     mc->buf_end = *buf_end;
 
@@ -625,7 +634,7 @@ UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 reque
     UA_MessageContext mc;
     UA_StatusCode retval;
     UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
-    retval = UA_MessageContext_begin(&mc, channel, requestId, UA_MESSAGETYPE_MSG);
+    retval = UA_MessageContext_begin(&mc, channel, requestId, messageType);
     if(retval != UA_STATUSCODE_GOOD)
         return retval;
 
@@ -755,19 +764,24 @@ decryptChunk(UA_SecureChannel *channel, const UA_SecurityPolicyCryptoModule *cry
        channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
        messageType == UA_MESSAGETYPE_OPN) {
         /* Compute the padding size */
-        sigsize = cryptoModule-> getRemoteSignatureSize(securityPolicy, channel->channelContext);
+        sigsize = cryptoModule->getRemoteSignatureSize(securityPolicy, channel->channelContext);
 
         if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
            (messageType == UA_MESSAGETYPE_OPN &&
-            channel->securityMode != UA_MESSAGESECURITYMODE_NONE)) {
-            paddingSize = chunk->data[chunkSizeAfterDecryption - sigsize - 1];
+            channel->securityMode > UA_MESSAGESECURITYMODE_NONE)) {
+            paddingSize = (size_t) chunk->data[chunkSizeAfterDecryption - sigsize - 1];
 
-            size_t keyLength = cryptoModule->
-                getRemoteEncryptionKeyLength(securityPolicy, channel->channelContext);
+            size_t keyLength = cryptoModule->getRemoteEncryptionKeyLength(securityPolicy, channel->channelContext);
             if(keyLength > 2048) {
                 paddingSize <<= 8; /* Extra padding size */
                 paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
+                // see comment below but for extraPaddingSize
+                paddingSize += 1;
             }
+
+            // we need to add one to the padding size since the paddingSize byte itself need to be removed as well.
+            // TODO: write unit test for correct padding calculation
+            paddingSize += 1;
         }
         if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
             return UA_STATUSCODE_BADSECURITYCHECKSFAILED;

+ 8 - 2
src/ua_securechannel.h

@@ -1,6 +1,12 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Florian Palm
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_SECURECHANNEL_H_
 #define UA_SECURECHANNEL_H_
@@ -9,7 +15,7 @@
 extern "C" {
 #endif
 
-#include "queue.h"
+#include "../deps/queue.h"
 #include "ua_types.h"
 #include "ua_transport_generated.h"
 #include "ua_connection_internal.h"

+ 5 - 1
src/ua_timer.c

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_util.h"
 #include "ua_timer.h"

+ 5 - 1
src/ua_timer.h

@@ -1,6 +1,10 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_TIMER_H_
 #define UA_TIMER_H_

+ 14 - 2
src/ua_types.c

@@ -1,6 +1,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2016-2017 (c) Florian Palm
+ *    Copyright 2014-2016 (c) Sten Grüner
+ *    Copyright 2014 (c) Leon Urbas
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015 (c) Markus Graube
+ *    Copyright 2015 (c) Reza Ebrahimi
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lorenz Haas
+ */
 
 #include "ua_util.h"
 #include "ua_types.h"
@@ -597,7 +609,7 @@ UA_Variant_copyRange(const UA_Variant *src, UA_Variant *dst,
        nextrange.dimensions = &range.dimensions[dims];
        nextrange.dimensionsSize = range.dimensionsSize - dims;
     }
-        
+
     /* Compute the strides */
     size_t count, block, stride, first;
     UA_StatusCode retval = computeStrides(src, thisrange, &count,

+ 38 - 3
src/ua_types_encoding_binary.c

@@ -1,6 +1,19 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2018 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014-2017 (c) Florian Palm
+ *    Copyright 2014-2016 (c) Sten Grüner
+ *    Copyright 2014 (c) Leon Urbas
+ *    Copyright 2015 (c) LEvertz
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2016 (c) Lorenz Haas
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ *    Copyright 2017 (c) Henrik Norrman
+ */
 
 #include "ua_util.h"
 #include "ua_types_encoding_binary.h"
@@ -905,7 +918,7 @@ ExtensionObject_decodeBinaryContent(UA_ExtensionObject *dst, const UA_NodeId *ty
 
     /* Jump over the length field (TODO: check if the decoded length matches) */
     ctx->pos += 4;
-        
+
     /* Decode */
     dst->encoding = UA_EXTENSIONOBJECT_DECODED;
     dst->content.decoded.type = type;
@@ -993,6 +1006,8 @@ enum UA_VARIANT_ENCODINGMASKTYPE {
     UA_VARIANT_ENCODINGMASKTYPE_ARRAY       = (0x01 << 7)  /* bit 7 */
 };
 
+
+
 ENCODE_BINARY(Variant) {
     /* Quit early for the empty variant */
     u8 encoding = 0;
@@ -1001,8 +1016,12 @@ ENCODE_BINARY(Variant) {
 
     /* Set the content type in the encoding mask */
     const bool isBuiltin = src->type->builtin;
+    const bool isAlias = src->type->membersSize == 1
+                         && UA_TYPES[src->type->members[0].memberTypeIndex].builtin;
     if(isBuiltin)
         encoding |= UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK & (u8)(src->type->typeIndex + 1);
+    else if(isAlias)
+        encoding |= UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK & (u8)(src->type->members[0].memberTypeIndex + 1);
     else
         encoding |= UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK & (u8)(UA_TYPES_EXTENSIONOBJECT + 1);
 
@@ -1021,7 +1040,7 @@ ENCODE_BINARY(Variant) {
         return ret;
 
     /* Encode the content */
-    if(!isBuiltin)
+    if(!isBuiltin && !isAlias)
         ret = Variant_encodeBinaryWrapExtensionObject(src, isArray, ctx);
     else if(!isArray)
         ret = encodeBinaryInternal(src->data, src->type, ctx);
@@ -1104,6 +1123,11 @@ DECODE_BINARY(Variant) {
     if(typeIndex == UA_TYPES_VARIANT && !isArray)
         return UA_STATUSCODE_BADDECODINGERROR;
 
+    /* Check the recursion limit */
+    if(ctx->depth > UA_ENCODING_MAX_RECURSION)
+        return UA_STATUSCODE_BADENCODINGERROR;
+    ctx->depth++;
+
     /* Decode the content */
     dst->type = &UA_TYPES[typeIndex];
     if(isArray) {
@@ -1121,6 +1145,8 @@ DECODE_BINARY(Variant) {
     if(isArray && (encodingByte & UA_VARIANT_ENCODINGMASKTYPE_DIMENSIONS) > 0)
         ret |= Array_decodeBinary((void**)&dst->arrayDimensions, &dst->arrayDimensionsSize,
                                   &UA_TYPES[UA_TYPES_INT32], ctx);
+
+    ctx->depth--;
     return ret;
 }
 
@@ -1172,6 +1198,12 @@ DECODE_BINARY(DataValue) {
     if(ret != UA_STATUSCODE_GOOD)
         return ret;
 
+    /* Check the recursion limit */
+    if(ctx->depth > UA_ENCODING_MAX_RECURSION)
+        return UA_STATUSCODE_BADENCODINGERROR;
+    ctx->depth++;
+
+
     /* Decode the content */
     if(encodingMask & 0x01) {
         dst->hasValue = true;
@@ -1201,6 +1233,9 @@ DECODE_BINARY(DataValue) {
         if(dst->serverPicoseconds > MAX_PICO_SECONDS)
             dst->serverPicoseconds = MAX_PICO_SECONDS;
     }
+
+    ctx->depth--;
+
     return ret;
 }
 

+ 8 - 1
src/ua_types_encoding_binary.h

@@ -1,6 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2015 (c) Sten Grüner
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
+ */
 
 #ifndef UA_TYPES_ENCODING_BINARY_H_
 #define UA_TYPES_ENCODING_BINARY_H_

+ 6 - 1
src/ua_util.c

@@ -1,6 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014, 2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014 (c) Florian Palm
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #include "ua_util.h"
 #include "ua_plugin_network.h"

+ 11 - 2
src/ua_util.h

@@ -1,6 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. 
+ *
+ *    Copyright 2014-2017 (c) Julius Pfrommer, Fraunhofer IOSB
+ *    Copyright 2014, 2017 (c) Florian Palm
+ *    Copyright 2015 (c) LEvertz
+ *    Copyright 2015-2016 (c) Sten Grüner
+ *    Copyright 2015 (c) Chris Iatrou
+ *    Copyright 2015-2016 (c) Oleksiy Vasylyev
+ *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
+ */
 
 #ifndef UA_UTIL_H_
 #define UA_UTIL_H_
@@ -12,7 +21,7 @@ extern "C" {
 #endif
 
 /* BSD Queue Macros */
-#include "queue.h"
+#include "../deps/queue.h"
 
 /* Macro-Expand for MSVC workarounds */
 #define UA_MACRO_EXPAND(x) x

+ 9 - 1
tests/client/check_client.c

@@ -152,7 +152,6 @@ START_TEST(Client_renewSecureChannel) {
 
 START_TEST(Client_reconnect) {
     UA_ClientConfig clientConfig = UA_ClientConfig_default;
-    clientConfig.timeout = 100;
     UA_Client *client = UA_Client_new(clientConfig);
     UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
     ck_assert_uint_eq(retval, UA_STATUSCODE_GOOD);
@@ -217,6 +216,14 @@ START_TEST(Client_activateSessionClose) {
 }
 END_TEST
 
+START_TEST(Client_delete_without_connect) {
+    UA_ClientConfig clientConfig = UA_ClientConfig_default;
+    UA_Client *client = UA_Client_new(clientConfig);
+    ck_assert_msg(client != NULL);
+    UA_Client_delete(client);
+}
+END_TEST
+
 START_TEST(Client_activateSessionTimeout) {
     // restart server
     teardown();
@@ -271,6 +278,7 @@ static Suite* testSuite_Client(void) {
     tcase_add_test(tc_client, Client_connect_username);
     tcase_add_test(tc_client, Client_endpoints);
     tcase_add_test(tc_client, Client_read);
+    tcase_add_test(tc_client, Client_delete_without_connect);
     suite_add_tcase(s,tc_client);
     TCase *tc_client_reconnect = tcase_create("Client Reconnect");
     tcase_add_checked_fixture(tc_client_reconnect, setup, teardown);

+ 206 - 2
tests/server/check_services_subscriptions.c

@@ -173,8 +173,10 @@ START_TEST(Server_publishCallback) {
     UA_Server_run_iterate(server, false);
     UA_realSleep(100);
 
-    LIST_FOREACH(sub, &adminSession.serverSubscriptions, listEntry)
-        ck_assert_uint_eq(sub->currentKeepAliveCount, sub->maxKeepAliveCount+1);
+    LIST_FOREACH(sub, &adminSession.serverSubscriptions, listEntry) {
+        if ((sub->subscriptionId == subscriptionId1) || (sub->subscriptionId == subscriptionId2))
+            ck_assert_uint_eq(sub->currentKeepAliveCount, sub->maxKeepAliveCount+1);
+    }
 
     /* Remove the subscriptions */
     UA_DeleteSubscriptionsRequest del_request;
@@ -225,6 +227,7 @@ START_TEST(Server_createMonitoredItems) {
     ck_assert_uint_eq(response.results[0].statusCode, UA_STATUSCODE_GOOD);
 
     monitoredItemId = response.results[0].monitoredItemId;
+    ck_assert_uint_gt(monitoredItemId, 0);
 
     UA_MonitoredItemCreateRequest_deleteMembers(&item);
     UA_CreateMonitoredItemsResponse_deleteMembers(&response);
@@ -263,6 +266,206 @@ START_TEST(Server_modifyMonitoredItems) {
 }
 END_TEST
 
+START_TEST(Server_overflow) {
+    /* Create a subscription */
+    UA_CreateSubscriptionRequest createSubscriptionRequest;
+    UA_CreateSubscriptionResponse createSubscriptionResponse;
+
+    UA_CreateSubscriptionRequest_init(&createSubscriptionRequest);
+    createSubscriptionRequest.publishingEnabled = true;
+    UA_CreateSubscriptionResponse_init(&createSubscriptionResponse);
+    Service_CreateSubscription(server, &adminSession, &createSubscriptionRequest, &createSubscriptionResponse);
+    ck_assert_uint_eq(createSubscriptionResponse.responseHeader.serviceResult, UA_STATUSCODE_GOOD);
+    UA_UInt32 localSubscriptionId = createSubscriptionResponse.subscriptionId;
+    UA_Double publishingInterval = createSubscriptionResponse.revisedPublishingInterval;
+    ck_assert(publishingInterval > 0.0f);
+    UA_CreateSubscriptionResponse_deleteMembers(&createSubscriptionResponse);
+
+    /* Create a monitoredItem */
+    UA_CreateMonitoredItemsRequest createMonitoredItemsRequest;
+    UA_CreateMonitoredItemsRequest_init(&createMonitoredItemsRequest);
+    createMonitoredItemsRequest.subscriptionId = localSubscriptionId;
+    createMonitoredItemsRequest.timestampsToReturn = UA_TIMESTAMPSTORETURN_SERVER;
+    UA_MonitoredItemCreateRequest item;
+    UA_MonitoredItemCreateRequest_init(&item);
+    UA_ReadValueId rvi;
+    UA_ReadValueId_init(&rvi);
+    rvi.nodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME);
+    rvi.attributeId = UA_ATTRIBUTEID_BROWSENAME;
+    rvi.indexRange = UA_STRING_NULL;
+    item.itemToMonitor = rvi;
+    item.monitoringMode = UA_MONITORINGMODE_REPORTING;
+    UA_MonitoringParameters params;
+    UA_MonitoringParameters_init(&params);
+    item.requestedParameters = params;
+    item.requestedParameters.queueSize = 3;
+    item.requestedParameters.discardOldest = true;
+    createMonitoredItemsRequest.itemsToCreateSize = 1;
+    createMonitoredItemsRequest.itemsToCreate = &item;
+
+    UA_CreateMonitoredItemsResponse createMonitoredItemsResponse;
+    UA_CreateMonitoredItemsResponse_init(&createMonitoredItemsResponse);
+
+    Service_CreateMonitoredItems(server, &adminSession, &createMonitoredItemsRequest, &createMonitoredItemsResponse);
+    ck_assert_uint_eq(createMonitoredItemsResponse.responseHeader.serviceResult, UA_STATUSCODE_GOOD);
+    ck_assert_uint_eq(createMonitoredItemsResponse.resultsSize, 1);
+    ck_assert_uint_eq(createMonitoredItemsResponse.results[0].statusCode, UA_STATUSCODE_GOOD);
+
+    UA_UInt32 localMonitoredItemId = createMonitoredItemsResponse.results[0].monitoredItemId;
+    ck_assert_uint_gt(localMonitoredItemId, 0);
+
+    UA_MonitoredItemCreateRequest_deleteMembers(&item);
+    UA_CreateMonitoredItemsResponse_deleteMembers(&createMonitoredItemsResponse);
+
+    UA_MonitoredItem *mon = NULL;
+    UA_Subscription *sub;
+    LIST_FOREACH(sub, &adminSession.serverSubscriptions, listEntry) {
+        if(sub->subscriptionId == localSubscriptionId)
+            mon = UA_Subscription_getMonitoredItem(sub, localMonitoredItemId);
+    }
+    ck_assert_ptr_ne(mon, NULL);
+    UA_assert(mon);
+    ck_assert_uint_eq(mon->currentQueueSize, 1); 
+    ck_assert_uint_eq(mon->maxQueueSize, 3); 
+    MonitoredItem_queuedValue *queueItem;
+    queueItem = TAILQ_LAST(&mon->queue, QueuedValueQueue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, false);
+
+    UA_ByteString_deleteMembers(&mon->lastSampledValue);
+    UA_MonitoredItem_SampleCallback(server, mon);
+    ck_assert_uint_eq(mon->currentQueueSize, 2); 
+    ck_assert_uint_eq(mon->maxQueueSize, 3); 
+    queueItem = TAILQ_LAST(&mon->queue, QueuedValueQueue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, false);
+
+    UA_ByteString_deleteMembers(&mon->lastSampledValue);
+    UA_MonitoredItem_SampleCallback(server, mon);
+    ck_assert_uint_eq(mon->currentQueueSize, 3); 
+    ck_assert_uint_eq(mon->maxQueueSize, 3); 
+    queueItem = TAILQ_LAST(&mon->queue, QueuedValueQueue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, false);
+
+    UA_ByteString_deleteMembers(&mon->lastSampledValue);
+    UA_MonitoredItem_SampleCallback(server, mon);
+    ck_assert_uint_eq(mon->currentQueueSize, 3); 
+    ck_assert_uint_eq(mon->maxQueueSize, 3); 
+    queueItem = TAILQ_FIRST(&mon->queue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, true);
+    ck_assert_uint_eq(queueItem->value.status, UA_STATUSCODE_INFOTYPE_DATAVALUE | UA_STATUSCODE_INFOBITS_OVERFLOW);
+
+    /* Remove status for next test */
+    queueItem->value.hasStatus = false;
+    queueItem->value.status = 0;
+
+    /* Modify the MonitoredItem */
+    UA_ModifyMonitoredItemsRequest modifyMonitoredItemsRequest;
+    UA_ModifyMonitoredItemsRequest_init(&modifyMonitoredItemsRequest);
+    modifyMonitoredItemsRequest.subscriptionId = localSubscriptionId;
+    modifyMonitoredItemsRequest.timestampsToReturn = UA_TIMESTAMPSTORETURN_SERVER;
+    UA_MonitoredItemModifyRequest itemToModify;
+    UA_MonitoredItemModifyRequest_init(&itemToModify);
+    itemToModify.monitoredItemId = localMonitoredItemId;
+    UA_MonitoringParameters_init(&params);
+    itemToModify.requestedParameters = params;
+    itemToModify.requestedParameters.queueSize = 2;
+    itemToModify.requestedParameters.discardOldest = true;
+    modifyMonitoredItemsRequest.itemsToModifySize = 1;
+    modifyMonitoredItemsRequest.itemsToModify = &itemToModify;
+
+    UA_ModifyMonitoredItemsResponse modifyMonitoredItemsResponse;
+    UA_ModifyMonitoredItemsResponse_init(&modifyMonitoredItemsResponse);
+
+    Service_ModifyMonitoredItems(server, &adminSession, &modifyMonitoredItemsRequest, &modifyMonitoredItemsResponse);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.responseHeader.serviceResult, UA_STATUSCODE_GOOD);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.resultsSize, 1);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.results[0].statusCode, UA_STATUSCODE_GOOD);
+
+    UA_MonitoredItemModifyRequest_deleteMembers(&itemToModify);
+    UA_ModifyMonitoredItemsResponse_deleteMembers(&modifyMonitoredItemsResponse);
+
+    ck_assert_uint_eq(mon->currentQueueSize, 2); 
+    ck_assert_uint_eq(mon->maxQueueSize, 2); 
+    queueItem = TAILQ_FIRST(&mon->queue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, true);
+    ck_assert_uint_eq(queueItem->value.status, UA_STATUSCODE_INFOTYPE_DATAVALUE | UA_STATUSCODE_INFOBITS_OVERFLOW);
+
+    /* Modify the MonitoredItem */
+    UA_ModifyMonitoredItemsRequest_init(&modifyMonitoredItemsRequest);
+    modifyMonitoredItemsRequest.subscriptionId = localSubscriptionId;
+    modifyMonitoredItemsRequest.timestampsToReturn = UA_TIMESTAMPSTORETURN_SERVER;
+    UA_MonitoredItemModifyRequest_init(&itemToModify);
+    itemToModify.monitoredItemId = localMonitoredItemId;
+    UA_MonitoringParameters_init(&params);
+    itemToModify.requestedParameters = params;
+    itemToModify.requestedParameters.queueSize = 1;
+    modifyMonitoredItemsRequest.itemsToModifySize = 1;
+    modifyMonitoredItemsRequest.itemsToModify = &itemToModify;
+
+    UA_ModifyMonitoredItemsResponse_init(&modifyMonitoredItemsResponse);
+
+    Service_ModifyMonitoredItems(server, &adminSession, &modifyMonitoredItemsRequest, &modifyMonitoredItemsResponse);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.responseHeader.serviceResult, UA_STATUSCODE_GOOD);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.resultsSize, 1);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.results[0].statusCode, UA_STATUSCODE_GOOD);
+
+    UA_MonitoredItemModifyRequest_deleteMembers(&itemToModify);
+    UA_ModifyMonitoredItemsResponse_deleteMembers(&modifyMonitoredItemsResponse);
+
+    ck_assert_uint_eq(mon->currentQueueSize, 1); 
+    ck_assert_uint_eq(mon->maxQueueSize, 1); 
+    queueItem = TAILQ_LAST(&mon->queue, QueuedValueQueue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, false);
+
+    /* Modify the MonitoredItem */
+    UA_ModifyMonitoredItemsRequest_init(&modifyMonitoredItemsRequest);
+    modifyMonitoredItemsRequest.subscriptionId = localSubscriptionId;
+    modifyMonitoredItemsRequest.timestampsToReturn = UA_TIMESTAMPSTORETURN_SERVER;
+    UA_MonitoredItemModifyRequest_init(&itemToModify);
+    itemToModify.monitoredItemId = localMonitoredItemId;
+    UA_MonitoringParameters_init(&params);
+    itemToModify.requestedParameters = params;
+    itemToModify.requestedParameters.discardOldest = false;
+    itemToModify.requestedParameters.queueSize = 1;
+    modifyMonitoredItemsRequest.itemsToModifySize = 1;
+    modifyMonitoredItemsRequest.itemsToModify = &itemToModify;
+
+    UA_ModifyMonitoredItemsResponse_init(&modifyMonitoredItemsResponse);
+
+    Service_ModifyMonitoredItems(server, &adminSession, &modifyMonitoredItemsRequest,
+                                 &modifyMonitoredItemsResponse);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.responseHeader.serviceResult, UA_STATUSCODE_GOOD);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.resultsSize, 1);
+    ck_assert_uint_eq(modifyMonitoredItemsResponse.results[0].statusCode, UA_STATUSCODE_GOOD);
+
+    UA_MonitoredItemModifyRequest_deleteMembers(&itemToModify);
+    UA_ModifyMonitoredItemsResponse_deleteMembers(&modifyMonitoredItemsResponse);
+
+    UA_MonitoredItem_SampleCallback(server, mon);
+    ck_assert_uint_eq(mon->currentQueueSize, 1); 
+    ck_assert_uint_eq(mon->maxQueueSize, 1); 
+    queueItem = TAILQ_FIRST(&mon->queue);
+    ck_assert_uint_eq(queueItem->value.hasStatus, false); /* the infobit is only set if the queue is larger than one */
+
+    /* Remove the subscriptions */
+    UA_DeleteSubscriptionsRequest deleteSubscriptionsRequest;
+    UA_DeleteSubscriptionsRequest_init(&deleteSubscriptionsRequest);
+    UA_UInt32 removeId = localSubscriptionId;
+    deleteSubscriptionsRequest.subscriptionIdsSize = 1;
+    deleteSubscriptionsRequest.subscriptionIds = &removeId;
+
+    UA_DeleteSubscriptionsResponse deleteSubscriptionsResponse;
+    UA_DeleteSubscriptionsResponse_init(&deleteSubscriptionsResponse);
+
+    Service_DeleteSubscriptions(server, &adminSession, &deleteSubscriptionsRequest, &deleteSubscriptionsResponse);
+    ck_assert_uint_eq(deleteSubscriptionsResponse.responseHeader.serviceResult, UA_STATUSCODE_GOOD);
+    ck_assert_uint_eq(deleteSubscriptionsResponse.resultsSize, 1);
+    ck_assert_uint_eq(deleteSubscriptionsResponse.results[0], UA_STATUSCODE_GOOD);
+
+    UA_DeleteSubscriptionsResponse_deleteMembers(&deleteSubscriptionsResponse);
+
+}
+END_TEST
+
 START_TEST(Server_setMonitoringMode) {
     UA_SetMonitoringModeRequest request;
     UA_SetMonitoringModeRequest_init(&request);
@@ -315,6 +518,7 @@ static Suite* testSuite_Client(void) {
     tcase_add_test(tc_server, Server_setPublishingMode);
     tcase_add_test(tc_server, Server_createMonitoredItems);
     tcase_add_test(tc_server, Server_modifyMonitoredItems);
+    tcase_add_test(tc_server, Server_overflow);
     tcase_add_test(tc_server, Server_setMonitoringMode);
     tcase_add_test(tc_server, Server_deleteMonitoredItems);
     tcase_add_test(tc_server, Server_republish);

+ 2 - 2
tools/c2rst.py

@@ -22,7 +22,7 @@ remove_keyword = [" UA_EXPORT", " UA_FUNC_ATTR_WARN_UNUSED_RESULT",
                   " UA_FUNC_ATTR_MALLOC", " UA_RESTRICT "]
 
 def clean_comment(line):
-    m = re.search("^( \* |/\*\* )(.*?)( \*/)?$", line)
+    m = re.search("^\s*(\* |/\*\* )(.*?)( \*/)?$", line)
     if not m:
         return "\n"
     return m.group(2) + "\n"
@@ -33,7 +33,7 @@ def clean_line(line):
     return line
 
 def comment_start(line):
-    m = re.search("^/\*\*[ \n]", line)
+    m = re.search("^\s*/\*\*[ \n]", line)
     if not m:
         return False
     return True

+ 4 - 3
tools/certs/create_self-signed.py

@@ -20,8 +20,9 @@ if len(sys.argv) == 3:
     keysize = int(sys.argv[2])
 
 certsdir = os.path.dirname(os.path.abspath(__file__))
+print(certsdir)
 os.environ['HOSTNAME'] = socket.gethostname()
-os.environ['OPENSSL_CONF'] = os.path.join(certsdir, "localhost.cnf")
+openssl_conf = os.path.join(certsdir, "localhost.cnf")
 
 os.chdir(os.path.abspath(sys.argv[1]))
 os.system("""openssl genrsa -out ca.key {}""".format(keysize))
@@ -47,8 +48,8 @@ os.system("""openssl x509 -req \
     -CAkey ca.key \
     -CAcreateserial \
     -out localhost.crt \
-    -extfile $OPENSSL_CONF \
-    -extensions v3_ca""")
+    -extfile {} \
+    -extensions v3_ca""".format(openssl_conf))
 os.system("openssl x509 -in localhost.crt -outform der -out server_cert.der")
 os.system("openssl rsa -inform PEM -in localhost.key -outform DER -out server_key.der")
 

+ 1 - 1
tools/generate_datatypes.py

@@ -99,7 +99,7 @@ class Type(object):
             "    " + str(len(self.members)) + ", /* .membersSize */\n" + \
             "    " + self.builtin + ", /* .builtin */\n" + \
             "    " + self.pointerfree + ", /* .pointerFree */\n" + \
-            "    " + self.overlayable + ", /* .overlayable */ \n" + \
+            "    " + self.overlayable + ", /* .overlayable */\n" + \
             "    " + binaryEncodingId + ", /* .binaryEncodingId */\n" + \
             "    %s_members" % self.name + " /* .members */\n}"
 

+ 234 - 0
tools/update_copyright_header.py

@@ -0,0 +1,234 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+# It is based on the idea of http://0pointer.net/blog/projects/copyright.html
+
+import os
+import re
+import io
+import sys
+
+from git import *
+from shutil import move
+
+try:
+    from StringIO import StringIO
+except ImportError:
+    from io import StringIO
+
+if sys.version_info[0] >= 3:
+    # strings are already parsed to unicode
+    def unicode(s):
+        return s
+
+
+# Replace the name by another value, i.e. add affiliation or replace user name by full name
+# only use lower case name
+authorFullName = {
+    'staldert': 'Thomas Stalder',
+    'mark giraud': 'Mark Giraud, Fraunhofer IOSB',
+    'julius pfrommer': 'Julius Pfrommer, Fraunhofer IOSB',
+    'stefan profanter': 'Stefan Profanter, fortiss GmbH',
+}
+
+# Skip commits with the following authors, since they are not valid names
+# and come from an invalid git config
+skipNames = ['=', 'open62541', 'opcua']
+
+def compactYears(yearList):
+
+    current = None
+    last = None
+    result = []
+
+    for yStr in yearList:
+        y = int(yStr)
+        if last is None:
+            current = y
+            last = y
+            continue
+
+        if y == last + 1:
+            last = y
+            continue
+
+        if last == current:
+            result.append("%i" % last)
+        else:
+            result.append("%i-%i" % (current, last))
+
+        current = y
+        last = y
+
+    if not last is None:
+        if last == current:
+            result.append("%i" % last)
+        else:
+            result.append("%i-%i" % (current, last))
+
+    return ", ".join(result)
+
+fileAuthorStats = dict()
+
+def insertCopyrightAuthors(file, authorsList):
+    copyrightEntries = list()
+    for author in authorsList:
+        copyrightEntries.append(unicode("Copyright {} (c) {}").format(compactYears(author['years']), author['author']))
+
+    copyrightAdded = False
+    commentPattern = re.compile(r"(.*)\*/$")
+
+    tmpName = file + ".new"
+    tempFile = io.open(tmpName, mode="w", encoding="utf-8")
+    with io.open(file, mode="r", encoding="utf-8") as f:
+        for line in f:
+            if copyrightAdded or not commentPattern.match(line):
+                tempFile.write(line)
+            else:
+                tempFile.write(commentPattern.match(line).group(1) + "\n *\n")
+                for e in copyrightEntries:
+                    tempFile.write(unicode(" *    {}\n").format(e))
+                tempFile.write(unicode(" */\n"))
+                copyrightAdded = True
+    tempFile.close()
+    os.unlink(file)
+    move(tmpName, file)
+
+def updateCopyright(repo, file):
+    print("Checking file {}".format(file))
+
+    # Build the info on how many lines every author commited every year
+    relativeFilePath = file[len(repo.working_dir)+1:].replace("\\","/")
+
+    if not relativeFilePath in fileAuthorStats:
+        print("File not found in list: {}".format(relativeFilePath))
+        return
+
+    stats = fileAuthorStats[relativeFilePath]
+
+    # Now create a sorted list and filter out small contributions
+    authorList = list()
+
+    for author in stats:
+        if author in skipNames:
+            continue
+
+        authorYears = list()
+        for year in stats[author]['years']:
+            if stats[author]['years'][year] < 10:
+                # ignore contributions for this year if less than 10 lines changed
+                continue
+            authorYears.append(year)
+        if len(authorYears) == 0:
+            continue
+        authorYears.sort()
+
+        if author.lower() in authorFullName:
+            authorName = authorFullName[author.lower()]
+        else:
+            authorName = author
+
+
+        authorList.append({
+            'author': authorName,
+            'years': authorYears,
+            'first_commit': stats[author]['first_commit']
+        })
+
+    # Sort the authors list first by year, and then by name
+
+    authorListSorted = sorted(authorList, key=lambda a: a['first_commit'])
+    insertCopyrightAuthors(file, authorListSorted)
+
+
+# This is required since some commits use different author names for the same person
+assumeSameAuthor = {
+    'Mark': u'Mark Giraud',
+    'Infinity95': u'Mark Giraud',
+    'janitza-thbe': u'Thomas Bender',
+    'Stasik0': u'Sten Grüner',
+    'Sten': u'Sten Grüner',
+    'Frank Meerkoetter': u'Frank Meerkötter',
+    'ichrispa': u'Chris Iatrou',
+    'Chris Paul Iatrou': u'Chris Iatrou',
+    'Torben-D': u'TorbenD',
+    'FlorianPalm': u'Florian Palm',
+    'ChristianFimmers': u'Christian Fimmers'
+}
+
+def buildFileStats(repo):
+
+    fileRenameMap = dict()
+    renamePattern = re.compile(r"(.*){(.*) => (.*)}(.*)")
+
+    cnt = 0
+    for commit in repo.iter_commits():
+        cnt += 1
+
+    curr = 0
+    for commit in repo.iter_commits():
+        curr += 1
+        print("Checking commit {}/{}  ->   {}".format(curr, cnt, commit.hexsha))
+
+        for objpath, stats in commit.stats.files.items():
+
+            match = renamePattern.match(objpath)
+
+            if match:
+                # the file was renamed, store the rename to follow up later
+                oldFile = (match.group(1) + match.group(2) + match.group(4)).replace("//", "/")
+                newFile = (match.group(1) + match.group(3) + match.group(4)).replace("//", "/")
+
+                while newFile in fileRenameMap:
+                    newFile = fileRenameMap[newFile]
+
+                if oldFile != newFile:
+                    fileRenameMap[oldFile] = newFile
+            else:
+                newFile = fileRenameMap[objpath] if objpath in fileRenameMap else objpath
+
+            if stats['insertions'] > 0:
+                if not newFile in fileAuthorStats:
+                    fileAuthorStats[newFile] = dict()
+
+                authorName = unicode(commit.author.name)
+                if authorName in assumeSameAuthor:
+                    authorName = assumeSameAuthor[authorName]
+
+                if not authorName in fileAuthorStats[newFile]:
+                    fileAuthorStats[newFile][authorName] = {
+                        'years': dict(),
+                        'first_commit': commit.committed_datetime
+                    }
+                elif commit.committed_datetime < fileAuthorStats[newFile][authorName]['first_commit']:
+                    fileAuthorStats[newFile][authorName]['first_commit'] = commit.committed_datetime
+
+                if not commit.committed_datetime.year in fileAuthorStats[newFile][authorName]['years']:
+                    fileAuthorStats[newFile][authorName]['years'][commit.committed_datetime.year] = 0
+
+                fileAuthorStats[newFile][authorName]['years'][commit.committed_datetime.year] += stats['insertions']
+
+
+
+
+def walkFiles(repo, folder, pattern):
+    patternCompiled = re.compile(pattern)
+    for root, subdirs, files in os.walk(folder):
+        for f in files:
+            if patternCompiled.match(f):
+                fname = os.path.join(root,f)
+                updateCopyright(repo, fname)
+
+if __name__ == '__main__':
+    baseDir = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
+    repo = Repo(baseDir)
+    assert not repo.bare
+
+    buildFileStats(repo)
+
+    dirs = ['src', 'plugins', 'include']
+
+    for dir in dirs:
+        walkFiles(repo, os.path.join(baseDir, dir), r"(.*\.c|.*\.h)$")