micsat 3 лет назад
Родитель
Сommit
f7e34005f0
56 измененных файлов с 2198 добавлено и 1749 удалено
  1. 43 37
      source/src/cip/appcontype.c
  2. 218 204
      source/src/cip/cip_security/certificatemanagement.c
  3. 143 129
      source/src/cip/cip_security/cipsecurity.c
  4. 5 4
      source/src/cip/cip_security/cipsecurity.h
  5. 226 216
      source/src/cip/cip_security/ethernetipsecurity.c
  6. 9 6
      source/src/cip/cip_security/ethernetipsecurity.h
  7. 3 3
      source/src/cip/cipassembly.c
  8. 1 1
      source/src/cip/cipclass3connection.c
  9. 28 28
      source/src/cip/cipcommon.h
  10. 113 104
      source/src/cip/cipconnectionmanager.c
  11. 60 60
      source/src/cip/cipconnectionobject.c
  12. 2 2
      source/src/cip/cipconnectionobject.h
  13. 5 5
      source/src/cip/cipdlr.h
  14. 46 46
      source/src/cip/cipepath.c
  15. 52 52
      source/src/cip/cipethernetlink.c
  16. 15 12
      source/src/cip/cipidentity.c
  17. 2 1
      source/src/cip/cipioconnection.c
  18. 5 5
      source/src/cip/cipmessagerouter.c
  19. 19 19
      source/src/cip/cipqos.c
  20. 14 11
      source/src/cip/cipstring.c
  21. 3 2
      source/src/cip/cipstring.h
  22. 39 39
      source/src/cip/cipstringi.c
  23. 53 54
      source/src/cip/ciptcpipinterface.c
  24. 73 72
      source/src/cip/ciptypes.c
  25. 3 3
      source/src/cip/ciptypes.h
  26. 24 24
      source/src/enet_encap/cpf.c
  27. 280 126
      source/src/enet_encap/encap.c
  28. 25 10
      source/src/enet_encap/encap.h
  29. 4 4
      source/src/ports/MINGW/main.c
  30. 13 13
      source/src/ports/MINGW/networkconfig.c
  31. 5 5
      source/src/ports/MINGW/networkhandler.c
  32. 137 66
      source/src/ports/MINGW/sample_application/ethlinkcbs.c
  33. 6 6
      source/src/ports/MINGW/sample_application/ethlinkcbs.h
  34. 1 1
      source/src/ports/MINGW/sample_application/opener_user_conf.h
  35. 6 6
      source/src/ports/POSIX/main.c
  36. 16 16
      source/src/ports/POSIX/networkconfig.c
  37. 2 2
      source/src/ports/POSIX/networkhandler.c
  38. 137 66
      source/src/ports/POSIX/sample_application/ethlinkcbs.c
  39. 6 6
      source/src/ports/POSIX/sample_application/ethlinkcbs.h
  40. 2 2
      source/src/ports/POSIX/sample_application/opener_user_conf.h
  41. 143 141
      source/src/ports/WIN32/main.c
  42. 13 13
      source/src/ports/WIN32/networkconfig.c
  43. 137 66
      source/src/ports/WIN32/sample_application/ethlinkcbs.c
  44. 6 6
      source/src/ports/WIN32/sample_application/ethlinkcbs.h
  45. 1 1
      source/src/ports/WIN32/sample_application/opener_user_conf.h
  46. 1 1
      source/src/ports/WIN32/sample_application/sampleapplication.c
  47. 3 3
      source/src/ports/nvdata/nvdata.h
  48. 4 4
      source/src/ports/nvdata/nvtcpip.c
  49. 1 1
      source/src/utils/enipmessage.c
  50. 3 2
      source/src/utils/xorshiftrandom.c
  51. 1 1
      source/tests/OpENerTests.cpp
  52. 6 6
      source/tests/cip/cipelectronickeyformattest.cpp
  53. 2 2
      source/tests/cip/cipelectronickeytest.cpp
  54. 14 14
      source/tests/cip/cipepathtest.cpp
  55. 17 18
      source/tests/cip/cipstringtests.cpp
  56. 2 2
      source/tests/ports/socket_timer_tests.cpp

+ 43 - 37
source/src/cip/appcontype.c

@@ -193,20 +193,20 @@ CipConnectionObject *GetExclusiveOwnerConnection(
           connection_object->produced_path.instance_id);
       if ( NULL
            != exclusive_owner ) {
-        if(kConnectionObjectStateEstablished ==
-           ConnectionObjectGetState(exclusive_owner) ) {
+        if( kConnectionObjectStateEstablished ==
+            ConnectionObjectGetState(exclusive_owner) ) {
           *extended_error =
             kConnectionManagerExtendedStatusCodeErrorOwnershipConflict;
           OPENER_TRACE_INFO("Hit an Ownership conflict in appcontype.c:198\n");
           break;
         }
-        if(kConnectionObjectStateTimedOut ==
-           ConnectionObjectGetState(exclusive_owner)
-           && ConnectionObjectEqualOriginator(connection_object,
-                                              exclusive_owner) ) {
+        if( kConnectionObjectStateTimedOut ==
+            ConnectionObjectGetState(exclusive_owner)
+            && ConnectionObjectEqualOriginator(connection_object,
+                                               exclusive_owner) ) {
           g_exlusive_owner_connections[i].connection_data.
-          connection_close_function(&(g_exlusive_owner_connections[i].
-                                      connection_data) );
+          connection_close_function( &(g_exlusive_owner_connections[i].
+                                       connection_data) );
           return &(g_exlusive_owner_connections[i].connection_data);
         } else {
           *extended_error =
@@ -232,23 +232,25 @@ CipConnectionObject *GetInputOnlyConnection(
         == connection_object->consumed_path.instance_id) { /* we have the same output assembly */
       if (g_input_only_connections[i].input_assembly
           != connection_object->produced_path.instance_id) {
-        err = kConnectionManagerExtendedStatusCodeInvalidProducingApplicationPath;
+        err =
+          kConnectionManagerExtendedStatusCodeInvalidProducingApplicationPath;
         continue;
       }
       if (g_input_only_connections[i].config_assembly
           != connection_object->configuration_path.instance_id) {
-        err = kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
+        err =
+          kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
         continue;
       }
 
       for (size_t j = 0; j < OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH;
            ++j) {
-        if (kConnectionObjectStateTimedOut
-            == ConnectionObjectGetState(&(g_input_only_connections[i].
-                                          connection_data[j]) )
-            && ConnectionObjectEqualOriginator(connection_object,
-                                               &(g_input_only_connections[i].
-                                                 connection_data[j]))) {
+        if ( kConnectionObjectStateTimedOut
+             == ConnectionObjectGetState( &(g_input_only_connections[i].
+                                            connection_data[j]) )
+             && ConnectionObjectEqualOriginator( connection_object,
+                                                 &(g_input_only_connections[i].
+                                                   connection_data[j]) ) ) {
           g_input_only_connections[i].connection_data[j].
           connection_close_function(
             &g_input_only_connections[i].connection_data[j]);
@@ -258,9 +260,9 @@ CipConnectionObject *GetInputOnlyConnection(
 
       for (size_t j = 0; j < OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH;
            ++j) {
-        if (kConnectionObjectStateNonExistent
-            == ConnectionObjectGetState(&(g_input_only_connections[i].
-                                          connection_data[j]) ) ) {
+        if ( kConnectionObjectStateNonExistent
+             == ConnectionObjectGetState( &(g_input_only_connections[i].
+                                            connection_data[j]) ) ) {
           return &(g_input_only_connections[i].connection_data[j]);
         }
       }
@@ -283,31 +285,35 @@ CipConnectionObject *GetListenOnlyConnection(
         == connection_object->consumed_path.instance_id) { /* we have the same output assembly */
       if (g_listen_only_connections[i].input_assembly
           != connection_object->produced_path.instance_id) {
-        err = kConnectionManagerExtendedStatusCodeInvalidProducingApplicationPath;
+        err =
+          kConnectionManagerExtendedStatusCodeInvalidProducingApplicationPath;
         continue;
       }
       if (g_listen_only_connections[i].config_assembly
           != connection_object->configuration_path.instance_id) {
-        err = kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
+        err =
+          kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
         continue;
       }
 
       /* Here we look for both Point-to-Point and Multicast IO connections */
       if ( NULL == GetExistingProducerIoConnection(false,
                                                    connection_object->
-                                                   produced_path.instance_id)) {
-        err = kConnectionManagerExtendedStatusCodeNonListenOnlyConnectionNotOpened;
+                                                   produced_path.instance_id) )
+      {
+        err =
+          kConnectionManagerExtendedStatusCodeNonListenOnlyConnectionNotOpened;
         break;
       }
 
       for (size_t j = 0; j < OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH;
            ++j) {
-        if (kConnectionObjectStateTimedOut
-            == ConnectionObjectGetState(&(g_listen_only_connections[i].
-                                          connection_data[j]) )
-            && ConnectionObjectEqualOriginator(connection_object,
-                                               &(g_listen_only_connections[i].
-                                                 connection_data[j]))) {
+        if ( kConnectionObjectStateTimedOut
+             == ConnectionObjectGetState( &(g_listen_only_connections[i].
+                                            connection_data[j]) )
+             && ConnectionObjectEqualOriginator( connection_object,
+                                                 &(g_listen_only_connections[i].
+                                                   connection_data[j]) ) ) {
           g_listen_only_connections[i].connection_data[j].
           connection_close_function(
             &g_listen_only_connections[i].connection_data[j]);
@@ -317,9 +323,9 @@ CipConnectionObject *GetListenOnlyConnection(
 
       for (size_t j = 0; j < OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH;
            j++) {
-        if (kConnectionObjectStateNonExistent
-            == ConnectionObjectGetState(&(g_listen_only_connections[i].
-                                          connection_data[j]) ) ) {
+        if ( kConnectionObjectStateNonExistent
+             == ConnectionObjectGetState( &(g_listen_only_connections[i].
+                                            connection_data[j]) ) ) {
           return &(g_listen_only_connections[i].connection_data[j]);
         }
       }
@@ -339,10 +345,10 @@ CipConnectionObject *GetExistingProducerIoConnection(
 
   while (NULL != node) {
     CipConnectionObject *producer_io_connection = node->data;
-    if (ConnectionObjectIsTypeIOConnection(producer_io_connection) &&
-        (input_point == producer_io_connection->produced_path.instance_id) &&
-        (kEipInvalidSocket !=
-         producer_io_connection->socket[kUdpCommuncationDirectionProducing]) )
+    if ( ConnectionObjectIsTypeIOConnection(producer_io_connection) &&
+         (input_point == producer_io_connection->produced_path.instance_id) &&
+         (kEipInvalidSocket !=
+          producer_io_connection->socket[kUdpCommuncationDirectionProducing]) )
     {
       ConnectionObjectConnectionType cnxn_type =
         ConnectionObjectGetTToOConnectionType(producer_io_connection);
@@ -404,7 +410,7 @@ void CloseAllConnectionsForInputWithSameType(const EipUint32 input_point,
   while (NULL != node) {
     CipConnectionObject *const connection = node->data;
     node = node->next;
-    if ( (instance_type == ConnectionObjectGetInstanceType(connection) )
+    if ( ( instance_type == ConnectionObjectGetInstanceType(connection) )
          && (input_point == connection->produced_path.instance_id) ) {
       CipConnectionObject *connection_to_delete = connection;
       CheckIoConnectionEvent(

+ 218 - 204
source/src/cip/cip_security/certificatemanagement.c

@@ -63,37 +63,39 @@
  * declaration of (static) Certificate Management object instance 1 data
  */
 CertificateManagementObjectClassAttributes cmo_class_attr = {
-    .capability_flags = kCertificateManagementObjectCapabilityFlagPushModel,
-    .certificate_list_dummy = 0,
-    .certificate_encodings_flag =
-        kCertificateManagementObjectCertificateEncodingFlagPEM |
-        kCertificateManagementObjectCertificateEncodingFlagPKCS7,
+  .capability_flags = kCertificateManagementObjectCapabilityFlagPushModel,
+  .certificate_list_dummy = 0,
+  .certificate_encodings_flag =
+    kCertificateManagementObjectCertificateEncodingFlagPEM |
+    kCertificateManagementObjectCertificateEncodingFlagPKCS7,
 };
 
 const char instance_1_name[] = "Default Device Certificate";
 const EipUint8 instance_1_length = 26; // excluding trailing \0
 
 const CipShortString default_name = {
-    .length = instance_1_length,
-    .string = (EipByte *)(&instance_1_name),
+  .length = instance_1_length,
+  .string = (EipByte *)(&instance_1_name),
 };
 
 const Certificate default_device_certificate = {
-    .certificate_status = kCertificateManagementObjectCertificateStateValueVerified
+  .certificate_status =
+    kCertificateManagementObjectCertificateStateValueVerified
     // TODO: add path
 };
 
 const Certificate default_ca_certificate = {
-    .certificate_status = kCertificateManagementObjectCertificateStateValueVerified
+  .certificate_status =
+    kCertificateManagementObjectCertificateStateValueVerified
     // TODO: add path
 };
 
 CertificateManagementObject g_certificate_management = {
-    .name = default_name,                                    /*Attribute 1*/
-    .state = kCertificateManagementObjectStateValueVerified, /*Attribute 2*/
-    .device_certificate = default_device_certificate,        /*Attribute 3*/
-    .ca_certificate = default_ca_certificate,                /*Attribute 4*/
-    .certificate_encoding = kCertificateManagementObjectCertificateEncodingPEM, /*Attribute 5*/
+  .name = default_name,                                      /*Attribute 1*/
+  .state = kCertificateManagementObjectStateValueVerified,   /*Attribute 2*/
+  .device_certificate = default_device_certificate,          /*Attribute 3*/
+  .ca_certificate = default_ca_certificate,                  /*Attribute 4*/
+  .certificate_encoding = kCertificateManagementObjectCertificateEncodingPEM,   /*Attribute 5*/
 };
 
 /** @brief Produce the data according to CIP encoding onto the message buffer.
@@ -104,7 +106,8 @@ CertificateManagementObject g_certificate_management = {
  *  @param outgoing_message pointer to the message to be sent
  */
 void EncodeCertificateManagementObjectCertificate(
-    const Certificate *const certificate, ENIPMessage *const outgoing_message) {
+  const Certificate *const certificate,
+  ENIPMessage *const outgoing_message) {
   AddSintToMessage(certificate->certificate_status, outgoing_message);
   EncodeCipSecurityObjectPath(&(certificate->path), outgoing_message);
 }
@@ -121,17 +124,18 @@ void EncodeCertificateManagementObjectCertificate(
  *          -1 .. error
  */
 int DecodeCertificateManagementObjectCertificate(
-    Certificate *const certificate,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  Certificate *const certificate,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
   int number_of_decoded_bytes = -1;
 
-  certificate->certificate_status = GetUsintFromMessage(&message_router_request->data);
+  certificate->certificate_status = GetUsintFromMessage(
+    &message_router_request->data);
   number_of_decoded_bytes = 1;
 
   // write EPATH to the file object instance
   number_of_decoded_bytes += DecodeCipSecurityObjectPath(
-      &(certificate->path), message_router_request, message_router_response);
+    &(certificate->path), message_router_request, message_router_response);
 
   OPENER_TRACE_INFO("Number_of_decoded bytes: %d\n", number_of_decoded_bytes);
   return number_of_decoded_bytes;
@@ -145,20 +149,23 @@ int DecodeCertificateManagementObjectCertificate(
  *  @param outgoing_message pointer to the message to be sent
  */
 void EncodeCertificateManagementObjectCertificateList(
-    const void *const data, ENIPMessage *const outgoing_message) {
+  const void *const data,
+  ENIPMessage *const outgoing_message) {
   CipClass *class = GetCipClass(kCertificateManagementObjectClassCode);
 
   CipUsint number_of_instances = class->number_of_instances;
   EncodeCipUsint(&number_of_instances, outgoing_message);
 
-  for (CipInstance *instance = class->instances; instance; instance = instance->next) {
+  for (CipInstance *instance = class->instances; instance;
+       instance = instance->next) {
     CipAttributeStruct *instance_name = GetCipAttribute(instance, 1);
-    EncodeCipShortString((CipShortString *)instance_name->data, outgoing_message);
+    EncodeCipShortString( (CipShortString *)instance_name->data,
+                          outgoing_message );
 
     CipEpath path = {
-        .path_size = 2,
-        .class_id = kCertificateManagementObjectClassCode,
-        .instance_number = instance->instance_number,
+      .path_size = 2,
+      .class_id = kCertificateManagementObjectClassCode,
+      .instance_number = instance->instance_number,
     };
     EncodeCipUsint(&path.path_size, outgoing_message);
     EncodeEPath(&path, outgoing_message);
@@ -181,46 +188,46 @@ void CertificateManagementObjectBindAttributes(CipInstance *instance,
                                                Certificate *ca_certificate,
                                                CipUsint *certificate_encoding) {
 
-    InsertAttribute(instance,
-                    1,
-                    kCipShortString,
-                    EncodeCipShortString,
-                    NULL,
-                    name,
-                    kGetableSingleAndAll
-    );
-    InsertAttribute(instance,
-                    2,
-                    kCipUsint,
-                    EncodeCipUsint,
-                    NULL,
-                    state,
-                    kGetableSingleAndAll
-    );
-    InsertAttribute(instance,
-                    3,
-                    kCipAny,
-                    EncodeCertificateManagementObjectCertificate,
-                    DecodeCertificateManagementObjectCertificate,
-                    device_certificate,
-                    kSetAndGetAble
-    );
-    InsertAttribute(instance,
-                    4,
-                    kCipAny,
-                    EncodeCertificateManagementObjectCertificate,
-                    DecodeCertificateManagementObjectCertificate,
-                    ca_certificate,
-                    kSetAndGetAble
-    );
-    InsertAttribute(instance,
-                    5,
-                    kCipUsint,
-                    EncodeCipUsint,
-                    NULL,
-                    certificate_encoding,
-                    kGetableSingleAndAll
-    );
+  InsertAttribute(instance,
+                  1,
+                  kCipShortString,
+                  EncodeCipShortString,
+                  NULL,
+                  name,
+                  kGetableSingleAndAll
+                  );
+  InsertAttribute(instance,
+                  2,
+                  kCipUsint,
+                  EncodeCipUsint,
+                  NULL,
+                  state,
+                  kGetableSingleAndAll
+                  );
+  InsertAttribute(instance,
+                  3,
+                  kCipAny,
+                  EncodeCertificateManagementObjectCertificate,
+                  DecodeCertificateManagementObjectCertificate,
+                  device_certificate,
+                  kSetAndGetAble
+                  );
+  InsertAttribute(instance,
+                  4,
+                  kCipAny,
+                  EncodeCertificateManagementObjectCertificate,
+                  DecodeCertificateManagementObjectCertificate,
+                  ca_certificate,
+                  kSetAndGetAble
+                  );
+  InsertAttribute(instance,
+                  5,
+                  kCipUsint,
+                  EncodeCipUsint,
+                  NULL,
+                  certificate_encoding,
+                  kGetableSingleAndAll
+                  );
 }
 
 /** @brief Certificate Management Object Delete Instance Data
@@ -228,14 +235,14 @@ void CertificateManagementObjectBindAttributes(CipInstance *instance,
  *  Used for common Delete service to delete instance struct before instance is deleted
  */
 EipStatus CertificateManagementObjectDeleteInstanceData(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response
-) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response
+  ) {
 
   // free all allocated attributes of instance
   CipAttributeStruct *attribute =
-      instance->attributes; /* init pointer to array of attributes*/
+    instance->attributes;   /* init pointer to array of attributes*/
   for (EipUint16 i = 0; i < instance->cip_class->number_of_attributes; i++) {
     CipFree(attribute->data);
     ++attribute;
@@ -257,10 +264,10 @@ EipStatus CertificateManagementObjectDeleteInstanceData(
  *  @See Vol.8, Chapter 5-5.5.1
  */
 EipStatus CertificateManagementObjectPreCreateCallback(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response
-) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response
+  ) {
 
   if (message_router_request->request_data_size > 0) {
     return kEipStatusOk;
@@ -276,33 +283,39 @@ EipStatus CertificateManagementObjectPreCreateCallback(
  *  @See Vol.8, Chapter 5-5.5.1
  */
 EipStatus CertificateManagementObjectPostCreateCallback(
-    CipInstance *RESTRICT const new_instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response
-) {
+  CipInstance *RESTRICT const new_instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response
+  ) {
 
-  CipShortString *name = (CipShortString *)CipCalloc(1, sizeof(CipShortString));
+  CipShortString *name =
+    (CipShortString *)CipCalloc( 1, sizeof(CipShortString) );
   name->length = GetUsintFromMessage(&message_router_request->data);
-  name->string = (CipByte *)CipCalloc(name->length, sizeof(CipByte));
+  name->string = (CipByte *)CipCalloc( name->length, sizeof(CipByte) );
   memcpy(name->string, message_router_request->data, name->length);
 
-  CipUsint *state = (CipUsint *)CipCalloc(1, sizeof(CipUsint));
+  CipUsint *state = (CipUsint *)CipCalloc( 1, sizeof(CipUsint) );
   *state = kCertificateManagementObjectStateValueCreated;
 
-  Certificate *device_certificate = (Certificate *)CipCalloc(1, sizeof(Certificate));
-  Certificate *ca_certificate = (Certificate *)CipCalloc(1, sizeof(Certificate));
-  CipUsint *certificate_encoding = (CipUsint *)CipCalloc(1, sizeof(CipUsint));
+  Certificate *device_certificate =
+    (Certificate *)CipCalloc( 1, sizeof(Certificate) );
+  Certificate *ca_certificate =
+    (Certificate *)CipCalloc( 1, sizeof(Certificate) );
+  CipUsint *certificate_encoding = (CipUsint *)CipCalloc( 1, sizeof(CipUsint) );
 
   CertificateManagementObjectBindAttributes(
-      new_instance,
-      name, state, device_certificate, ca_certificate, certificate_encoding);
+    new_instance,
+    name, state, device_certificate, ca_certificate, certificate_encoding);
 
   //create new CMO data struct for additional data
-  CertificateManagementObjectValues *CMO_instance_data = CipCalloc(1, sizeof(CertificateManagementObjectValues));
+  CertificateManagementObjectValues *CMO_instance_data =
+    CipCalloc( 1, sizeof(CertificateManagementObjectValues) );
   new_instance->data = CMO_instance_data;
-  CMO_instance_data->delete_instance_data = &CertificateManagementObjectDeleteInstanceData; //delete instance data function
+  CMO_instance_data->delete_instance_data =
+    &CertificateManagementObjectDeleteInstanceData;                                         //delete instance data function
 
-  AddIntToMessage(new_instance->instance_number, &(message_router_response->message));
+  AddIntToMessage( new_instance->instance_number,
+                   &(message_router_response->message) );
   return kEipStatusOk;
 }
 
@@ -312,10 +325,10 @@ EipStatus CertificateManagementObjectPostCreateCallback(
  *  @See Vol.8, Chapter 5-5.5.2
  */
 EipStatus CertificateManagementObjectPreDeleteCallback(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response
-) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response
+  ) {
   EipStatus internal_state = kEipStatusOk;
 
   CertificateManagementObjectValues *CMO_instance_data = instance->data;
@@ -326,8 +339,9 @@ EipStatus CertificateManagementObjectPreDeleteCallback(
     internal_state = kEipStatusError;
   }
   else{
-    internal_state = CertificateManagementObjectDeleteInstanceData(instance, message_router_request,
-                                               message_router_response);
+    internal_state = CertificateManagementObjectDeleteInstanceData(instance,
+                                                                   message_router_request,
+                                                                   message_router_response);
   }
   return internal_state;
 }
@@ -339,11 +353,11 @@ EipStatus CertificateManagementObjectPreDeleteCallback(
  *  @See Vol.8, Chapter 5-5.7.1
  */
 EipStatus CertificateManagementObjectCreateCSR(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   // TODO: implement service
 
   return kEipStatusOk;
@@ -357,11 +371,11 @@ EipStatus CertificateManagementObjectCreateCSR(
  *  @See Vol.8, Chapter 5-5.7.2
  */
 EipStatus CertificateManagementObjectVerifyCertificate(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   // TODO: implement service
 
   return kEipStatusOk;
@@ -371,93 +385,93 @@ void CertificateManagementObjectInitializeClassSettings(CipClass *class) {
 
   CipClass *meta_class = class->class_instance.cip_class;
 
-  InsertAttribute((CipInstance *) class,
-                  1,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->revision,
-                  kGetableSingleAndAll);  /* revision */
-  InsertAttribute((CipInstance *) class,
-                  2,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->max_instance,
-                  kGetableSingleAndAll); /*  largest instance number */
-  InsertAttribute((CipInstance *) class,
-                  3,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->number_of_instances,
-                  kGetableSingleAndAll); /* number of instances currently existing*/
-  InsertAttribute((CipInstance *) class,
-                  4,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &kCipUintZero,
-                  kNotSetOrGetable); /* optional attribute list - default = 0 */
-  InsertAttribute((CipInstance *) class,
-                  5,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &kCipUintZero,
-                  kNotSetOrGetable); /* optional service list - default = 0 */
-  InsertAttribute((CipInstance *) class,
-                  6,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &meta_class->highest_attribute_number,
-                  kGetableSingleAndAll); /* max class attribute number*/
-  InsertAttribute((CipInstance *) class,
-                  7,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->highest_attribute_number,
-                  kGetableSingleAndAll); /* max instance attribute number*/
-  InsertAttribute((CipInstance *) class,
-                  8,
-                  kCipDword,
-                  EncodeCipDword,
-                  NULL,
-                  (void *) &cmo_class_attr.capability_flags,
-                  kGetableSingleAndAll); /* Certificate Management capabilities*/
-  InsertAttribute((CipInstance *) class,
-                  9,
-                  kCipAny,
-                  EncodeCertificateManagementObjectCertificateList,
-                  NULL,
-                  (void *) &cmo_class_attr.certificate_list_dummy,
-                  kGetableSingleAndAll); /* List of device certificates*/
-  InsertAttribute((CipInstance *) class,
-                  10,
-                  kCipDword,
-                  EncodeCipDword,
-                  NULL,
-                  (void *) &cmo_class_attr.certificate_encodings_flag,
-                  kGetableSingleAndAll); /* Certificate encodings supported*/
+  InsertAttribute( (CipInstance *) class,
+                   1,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->revision,
+                   kGetableSingleAndAll ); /* revision */
+  InsertAttribute( (CipInstance *) class,
+                   2,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->max_instance,
+                   kGetableSingleAndAll ); /*  largest instance number */
+  InsertAttribute( (CipInstance *) class,
+                   3,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->number_of_instances,
+                   kGetableSingleAndAll ); /* number of instances currently existing*/
+  InsertAttribute( (CipInstance *) class,
+                   4,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &kCipUintZero,
+                   kNotSetOrGetable ); /* optional attribute list - default = 0 */
+  InsertAttribute( (CipInstance *) class,
+                   5,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &kCipUintZero,
+                   kNotSetOrGetable ); /* optional service list - default = 0 */
+  InsertAttribute( (CipInstance *) class,
+                   6,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &meta_class->highest_attribute_number,
+                   kGetableSingleAndAll ); /* max class attribute number*/
+  InsertAttribute( (CipInstance *) class,
+                   7,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->highest_attribute_number,
+                   kGetableSingleAndAll ); /* max instance attribute number*/
+  InsertAttribute( (CipInstance *) class,
+                   8,
+                   kCipDword,
+                   EncodeCipDword,
+                   NULL,
+                   (void *) &cmo_class_attr.capability_flags,
+                   kGetableSingleAndAll ); /* Certificate Management capabilities*/
+  InsertAttribute( (CipInstance *) class,
+                   9,
+                   kCipAny,
+                   EncodeCertificateManagementObjectCertificateList,
+                   NULL,
+                   (void *) &cmo_class_attr.certificate_list_dummy,
+                   kGetableSingleAndAll ); /* List of device certificates*/
+  InsertAttribute( (CipInstance *) class,
+                   10,
+                   kCipDword,
+                   EncodeCipDword,
+                   NULL,
+                   (void *) &cmo_class_attr.certificate_encodings_flag,
+                   kGetableSingleAndAll ); /* Certificate encodings supported*/
 
   /* Add class services to the meta class */
   InsertService(meta_class,
                 kGetAttributeAll,
                 &GetAttributeAll,
                 "GetAttributeAll"
-  );
+                );
   InsertService(meta_class,
                 kGetAttributeSingle,
                 &GetAttributeSingle,
                 "GetAttributeSingle"
-  );
+                );
   InsertService(meta_class,
                 kCreate,
                 &CipCreateService,
                 "Create"
-  );
+                );
   // add Callback function pointers
   class->PreCreateCallback = &CertificateManagementObjectPreCreateCallback;
   class->PostCreateCallback = &CertificateManagementObjectPostCreateCallback;
@@ -469,18 +483,18 @@ EipStatus CertificateManagementObjectInit(void) {
   CipInstance *certificate_management_object_instance;
 
   certificate_management_object_class = CreateCipClass(
-      kCertificateManagementObjectClassCode,
-      3,  /* # class attributes */
-      10, /* # highest class attribute number */
-      3,  /* # class services */
-      5,  /* # instance attributes */
-      5,  /* # highest instance attribute number */
-      6,  /* # instance services */
-      1,  /* # instances */
-      "Certificate Management Object",
-      CERTIFICATE_MANAGEMENT_OBJECT_REVISION,             /* # class revision */
-      &CertificateManagementObjectInitializeClassSettings /* # function pointer for initialization */
-  );
+    kCertificateManagementObjectClassCode,
+    3,    /* # class attributes */
+    10,   /* # highest class attribute number */
+    3,    /* # class services */
+    5,    /* # instance attributes */
+    5,    /* # highest instance attribute number */
+    6,    /* # instance services */
+    1,    /* # instances */
+    "Certificate Management Object",
+    CERTIFICATE_MANAGEMENT_OBJECT_REVISION,               /* # class revision */
+    &CertificateManagementObjectInitializeClassSettings   /* # function pointer for initialization */
+    );
 
   if (NULL == certificate_management_object_class) {
     /* Initialization failed */
@@ -488,48 +502,48 @@ EipStatus CertificateManagementObjectInit(void) {
   }
 
   certificate_management_object_instance =
-      GetCipInstance(certificate_management_object_class, 1);
+    GetCipInstance(certificate_management_object_class, 1);
 
   /* Bind attributes to the static instance number 1 (default certificates)*/
   CertificateManagementObjectBindAttributes(
-      certificate_management_object_instance,
-      &g_certificate_management.name,
-      &g_certificate_management.state,
-      &g_certificate_management.device_certificate,
-      &g_certificate_management.ca_certificate,
-      &g_certificate_management.certificate_encoding);
+    certificate_management_object_instance,
+    &g_certificate_management.name,
+    &g_certificate_management.state,
+    &g_certificate_management.device_certificate,
+    &g_certificate_management.ca_certificate,
+    &g_certificate_management.certificate_encoding);
 
   /* Add services to the instance */
   InsertService(certificate_management_object_class,
                 kGetAttributeAll,
                 &GetAttributeAll,
                 "GetAttributeAll"
-  );
+                );
   InsertService(certificate_management_object_class,
                 kDelete,
                 &CipDeleteService,
                 "Delete"
-  );
+                );
   InsertService(certificate_management_object_class,
                 kGetAttributeSingle,
                 &GetAttributeSingle,
                 "GetAttributeSingle"
-  );
+                );
   InsertService(certificate_management_object_class,
                 kSetAttributeSingle,
                 &SetAttributeSingle,
                 "SetAttributeSingle"
-  );
+                );
   InsertService(certificate_management_object_class,
                 kCertificateManagementObjectServiceCodeCreateCSR,
                 &CertificateManagementObjectCreateCSR,
                 "CertificateManagementObjectCreateCSR"
-  );
+                );
   InsertService(certificate_management_object_class,
                 kCertificateManagementObjectServiceCodeVerifyCertificate,
                 &CertificateManagementObjectVerifyCertificate,
                 "CertificateManagementObjectVerifyCertificate"
-  );
+                );
 
   return kEipStatusOk;
 }

+ 143 - 129
source/src/cip/cip_security/cipsecurity.c

@@ -58,12 +58,15 @@
 /**< definition of CIP Security object instance 1 data */
 
 CipSecurityObject g_security = {
-    .state = kCipSecurityObjectStateValueFactoryDefaultConfiguration,
-    .security_profiles = kCipSecurityObjectSecurityProfileValueEtherNetIpConfidentialityProfile,
-    .security_profiles_configured = kCipSecurityObjectSecurityProfileValueEtherNetIpConfidentialityProfile,
+  .state = kCipSecurityObjectStateValueFactoryDefaultConfiguration,
+  .security_profiles =
+    kCipSecurityObjectSecurityProfileValueEtherNetIpConfidentialityProfile,
+  .security_profiles_configured =
+    kCipSecurityObjectSecurityProfileValueEtherNetIpConfidentialityProfile,
 };
 
-MilliSeconds cipSecurityConfigSessionTimeout = CIP_SECURITY_CONFIG_SESSION_DEFAULT_TIMEOUT;
+MilliSeconds cipSecurityConfigSessionTimeout =
+  CIP_SECURITY_CONFIG_SESSION_DEFAULT_TIMEOUT;
 
 /* ********************************************************************
  * public functions
@@ -78,18 +81,20 @@ MilliSeconds cipSecurityConfigSessionTimeout = CIP_SECURITY_CONFIG_SESSION_DEFAU
  *  @See Vol.8, Chapter 5-3.5.1
  */
 EipStatus CipSecurityObjectPreResetCallback(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
 
   if (message_router_request->request_data_size > 0) {
     message_router_response->general_status = kCipErrorTooMuchData;
   } else {
     g_security.state = kCipSecurityObjectStateValueFactoryDefaultConfiguration;
-    OPENER_TRACE_INFO("Reset attribute 1 (state) of instance %d\n", instance->instance_number);
+    OPENER_TRACE_INFO("Reset attribute 1 (state) of instance %d\n",
+                      instance->instance_number);
 
     /*perform a reset on each Ethernet/IP Security Object instances present*/
-    CipInstance *eip_security_instance = GetCipClass(kEIPSecurityObjectClassCode)->instances;
+    CipInstance *eip_security_instance =
+      GetCipClass(kEIPSecurityObjectClassCode)->instances;
 
     while (NULL != eip_security_instance) {
       EIPSecurityObjectPreResetCallback(eip_security_instance,
@@ -108,15 +113,16 @@ EipStatus CipSecurityObjectPreResetCallback(
  *  @See Vol.8, Chapter 5-3.7.1
  */
 EipStatus CipSecurityObjectBeginConfig(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorPrivilegeViolation;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
 //  CipAttributeStruct *attribute = GetCipAttribute(instance, 1);
 //  attribute #1 state CipUsint state = *(CipUsint*) attribute->data; //TODO: check
@@ -148,15 +154,16 @@ EipStatus CipSecurityObjectBeginConfig(
  *  @See Vol.8, Chapter 5-3.7.3
  */
 EipStatus CipSecurityObjectEndConfig(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorObjectStateConflict;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
 //  CipAttributeStruct *attribute = GetCipAttribute(instance, 1); // attribute #1 state
 //  CipUsint state = *(CipUsint*) attribute->data; //TODO: check
@@ -177,21 +184,23 @@ EipStatus CipSecurityObjectEndConfig(
  *  @See Vol.8, Chapter 5-3.7.2
  */
 EipStatus CipSecurityObjectKickTimer(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorObjectStateConflict;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
   CipUsint state = g_security.state;
 
   if (kCipSecurityObjectStateValueConfigurationInProgress == state) {
     // reset configuration session timer
-    cipSecurityConfigSessionTimeout = CIP_SECURITY_CONFIG_SESSION_DEFAULT_TIMEOUT;
+    cipSecurityConfigSessionTimeout =
+      CIP_SECURITY_CONFIG_SESSION_DEFAULT_TIMEOUT;
     message_router_response->general_status = kCipErrorSuccess;
   }
 
@@ -204,15 +213,17 @@ EipStatus CipSecurityObjectKickTimer(
  *  @See Vol.8, Chapter 5-3.7.4
  */
 EipStatus CipSecurityObjectCleanup(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
-  message_router_response->general_status = kCipSecurityObjectErrorCodeNoOrphanObjects;
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
+  message_router_response->general_status =
+    kCipSecurityObjectErrorCodeNoOrphanObjects;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
   // TODO: implement service
 
@@ -223,17 +234,20 @@ EipStatus CipSecurityObjectCleanup(
  *
  */
 void CipSecuritySessionTimeoutChecker(const MilliSeconds elapsed_time) {
-    /* check if CIPSecurity configuration session timed out. */
-  if(kCipSecurityObjectStateValueConfigurationInProgress == g_security.state){
-	  if(elapsed_time > cipSecurityConfigSessionTimeout) {
-		  g_security.state = kCipSecurityObjectStateValueIncompleteConfiguration;
-		  OPENER_TRACE_INFO("CipSecuritySessionTimeoutCheck: CIP Security configuration session timed out\n");
-      cipSecurityConfigSessionTimeout = CIP_SECURITY_CONFIG_SESSION_DEFAULT_TIMEOUT;
-	  }
+  /* check if CIPSecurity configuration session timed out. */
+  if(kCipSecurityObjectStateValueConfigurationInProgress == g_security.state) {
+    if(elapsed_time > cipSecurityConfigSessionTimeout) {
+      g_security.state = kCipSecurityObjectStateValueIncompleteConfiguration;
+      OPENER_TRACE_INFO(
+        "CipSecuritySessionTimeoutCheck: CIP Security configuration session timed out\n");
+      cipSecurityConfigSessionTimeout =
+        CIP_SECURITY_CONFIG_SESSION_DEFAULT_TIMEOUT;
+    }
     else {
-        cipSecurityConfigSessionTimeout -= elapsed_time;
-      }
-      OPENER_TRACE_INFO("CipSecurityConfigSession: Time left %" PRIu64 "\n", cipSecurityConfigSessionTimeout);
+      cipSecurityConfigSessionTimeout -= elapsed_time;
+    }
+    OPENER_TRACE_INFO("CipSecurityConfigSession: Time left %" PRIu64 "\n",
+                      cipSecurityConfigSessionTimeout);
   }
 }
 
@@ -241,14 +255,14 @@ void EncodeCipSecurityObjectPath(const CipEpath *const epath,
                                  ENIPMessage *const outgoing_message) {
   AddSintToMessage(epath->path_size, outgoing_message);
   if (0 != epath->path_size) {
-    EncodeEPath((CipEpath *)epath, outgoing_message);
+    EncodeEPath( (CipEpath *)epath, outgoing_message );
   }
 }
 
 int DecodeCipSecurityObjectPath(
-    CipEpath *const epath,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  CipEpath *const epath,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
   const EipUint8 *message_runner = (message_router_request->data);
 
   /* get data from message */
@@ -259,45 +273,45 @@ int DecodeCipSecurityObjectPath(
 
   int number_of_decoded_bytes = 0;
 
-  while (number_of_decoded_bytes < (path_size * 2)) {
+  while ( number_of_decoded_bytes < (path_size * 2) ) {
     switch (*message_runner) {
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_CLASS_ID +
-          LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
+        LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
         message_runner++;
         class_id = GetUsintFromMessage(&message_runner);
         number_of_decoded_bytes += 2;
         break;
 
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_CLASS_ID +
-          LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
+        LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
         message_runner += 2;
         class_id = GetUintFromMessage(&message_runner);
         number_of_decoded_bytes += 4;
         break;
 
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_INSTANCE_ID +
-          LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
+        LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
         message_runner++;
         instance_number = GetUsintFromMessage(&message_runner);
         number_of_decoded_bytes += 2;
         break;
 
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_INSTANCE_ID +
-          LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
+        LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
         message_runner += 2;
         instance_number = GetUintFromMessage(&message_runner);
         number_of_decoded_bytes += 4;
         break;
 
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_ATTRIBUTE_ID +
-          LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
+        LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
         message_runner++;
         attribute_number = GetUsintFromMessage(&message_runner);
         number_of_decoded_bytes += 2;
         break;
 
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_ATTRIBUTE_ID +
-          LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
+        LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
         message_runner += 2;
         attribute_number = GetUintFromMessage(&message_runner);
         number_of_decoded_bytes += 4;
@@ -329,72 +343,72 @@ void CipSecurityObjectInitializeClassSettings(CipClass *class) {
 
   CipClass *meta_class = class->class_instance.cip_class;
 
-  InsertAttribute((CipInstance *) class,
-                  1,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->revision,
-                  kGetableSingleAndAll);  /* revision */
-  InsertAttribute((CipInstance *) class,
-                  2,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->max_instance,
-                  kGetableSingleAndAll); /*  largest instance number */
-  InsertAttribute((CipInstance *) class,
-                  3,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->number_of_instances,
-                  kGetableSingle); /* number of instances currently existing*/
-  InsertAttribute((CipInstance *) class,
-                  4,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &kCipUintZero,
-                  kNotSetOrGetable); /* optional attribute list - default = 0 */
-  InsertAttribute((CipInstance *) class,
-                  5,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &kCipUintZero,
-                  kNotSetOrGetable); /* optional service list - default = 0 */
-  InsertAttribute((CipInstance *) class,
-                  6,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &meta_class->highest_attribute_number,
-                  kGetableSingleAndAll); /* max class attribute number*/
-  InsertAttribute((CipInstance *) class,
-                  7,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->highest_attribute_number,
-                  kGetableSingleAndAll); /* max instance attribute number*/
+  InsertAttribute( (CipInstance *) class,
+                   1,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->revision,
+                   kGetableSingleAndAll ); /* revision */
+  InsertAttribute( (CipInstance *) class,
+                   2,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->max_instance,
+                   kGetableSingleAndAll ); /*  largest instance number */
+  InsertAttribute( (CipInstance *) class,
+                   3,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->number_of_instances,
+                   kGetableSingle ); /* number of instances currently existing*/
+  InsertAttribute( (CipInstance *) class,
+                   4,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &kCipUintZero,
+                   kNotSetOrGetable ); /* optional attribute list - default = 0 */
+  InsertAttribute( (CipInstance *) class,
+                   5,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &kCipUintZero,
+                   kNotSetOrGetable ); /* optional service list - default = 0 */
+  InsertAttribute( (CipInstance *) class,
+                   6,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &meta_class->highest_attribute_number,
+                   kGetableSingleAndAll ); /* max class attribute number*/
+  InsertAttribute( (CipInstance *) class,
+                   7,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->highest_attribute_number,
+                   kGetableSingleAndAll ); /* max instance attribute number*/
 
   /* Add class services to the meta class */
   InsertService(meta_class,
                 kGetAttributeAll,
                 &GetAttributeAll,
                 "GetAttributeAll"
-  );
+                );
   InsertService(meta_class,
                 kGetAttributeSingle,
                 &GetAttributeSingle,
                 "GetAttributeSingle"
-  );
+                );
   InsertService(meta_class,
                 kCIPSecurityObjectServiceCodeObjectCleanup,
                 &CipSecurityObjectCleanup,
                 "CipSecurityObjectCleanup"
-  );
+                );
   // add Callback function pointers
   class->PreResetCallback = &CipSecurityObjectPreResetCallback;
 }
@@ -404,18 +418,18 @@ EipStatus CipSecurityInit(void) {
   CipInstance *cip_security_object_instance;
 
   cip_security_object_class =
-      CreateCipClass(kCipSecurityObjectClassCode,
-                     0, /* # class attributes */
-                     7, /* # highest class attribute number */
-                     3, /* # class services */
-                     3, /* # instance attributes */
-                     3, /* # highest instance attribute number */
-                     6, /* # instance services */
-                     1, /* # instances*/
-                     "CIP Security Object",
-                     CIP_SECURITY_OBJECT_REVISION, /* # class revision */
-                     &CipSecurityObjectInitializeClassSettings /* # function pointer for initialization */
-      );
+    CreateCipClass(kCipSecurityObjectClassCode,
+                   0,   /* # class attributes */
+                   7,   /* # highest class attribute number */
+                   3,   /* # class services */
+                   3,   /* # instance attributes */
+                   3,   /* # highest instance attribute number */
+                   6,   /* # instance services */
+                   1,   /* # instances*/
+                   "CIP Security Object",
+                   CIP_SECURITY_OBJECT_REVISION,   /* # class revision */
+                   &CipSecurityObjectInitializeClassSettings   /* # function pointer for initialization */
+                   );
 
   if (NULL == cip_security_object_class) {
     /* Initialization failed */
@@ -432,7 +446,7 @@ EipStatus CipSecurityInit(void) {
                   NULL,
                   &g_security.state,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(cip_security_object_instance,
                   2,
                   kCipWord,
@@ -440,7 +454,7 @@ EipStatus CipSecurityInit(void) {
                   NULL,
                   &g_security.security_profiles,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(cip_security_object_instance,
                   3,
                   kCipWord,
@@ -448,39 +462,39 @@ EipStatus CipSecurityInit(void) {
                   NULL,
                   &g_security.security_profiles_configured,
                   kGetableSingleAndAll
-  );
+                  );
 
   /* Add services to the instance */
   InsertService(cip_security_object_class,
                 kGetAttributeSingle,
                 &GetAttributeSingle,
                 "GetAttributeSingle"
-  );
+                );
   InsertService(cip_security_object_class,
                 kGetAttributeAll,
                 &GetAttributeAll,
                 "GetAttributeAll"
-  );
+                );
   InsertService(cip_security_object_class,
                 kReset,
                 &CipResetService,
                 "Reset"
-  );
+                );
   InsertService(cip_security_object_class,
                 kCIPSecurityObjectServiceCodeBeginConfig,
                 &CipSecurityObjectBeginConfig,
                 "CipSecurityObjectBeginConfig"
-  );
+                );
   InsertService(cip_security_object_class,
                 kCIPSecurityObjectServiceCodeKickTimer,
                 &CipSecurityObjectKickTimer,
                 "CipSecurityObjectKickTimer"
-  );
+                );
   InsertService(cip_security_object_class,
                 kCIPSecurityObjectServiceCodeEndConfig,
                 &CipSecurityObjectEndConfig,
                 "CipSecurityObjectEndConfig"
-  );
+                );
 
   /* Register timeout checker function in opener */
   RegisterTimeoutChecker(CipSecuritySessionTimeoutChecker);

+ 5 - 4
source/src/cip/cip_security/cipsecurity.h

@@ -52,7 +52,8 @@ typedef enum {
  */
 typedef enum {
   kCipSecurityObjectSecurityProfileValueEtherNetIpIntegrityProfile = 0x01U,       /**< The device supports the EtherNet/IP Integrity Profile (Obsoleted) */
-  kCipSecurityObjectSecurityProfileValueEtherNetIpConfidentialityProfile = 0x02U, /**< The device supports the EtherNet/IP Confidentiality Profile */
+  kCipSecurityObjectSecurityProfileValueEtherNetIpConfidentialityProfile =
+    0x02U,                                                                        /**< The device supports the EtherNet/IP Confidentiality Profile */
   kCipSecurityObjectSecurityProfileValueCipAuthorizationProfile = 0x04U,          /**< The device supports the CIP Authorization Profile */
   kCipSecurityObjectSecurityProfileValueCipUserAuthenticationProfile = 0x08U,     /**< The device supports the CIP User Authentication Profile */
 } CipSecurityObjectSecurityProfileValue;
@@ -91,7 +92,7 @@ EipStatus CipSecurityInit(void);
  *  @param outgoing_message pointer to the message to be sent
  */
 void EncodeCipSecurityObjectPath(const CipEpath *epath,
-		ENIPMessage *outgoing_message);
+                                 ENIPMessage *outgoing_message);
 
 /** @brief Retrieve the given object instance EPATH according to
  *  CIP encoding from the message buffer.
@@ -105,7 +106,7 @@ void EncodeCipSecurityObjectPath(const CipEpath *epath,
  *          -1 ... error
  */
 int DecodeCipSecurityObjectPath(CipEpath *epath,
-    CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response);
+                                CipMessageRouterRequest *message_router_request,
+                                CipMessageRouterResponse *message_router_response);
 
 #endif  // OPENER_CIPSECURITY_H

+ 226 - 216
source/src/cip/cip_security/ethernetipsecurity.c

@@ -70,50 +70,51 @@
 /**< definition of EtherNet/IP Security object instance 1 data */
 
 CipEpath CMO_Paths[1] = {  // Certificate Management object paths
-    {
-        2,                                     /* PathSize in 16 Bit chunks */
-        kCertificateManagementObjectClassCode, /* Class Code */
-        0x01,                                  /* Instance # */
-    }};
+  {
+    2,                                         /* PathSize in 16 Bit chunks */
+    kCertificateManagementObjectClassCode,     /* Class Code */
+    0x01,                                      /* Instance # */
+  }
+};
 
 const EIPSecurityObjectPathList active_device_certificates = {
-    // at present, a maximum of 1 entry may be configured
-    1,
-    CMO_Paths,
+  // at present, a maximum of 1 entry may be configured
+  1,
+  CMO_Paths,
 };
 
 #define number_of_required_cipher_suites 8
 EIPSecurityObjectCipherSuiteId TLS_RSA_WITH_NULL_SHA256 = {
-    0x00,
-    0x3B,
+  0x00,
+  0x3B,
 };
 EIPSecurityObjectCipherSuiteId TLS_RSA_WITH_AES_128_CBC_SHA256 = {
-    0x00,
-    0x3C,
+  0x00,
+  0x3C,
 };
 EIPSecurityObjectCipherSuiteId TLS_RSA_WITH_AES_256_CBC_SHA256 = {
-    0x00,
-    0x3D,
+  0x00,
+  0x3D,
 };
 EIPSecurityObjectCipherSuiteId TLS_ECDHE_ECDSA_WITH_NULL_SHA = {
-    0xC0,
-    0x06,
+  0xC0,
+  0x06,
 };
 EIPSecurityObjectCipherSuiteId TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = {
-    0xC0,
-    0x23,
+  0xC0,
+  0x23,
 };
 EIPSecurityObjectCipherSuiteId TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = {
-    0xC0,
-    0x24,
+  0xC0,
+  0x24,
 };
 EIPSecurityObjectCipherSuiteId TLS_ECDHE_PSK_WITH_NULL_SHA256 = {
-    0xC0,
-    0x3A,
+  0xC0,
+  0x3A,
 };
 EIPSecurityObjectCipherSuiteId TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = {
-    0xC0,
-    0x37,
+  0xC0,
+  0x37,
 };
 
 //const EIPSecurityObjectCipherSuiteId * cipher_suite_ids[] = {
@@ -133,18 +134,18 @@ EIPSecurityObjectCipherSuiteId TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = {
 //};
 
 EIPSecurityObject g_eip_security = {
-    // TODO: add object configuration
-    .state = kEIPSecurityObjectStateValueFactoryDefaultConfiguration, /** Attribute #1 */
-    .capability_flags = 0,                          /** Attribute #2 */
-    .available_cipher_suites = NULL,                /** Attribute #3 */
-    //.allowed_cipher_suites = allowed_cipher_suites,                         /** Attribute #4 */
-    .active_device_certificates = active_device_certificates, /** Attribute #6 */
-    .pre_shared_keys.number_of_pre_shared_keys = 0, /** Attribute #5 */
-    .check_expiration = 0,                          /** Attribute #11 */
-    .pull_model_enabled = true,  // default: true   /** Attribute #13 */
-    .pull_model_status = 0x0000,                    /** Attribute #14 */
-    .dtls_timeout = 0x0C,  // default: 12 seconds   /** Attribute #15 */
-    .udp_only_policy = 0,                           /** Attribute #16 */
+  // TODO: add object configuration
+  .state = kEIPSecurityObjectStateValueFactoryDefaultConfiguration,   /** Attribute #1 */
+  .capability_flags = 0,                            /** Attribute #2 */
+  .available_cipher_suites = NULL,                  /** Attribute #3 */
+  //.allowed_cipher_suites = allowed_cipher_suites,                         /** Attribute #4 */
+  .active_device_certificates = active_device_certificates,   /** Attribute #6 */
+  .pre_shared_keys.number_of_pre_shared_keys = 0,   /** Attribute #5 */
+  .check_expiration = 0,                            /** Attribute #11 */
+  .pull_model_enabled = true,    // default: true   /** Attribute #13 */
+  .pull_model_status = 0x0000,                      /** Attribute #14 */
+  .dtls_timeout = 0x0C,    // default: 12 seconds   /** Attribute #15 */
+  .udp_only_policy = 0,                             /** Attribute #16 */
 };
 
 //
@@ -209,9 +210,9 @@ void EIPSecurityObjectResetSettableAttributes(CipInstance *instance) {
  *  @See Vol.8, Chapter 5-4.5.1
  */
 EipStatus EIPSecurityObjectPreResetCallback(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
   CipAttributeStruct *attribute = GetCipAttribute(instance, 1);
   CipUint *state = attribute->data;
 
@@ -219,7 +220,7 @@ EipStatus EIPSecurityObjectPreResetCallback(
     CipBool sent_over_TLS = false;  // TODO: check for valid TLS connection
     if (!sent_over_TLS) {
       message_router_response->general_status =
-          kCipErrorPrivilegeViolation;  // 0x0F Permission Denied
+        kCipErrorPrivilegeViolation;    // 0x0F Permission Denied
       return kEipStatusOk;
     }
   }
@@ -258,15 +259,16 @@ EipStatus EIPSecurityObjectPreResetCallback(
  *  @See Vol.8, Chapter 5-4.7.1
  */
 EipStatus EIPSecurityObjectBeginConfig(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorSuccess;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
   CipAttributeStruct *attribute = GetCipAttribute(instance, 1);  // attribute #1 state
   CipUsint state = *(CipUsint *)attribute->data;
@@ -275,7 +277,8 @@ EipStatus EIPSecurityObjectBeginConfig(
     message_router_response->general_status = kCipErrorObjectStateConflict;
   } else {
     // TODO: save current instance config before starting new config
-    *(CipUsint *)attribute->data = kEIPSecurityObjectStateValueConfigurationInProgress;  // set state
+    *(CipUsint *)attribute->data =
+      kEIPSecurityObjectStateValueConfigurationInProgress;                               // set state
 
     // TODO: start configuration session timer
   }
@@ -289,15 +292,16 @@ EipStatus EIPSecurityObjectBeginConfig(
  *  @See Vol.8, Chapter 5-4.7.2
  */
 EipStatus EIPSecurityObjectKickTimer(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorObjectStateConflict;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
   CipAttributeStruct *attribute = GetCipAttribute(instance, 1);  // attribute #1 state
   CipUsint state = *(CipUsint *)attribute->data;
@@ -316,15 +320,16 @@ EipStatus EIPSecurityObjectKickTimer(
  *  @See Vol.8, Chapter 5-4.7.3
  */
 EipStatus EIPSecurityObjectApplyConfig(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorObjectStateConflict;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
   CipAttributeStruct *attribute = GetCipAttribute(instance, 1);  // attribute #1 state
   CipUsint state = *(CipUsint *)attribute->data;
@@ -335,15 +340,16 @@ EipStatus EIPSecurityObjectApplyConfig(
     CipUint close_delay = 0;
 
     if (0 < message_router_request->request_data_size) {
-      apply_behavior_flags = GetWordFromMessage(&(message_router_request->data));
-      close_delay = GetUintFromMessage(&(message_router_request->data));
+      apply_behavior_flags =
+        GetWordFromMessage( &(message_router_request->data) );
+      close_delay = GetUintFromMessage( &(message_router_request->data) );
     }
 
     // check apply behavior
-    if (apply_behavior_flags & (1 << 0)) {  // Bit 0 set
+    if ( apply_behavior_flags & (1 << 0) ) {  // Bit 0 set
       // TODO: close existing connections once close_delay has elapsed
     }
-    if (apply_behavior_flags & (1 << 1)) {  // Bit 1 set
+    if ( apply_behavior_flags & (1 << 1) ) {  // Bit 1 set
       // TODO: run Object_Cleanup service of the CIP Security Object after
       // applying changes
     }
@@ -366,15 +372,16 @@ EipStatus EIPSecurityObjectApplyConfig(
  *  @See Vol.8, Chapter 5-4.7.4
  */
 EipStatus EIPSecurityObjectAbortConfig(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session) {
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session) {
   message_router_response->general_status = kCipErrorObjectStateConflict;
   message_router_response->size_of_additional_status = 0;
   InitializeENIPMessage(&message_router_response->message);
-  message_router_response->reply_service = (0x80 | message_router_request->service);
+  message_router_response->reply_service =
+    (0x80 | message_router_request->service);
 
   CipAttributeStruct *attribute = GetCipAttribute(instance, 1);  // attribute #1 state
   CipUsint state = *(CipUsint *)attribute->data;
@@ -393,94 +400,92 @@ EipStatus EIPSecurityObjectAbortConfig(
 void EncodeEIPSecurityObjectCipherSuiteId(const void *const data,
                                           ENIPMessage *const outgoing_message) {
   EIPSecurityObjectCipherSuiteId *cipher_suite_id =
-      (EIPSecurityObjectCipherSuiteId *)data;
+    (EIPSecurityObjectCipherSuiteId *)data;
 
   EncodeCipUsint(&(cipher_suite_id->iana_first_byte), outgoing_message);
   EncodeCipUsint(&(cipher_suite_id->iana_second_byte), outgoing_message);
 }
 
 int DecodeEIPSecurityObjectCipherSuites(
-        EIPSecurityObjectCipherSuites *const data,
-        const CipMessageRouterRequest *const message_router_request,
-        CipMessageRouterResponse *const message_router_response) {
+  EIPSecurityObjectCipherSuites *const data,
+  const CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
 
-    int number_of_decoded_bytes = -1;
+  int number_of_decoded_bytes = -1;
 
   CipUsint number_of_cipher_suites =
-      GetUsintFromMessage(&(message_router_request->data));
+    GetUsintFromMessage( &(message_router_request->data) );
   number_of_decoded_bytes = sizeof(number_of_cipher_suites);
   CipFree(data->cipher_suite_ids);
 
-     if (number_of_cipher_suites > 0) {
-         EIPSecurityObjectCipherSuiteId *cipher_suite_ids = CipCalloc(
-                number_of_cipher_suites,
-                sizeof(EIPSecurityObjectCipherSuiteId));
+  if (number_of_cipher_suites > 0) {
+    EIPSecurityObjectCipherSuiteId *cipher_suite_ids = CipCalloc(
+      number_of_cipher_suites,
+      sizeof(EIPSecurityObjectCipherSuiteId) );
 
-         memcpy(cipher_suite_ids, &(message_router_request->data),
-                number_of_cipher_suites
-                * sizeof(EIPSecurityObjectCipherSuiteId));
+    memcpy( cipher_suite_ids, &(message_router_request->data),
+            number_of_cipher_suites
+            * sizeof(EIPSecurityObjectCipherSuiteId) );
 
     number_of_decoded_bytes +=
-        number_of_cipher_suites * sizeof(EIPSecurityObjectCipherSuiteId);
+      number_of_cipher_suites * sizeof(EIPSecurityObjectCipherSuiteId);
 
-         data->number_of_cipher_suites = number_of_cipher_suites;
-         data->cipher_suite_ids = cipher_suite_ids;
-    } else {
-       data->cipher_suite_ids = NULL;
-    }
+    data->number_of_cipher_suites = number_of_cipher_suites;
+    data->cipher_suite_ids = cipher_suite_ids;
+  } else {
+    data->cipher_suite_ids = NULL;
+  }
 
-    message_router_response->general_status = kCipErrorSuccess;
-    return number_of_decoded_bytes;
+  message_router_response->general_status = kCipErrorSuccess;
+  return number_of_decoded_bytes;
 }
 
 void EncodeEIPSecurityObjectCipherSuites(const void *const data,
-                                           ENIPMessage *const outgoing_message)
-{
+                                         ENIPMessage *const outgoing_message) {
   EIPSecurityObjectCipherSuites *cipher_suites =
-      (EIPSecurityObjectCipherSuites *) data;
+    (EIPSecurityObjectCipherSuites *) data;
 
   EncodeCipUsint(&(cipher_suites->number_of_cipher_suites), outgoing_message);
 
-  for (int i=0; i<cipher_suites->number_of_cipher_suites; i++) {
+  for (int i = 0; i<cipher_suites->number_of_cipher_suites; i++) {
     EncodeEIPSecurityObjectCipherSuiteId(&(cipher_suites->cipher_suite_ids[i]),
                                          outgoing_message);
   }
 }
 
 void EncodeEIPSecurityObjectPathList(const void *const data,
-                                       ENIPMessage *const outgoing_message)
-{
+                                     ENIPMessage *const outgoing_message) {
   EIPSecurityObjectPathList *path_list = (EIPSecurityObjectPathList *) data;
 
   EncodeCipUsint(&(path_list->number_of_paths), outgoing_message);
 
-  for (int i=0; i<path_list->number_of_paths; i++) {
+  for (int i = 0; i<path_list->number_of_paths; i++) {
     EncodeCipSecurityObjectPath(&(path_list->paths[i]), outgoing_message);
   }
 }
 
 int DecodeEIPSecurityObjectPathList(
-    EIPSecurityObjectPathList *const path_list,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  EIPSecurityObjectPathList *const path_list,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
   int number_of_decoded_bytes = -1;
 
   path_list->number_of_paths =
-      GetUsintFromMessage(&message_router_request->data);
+    GetUsintFromMessage(&message_router_request->data);
   number_of_decoded_bytes = 1;
 
-	if (0 != path_list->number_of_paths) {
-		for (int i = 0; i < path_list->number_of_paths; i++) {
-			number_of_decoded_bytes += DecodeCipSecurityObjectPath(
-					&(path_list->paths[i]), message_router_request,
-					message_router_response);
-		}
-	} else {
-		message_router_response->general_status = kCipErrorSuccess;
-	}
-
-	OPENER_TRACE_INFO("Number_of_decoded bytes: %d\n", number_of_decoded_bytes);
-	return number_of_decoded_bytes;
+  if (0 != path_list->number_of_paths) {
+    for (int i = 0; i < path_list->number_of_paths; i++) {
+      number_of_decoded_bytes += DecodeCipSecurityObjectPath(
+        &(path_list->paths[i]), message_router_request,
+        message_router_response);
+    }
+  } else {
+    message_router_response->general_status = kCipErrorSuccess;
+  }
+
+  OPENER_TRACE_INFO("Number_of_decoded bytes: %d\n", number_of_decoded_bytes);
+  return number_of_decoded_bytes;
 }
 
 /** @brief When accessed via Get_Attributes_All or Get_Attribute_Single, the
@@ -494,12 +499,13 @@ void EncodeEIPSecurityObjectPreSharedKeys(const void *const data,
 }
 
 int DecodeEIPSecurityObjectPreSharedKeys(
-    EIPSecurityObjectPreSharedKeys *const pre_shared_keys,
-    CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  EIPSecurityObjectPreSharedKeys *const pre_shared_keys,
+  CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
   int number_of_decoded_bytes = -1;
 
-  CipUsint number_of_psk = GetUsintFromMessage(&(message_router_request->data));
+  CipUsint number_of_psk =
+    GetUsintFromMessage( &(message_router_request->data) );
 
   // At present, a maximum of 1 PSK may be configured
   if (number_of_psk > 1) {
@@ -509,16 +515,18 @@ int DecodeEIPSecurityObjectPreSharedKeys(
 
   if (number_of_psk == 1) {
     EIPSecurityObjectPreSharedKey *psk_structure =
-        CipCalloc(number_of_psk, sizeof(EIPSecurityObjectPreSharedKey));
+      CipCalloc( number_of_psk, sizeof(EIPSecurityObjectPreSharedKey) );
 
     psk_structure->psk_identity_size =
-        GetUsintFromMessage(&(message_router_request->data));
+      GetUsintFromMessage( &(message_router_request->data) );
 
     if (psk_structure->psk_identity_size <= SIZE_MAX_PSK_IDENTITY) {
       CipOctet *psk_identity =
-          CipCalloc(psk_structure->psk_identity_size, sizeof(CipOctet));
+        CipCalloc( psk_structure->psk_identity_size, sizeof(CipOctet) );
 
-      memcpy(psk_identity, message_router_request->data, psk_structure->psk_identity_size);
+      memcpy(psk_identity,
+             message_router_request->data,
+             psk_structure->psk_identity_size);
       message_router_request->data += psk_structure->psk_identity_size;
       //          for (int i=0; i<psk_structure->psk_identity_size; i++) {
       //            psk_identity[i] =
@@ -526,10 +534,11 @@ int DecodeEIPSecurityObjectPreSharedKeys(
       //          }
 
       psk_structure->psk_identity = psk_identity;
-      psk_structure->psk_size = GetUsintFromMessage(&(message_router_request->data));
+      psk_structure->psk_size =
+        GetUsintFromMessage( &(message_router_request->data) );
 
       if (psk_structure->psk_size <= SIZE_MAX_PSK) {
-        CipOctet *psk = CipCalloc(psk_structure->psk_size, sizeof(CipOctet));
+        CipOctet *psk = CipCalloc( psk_structure->psk_size, sizeof(CipOctet) );
 
         memcpy(psk, message_router_request->data, psk_structure->psk_size);
         //            for (int i=0; i<psk_structure->psk_size; i++) {
@@ -550,7 +559,7 @@ int DecodeEIPSecurityObjectPreSharedKeys(
           CipFree(psk_structure);
         }
         message_router_response->general_status =
-            kCipErrorInvalidAttributeValue;
+          kCipErrorInvalidAttributeValue;
       }
     } else {
       if (psk_structure != NULL) {
@@ -569,18 +578,19 @@ int DecodeEIPSecurityObjectPreSharedKeys(
 }
 
 int DecodeDTLSTimeout(
-    CipUint *const data,
-    const CipMessageRouterRequest *const message_router_request,
-    CipMessageRouterResponse *const message_router_response) {
+  CipUint *const data,
+  const CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response) {
   CipInstance *const instance =
-      GetCipInstance(GetCipClass(message_router_request->request_path.class_id),
-                     message_router_request->request_path.instance_number);
+    GetCipInstance(GetCipClass(message_router_request->request_path.class_id),
+                   message_router_request->request_path.instance_number);
 
   CipAttributeStruct *attribute = GetCipAttribute(instance, 1);  // attribute #1 state
   CipUsint state = *(CipUsint *)attribute->data;
 
   if (kEIPSecurityObjectStateValueConfigurationInProgress == state) {
-    CipUint dtls_timeout = GetUintFromMessage(&(message_router_request->data));
+    CipUint dtls_timeout =
+      GetUintFromMessage( &(message_router_request->data) );
 
     if (0 <= dtls_timeout && 3600 >= dtls_timeout) {
       *data = dtls_timeout;
@@ -599,67 +609,67 @@ void EIPSecurityObjectInitializeClassSettings(CipClass *class) {
 
   CipClass *meta_class = class->class_instance.cip_class;
 
-  InsertAttribute((CipInstance *) class,
-                  1,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->revision,
-                  kGetableSingleAndAll);  /* revision */
-  InsertAttribute((CipInstance *) class,
-                  2,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->number_of_instances,
-                  kGetableSingleAndAll); /*  largest instance number */
-  InsertAttribute((CipInstance *) class,
-                  3,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->number_of_instances,
-                  kGetableSingle); /* number of instances currently existing*/
-  InsertAttribute((CipInstance *) class,
-                  4,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &kCipUintZero,
-                  kNotSetOrGetable); /* optional attribute list - default = 0 */
-  InsertAttribute((CipInstance *) class,
-                  5,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &kCipUintZero,
-                  kNotSetOrGetable); /* optional service list - default = 0 */
-  InsertAttribute((CipInstance *) class,
-                  6,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &meta_class->highest_attribute_number,
-                  kGetableSingleAndAll); /* max class attribute number*/
-  InsertAttribute((CipInstance *) class,
-                  7,
-                  kCipUint,
-                  EncodeCipUint,
-                  NULL,
-                  (void *) &class->highest_attribute_number,
-                  kGetableSingleAndAll); /* max instance attribute number*/
+  InsertAttribute( (CipInstance *) class,
+                   1,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->revision,
+                   kGetableSingleAndAll ); /* revision */
+  InsertAttribute( (CipInstance *) class,
+                   2,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->number_of_instances,
+                   kGetableSingleAndAll ); /*  largest instance number */
+  InsertAttribute( (CipInstance *) class,
+                   3,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->number_of_instances,
+                   kGetableSingle ); /* number of instances currently existing*/
+  InsertAttribute( (CipInstance *) class,
+                   4,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &kCipUintZero,
+                   kNotSetOrGetable ); /* optional attribute list - default = 0 */
+  InsertAttribute( (CipInstance *) class,
+                   5,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &kCipUintZero,
+                   kNotSetOrGetable ); /* optional service list - default = 0 */
+  InsertAttribute( (CipInstance *) class,
+                   6,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &meta_class->highest_attribute_number,
+                   kGetableSingleAndAll ); /* max class attribute number*/
+  InsertAttribute( (CipInstance *) class,
+                   7,
+                   kCipUint,
+                   EncodeCipUint,
+                   NULL,
+                   (void *) &class->highest_attribute_number,
+                   kGetableSingleAndAll ); /* max instance attribute number*/
 
   /* Add class services to the meta class */
   InsertService(meta_class,
                 kGetAttributeAll,
                 &GetAttributeAll,
                 "GetAttributeAll"
-  );
+                );
   InsertService(meta_class,
                 kGetAttributeSingle,
                 &GetAttributeSingle,
                 "GetAttributeSingle"
-  );
+                );
   // add Callback function pointers
   class->PreResetCallback = &EIPSecurityObjectPreResetCallback;
 }
@@ -670,18 +680,18 @@ EipStatus EIPSecurityInit(void) {
   CipInstance *eip_security_object_instance;
 
   eip_security_object_class = CreateCipClass(
-      kEIPSecurityObjectClassCode, 0, /* # class attributes */
-      7,                              /* # highest class attribute number */
-      2,                              /* # class services */
-      16,                             /* # instance attributes */
-      16,                             /* # highest instance attribute number */
-      8,                              /* # instance services */
-      1,                              /* # instances*/
-      "EtherNet/IP Security Object",
-      ETHERNET_IP_SECURITY_OBJECT_REVISION,     /* # class revision */
-      &EIPSecurityObjectInitializeClassSettings /* # function pointer for
+    kEIPSecurityObjectClassCode, 0,   /* # class attributes */
+    7,                                /* # highest class attribute number */
+    2,                                /* # class services */
+    16,                               /* # instance attributes */
+    16,                               /* # highest instance attribute number */
+    8,                                /* # instance services */
+    1,                                /* # instances*/
+    "EtherNet/IP Security Object",
+    ETHERNET_IP_SECURITY_OBJECT_REVISION,       /* # class revision */
+    &EIPSecurityObjectInitializeClassSettings   /* # function pointer for
                                                    initialization */
-  );
+    );
 
   if (NULL == eip_security_object_class) {
     /* Initialization failed */
@@ -698,7 +708,7 @@ EipStatus EIPSecurityInit(void) {
                   NULL,
                   &g_eip_security.state,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   2,
                   kCipWord,
@@ -706,7 +716,7 @@ EipStatus EIPSecurityInit(void) {
                   NULL,
                   &g_eip_security.capability_flags,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   3,
                   kCipAny,
@@ -714,7 +724,7 @@ EipStatus EIPSecurityInit(void) {
                   NULL,
                   &g_eip_security.available_cipher_suites,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   4,
                   kCipAny,
@@ -722,7 +732,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeEIPSecurityObjectCipherSuites,
                   &g_eip_security.allowed_cipher_suites,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   5,
                   kCipAny,
@@ -730,7 +740,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeEIPSecurityObjectPreSharedKeys,
                   &g_eip_security.pre_shared_keys,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   6,
                   kCipAny,
@@ -738,7 +748,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeEIPSecurityObjectPathList,
                   &g_eip_security.active_device_certificates,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   7,
                   kCipAny,
@@ -746,7 +756,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeEIPSecurityObjectPathList,
                   &g_eip_security.trusted_authorities,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   8,
                   kCipEpath,
@@ -754,7 +764,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeCipSecurityObjectPath,
                   &g_eip_security.certificate_revocation_list,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   9,
                   kCipBool,
@@ -762,7 +772,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeCipBool,
                   &g_eip_security.verify_client_certificate,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   10,
                   kCipBool,
@@ -770,7 +780,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeCipBool,
                   &g_eip_security.send_certificate_chain,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   11,
                   kCipBool,
@@ -778,7 +788,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeCipBool,
                   &g_eip_security.check_expiration,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   12,
                   kCipAny,
@@ -786,7 +796,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeEIPSecurityObjectPathList,
                   &g_eip_security.trusted_identities,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   13,
                   kCipBool,
@@ -794,7 +804,7 @@ EipStatus EIPSecurityInit(void) {
                   NULL,
                   &g_eip_security.pull_model_enabled,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   14,
                   kCipUint,
@@ -802,7 +812,7 @@ EipStatus EIPSecurityInit(void) {
                   NULL,
                   &g_eip_security.pull_model_status,
                   kGetableSingleAndAll
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   15,
                   kCipUint,
@@ -810,7 +820,7 @@ EipStatus EIPSecurityInit(void) {
                   DecodeDTLSTimeout,
                   &g_eip_security.dtls_timeout,
                   kSetAndGetAble
-  );
+                  );
   InsertAttribute(eip_security_object_instance,
                   16,
                   kCipUsint,
@@ -818,49 +828,49 @@ EipStatus EIPSecurityInit(void) {
                   DecodeCipUsint,
                   &g_eip_security.udp_only_policy,
                   kSetAndGetAble
-  );
+                  );
 
   /* Add services to the instance */
   InsertService(eip_security_object_class,
                 kGetAttributeAll,
                 &GetAttributeAll,
                 "GetAttributeAll"
-  );
+                );
   InsertService(eip_security_object_class,
                 kReset,
                 &CipResetService,
                 "Reset"
-  );
+                );
   InsertService(eip_security_object_class,
                 kGetAttributeSingle,
                 &GetAttributeSingle,
                 "GetAttributeSingle"
-  );
+                );
   InsertService(eip_security_object_class,
                 kSetAttributeSingle,
                 &SetAttributeSingle,
                 "SetAttributeSingle"
-  );
+                );
   InsertService(eip_security_object_class,
                 kEIPSecurityObjectServiceCodeBeginConfig,
                 &EIPSecurityObjectBeginConfig,
                 "EIPSecurityObjectBeginConfig"
-  );
+                );
   InsertService(eip_security_object_class,
                 kEIPSecurityObjectServiceCodeKickTimer,
                 &EIPSecurityObjectKickTimer,
                 "EIPSecurityObjectKickTimer"
-  );
+                );
   InsertService(eip_security_object_class,
                 kEIPSecurityObjectServiceCodeApplyConfig,
                 &EIPSecurityObjectApplyConfig,
                 "EIPSecurityObjectApplyConfig"
-  );
+                );
   InsertService(eip_security_object_class,
                 kEIPSecurityObjectServiceCodeAbortConfig,
                 &EIPSecurityObjectAbortConfig,
                 "EIPSecurityObjectAbortConfig"
-  );
+                );
 
   return kEipStatusOk;
 }

+ 9 - 6
source/src/cip/cip_security/ethernetipsecurity.h

@@ -64,9 +64,12 @@ typedef enum {
  */
 typedef enum {
   kEIPSecurityObjectApplyConfigErrorCodeExtendedNoPSKConfigured = 0x0001,                 /**< Only PSK cipher suited allowed but no Pre-Shared Keys configured */
-  kEIPSecurityObjectApplyConfigErrorCodeExtendedNoCertificatesConfigured = 0x0002,        /**< Only certificate suites allowed, but no certificates configured */
-  kEIPSecurityObjectApplyConfigErrorCodeExtendedCertificateSuitesNoneConsistent = 0x0003, /**< Certificate suites allowed but none consistent with the device private key type */
-  kEIPSecurityObjectApplyConfigErrorCodeExtendedNoActiveCipherSuitesConfigured = 0x0004,  /**< No Active Cipher Suites configured */
+  kEIPSecurityObjectApplyConfigErrorCodeExtendedNoCertificatesConfigured =
+    0x0002,                                                                               /**< Only certificate suites allowed, but no certificates configured */
+  kEIPSecurityObjectApplyConfigErrorCodeExtendedCertificateSuitesNoneConsistent
+    = 0x0003,                                                                             /**< Certificate suites allowed but none consistent with the device private key type */
+  kEIPSecurityObjectApplyConfigErrorCodeExtendedNoActiveCipherSuitesConfigured =
+    0x0004,                                                                               /**< No Active Cipher Suites configured */
 } EIPSecurityObjectApplyConfigErrorCodeExtended;
 
 /** @brief Type declaration for a single IANA cipher suite ID
@@ -166,8 +169,8 @@ void EIPSecurityObjectResetSettableAttributes(CipInstance *instance);
  *  @See Vol.8, Chapter 5-4.5.1
  */
 EipStatus EIPSecurityObjectPreResetCallback(
-    CipInstance *instance,
-    CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response);
+  CipInstance *instance,
+  CipMessageRouterRequest *message_router_request,
+  CipMessageRouterResponse *message_router_response);
 
 #endif  // OPENER_ETHERNETIPSECURITY_H

+ 3 - 3
source/src/cip/cipassembly.c

@@ -109,9 +109,9 @@ CipInstance *CreateAssemblyObject(const EipUint32 instance_id,
 
   CipInstance *const instance = AddCipInstance(assembly_class, instance_id); /* add instances (always succeeds (or asserts))*/
 
-  CipByteArray *const assembly_byte_array = (CipByteArray *) CipCalloc(1,
-                                                                       sizeof(
-                                                                         CipByteArray) );
+  CipByteArray *const assembly_byte_array = (CipByteArray *) CipCalloc( 1,
+                                                                        sizeof(
+                                                                          CipByteArray) );
   if(assembly_byte_array == NULL) {
     return NULL; /*TODO remove assembly instance in case of error*/
   }

+ 1 - 1
source/src/cip/cipclass3connection.c

@@ -60,7 +60,7 @@ CipError EstablishClass3Connection(
  */
 CipConnectionObject *GetFreeExplicitConnection(void) {
   for (size_t i = 0; i < OPENER_CIP_NUM_EXPLICIT_CONNS; ++i) {
-    if (ConnectionObjectGetState(&(explicit_connection_object_pool[i]) ) ==
+    if (ConnectionObjectGetState( &(explicit_connection_object_pool[i]) ) ==
         kConnectionObjectStateNonExistent) {
       return &(explicit_connection_object_pool[i]);
     }

+ 28 - 28
source/src/cip/cipcommon.h

@@ -38,7 +38,7 @@ EipStatus NotifyClass(const CipClass *const RESTRICT cip_class,
  * @param cip_class class to be considered
  * @return largest instance_number in class instances
  */
-CipUint GetMaxInstanceNumber(CipClass *RESTRICT const cip_class);                      
+CipUint GetMaxInstanceNumber(CipClass *RESTRICT const cip_class);
 
 void GenerateGetAttributeSingleHeader(
   const CipMessageRouterRequest *const message_router_request,
@@ -121,10 +121,10 @@ EipStatus GetAttributeAll(CipInstance *instance,
  *              0 .. no reply to send
  */
 EipStatus GetAttributeList(CipInstance *instance,
-                          CipMessageRouterRequest *message_router_request,
-                          CipMessageRouterResponse *message_router_response,
-                          const struct sockaddr *originator_address,
-                          const int encapsulation_session);
+                           CipMessageRouterRequest *message_router_request,
+                           CipMessageRouterResponse *message_router_response,
+                           const struct sockaddr *originator_address,
+                           const int encapsulation_session);
 
 /** @brief Generic implementation of the SetAttributeList CIP service
  *
@@ -139,10 +139,10 @@ EipStatus GetAttributeList(CipInstance *instance,
  *              0 .. no reply to send
  */
 EipStatus SetAttributeList(CipInstance *instance,
-                          CipMessageRouterRequest *message_router_request,
-                          CipMessageRouterResponse *message_router_response,
-                          const struct sockaddr *originator_address,
-                          const int encapsulation_session);
+                           CipMessageRouterRequest *message_router_request,
+                           CipMessageRouterResponse *message_router_response,
+                           const struct sockaddr *originator_address,
+                           const int encapsulation_session);
 
 /** @brief Decodes padded EPath
  *  @param epath EPath object to the receiving element
@@ -165,13 +165,13 @@ int DecodePaddedEPath(CipEpath *epath,
  *          -1 .. requested instance not created
  */
 EipStatus CipCreateService(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const
-        message_router_request,
-    CipMessageRouterResponse *const
-        message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session);
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *const
+  message_router_request,
+  CipMessageRouterResponse *const
+  message_router_response,
+  const struct sockaddr *originator_address,
+  const int encapsulation_session);
 
 /** @brief Generic implementation of the CIP Delete service
  *
@@ -187,12 +187,12 @@ EipStatus CipCreateService(
  *          -1 .. requested instance not deleted
  */
 EipStatus CipDeleteService(CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const
-        message_router_request,
-    CipMessageRouterResponse *const
-        message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session);
+                           CipMessageRouterRequest *const
+                           message_router_request,
+                           CipMessageRouterResponse *const
+                           message_router_response,
+                           const struct sockaddr *originator_address,
+                           const int encapsulation_session);
 
 /** @brief Generic implementation of the CIP Reset service
  *
@@ -209,11 +209,11 @@ EipStatus CipDeleteService(CipInstance *RESTRICT const instance,
  *          -1 .. requested instance not reseted
  */
 EipStatus CipResetService(CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *const
-        message_router_request,
-    CipMessageRouterResponse *const
-        message_router_response,
-    const struct sockaddr *originator_address,
-    const int encapsulation_session);
+                          CipMessageRouterRequest *const
+                          message_router_request,
+                          CipMessageRouterResponse *const
+                          message_router_response,
+                          const struct sockaddr *originator_address,
+                          const int encapsulation_session);
 
 #endif /* OPENER_CIPCOMMON_H_ */

+ 113 - 104
source/src/cip/cipconnectionmanager.c

@@ -193,7 +193,7 @@ CipUdint GetConnectionId(void) {
 #else
   CipUint connection_id = NextXorShiftUint32();
 #endif
-  return (g_incarnation_id | (connection_id & 0x0000FFFF) );
+  return ( g_incarnation_id | (connection_id & 0x0000FFFF) );
 }
 
 void InitializeConnectionManager(CipClass *class) {
@@ -285,8 +285,9 @@ EipStatus HandleReceivedConnectedData(const EipUint8 *const data,
                                       int data_length,
                                       struct sockaddr_in *from_address) {
 
-  if( (CreateCommonPacketFormatStructure(data, data_length,
-                                         &g_common_packet_format_data_item) ) ==
+  if( ( CreateCommonPacketFormatStructure(data, data_length,
+                                          &g_common_packet_format_data_item) )
+      ==
       kEipStatusError ) {
     return kEipStatusError;
   } else {
@@ -455,9 +456,9 @@ EipStatus HandleNonNullNonMatchingForwardOpenRequest(
   EipUint16 connection_status = kConnectionManagerExtendedStatusCodeSuccess;
 
   /*check if the trigger type value is invalid or ok */
-  if(kConnectionObjectTransportClassTriggerProductionTriggerInvalid ==
-     ConnectionObjectGetTransportClassTriggerProductionTrigger(&
-                                                               g_dummy_connection_object) )
+  if( kConnectionObjectTransportClassTriggerProductionTriggerInvalid ==
+      ConnectionObjectGetTransportClassTriggerProductionTrigger(&
+                                                                g_dummy_connection_object) )
   {
     return AssembleForwardOpenResponse(&g_dummy_connection_object,
                                        message_router_response,
@@ -594,9 +595,9 @@ EipStatus ForwardOpenRoutine(CipInstance *instance,
   g_dummy_connection_object.associated_encapsulation_session =
     encapsulation_session;
 
-  memcpy(&(g_dummy_connection_object.originator_address),
-         originator_address,
-         sizeof(g_dummy_connection_object.originator_address) );
+  memcpy( &(g_dummy_connection_object.originator_address),
+          originator_address,
+          sizeof(g_dummy_connection_object.originator_address) );
 
   ConnectionObjectConnectionType o_to_t_connection_type =
     ConnectionObjectGetOToTConnectionType(&g_dummy_connection_object);
@@ -643,7 +644,7 @@ EipStatus ForwardOpenRoutine(CipInstance *instance,
   }
 
   /* Check if we have a matching or non matching request */
-  if(NULL != CheckForExistingConnection(&g_dummy_connection_object) ) {
+  if( NULL != CheckForExistingConnection(&g_dummy_connection_object) ) {
     OPENER_TRACE_INFO("We have a Matching request\n");
     is_matching_request = true;
 
@@ -694,10 +695,10 @@ EipStatus ForwardClose(CipInstance *instance,
   while(NULL != node) {
     /* this check should not be necessary as only established connections should be in the active connection list */
     CipConnectionObject *connection_object = node->data;
-    if( (kConnectionObjectStateEstablished ==
-         ConnectionObjectGetState(connection_object) )
-        || (kConnectionObjectStateTimedOut ==
-            ConnectionObjectGetState(connection_object) ) ) {
+    if( ( kConnectionObjectStateEstablished ==
+          ConnectionObjectGetState(connection_object) )
+        || ( kConnectionObjectStateTimedOut ==
+             ConnectionObjectGetState(connection_object) ) ) {
       if( (connection_object->connection_serial_number ==
            connection_serial_number) &&
           (connection_object->originator_vendor_id == originator_vendor_id)
@@ -932,11 +933,11 @@ EipStatus ManageConnections(MilliSeconds elapsed_time) {
   while(NULL != node) {
     //OPENER_TRACE_INFO("Entering Connection Object loop\n");
     CipConnectionObject *connection_object = node->data;
-    if(kConnectionObjectStateEstablished ==
-       ConnectionObjectGetState(connection_object) ) {
+    if( kConnectionObjectStateEstablished ==
+        ConnectionObjectGetState(connection_object) ) {
       if( (NULL != connection_object->consuming_instance) || /* we have a consuming connection check inactivity watchdog timer */
-          (kConnectionObjectTransportClassTriggerDirectionServer ==
-           ConnectionObjectGetTransportClassTriggerDirection(connection_object) ) ) /* all server connections have to maintain an inactivity watchdog timer */
+          ( kConnectionObjectTransportClassTriggerDirectionServer ==
+            ConnectionObjectGetTransportClassTriggerDirection(connection_object) ) ) /* all server connections have to maintain an inactivity watchdog timer */
       {
         if(elapsed_time >= connection_object->inactivity_watchdog_timer) {
           /* we have a timed out connection perform watchdog time out action*/
@@ -950,16 +951,16 @@ EipStatus ManageConnections(MilliSeconds elapsed_time) {
         }
       }
       /* only if the connection has not timed out check if data is to be send */
-      if(kConnectionObjectStateEstablished ==
-         ConnectionObjectGetState(connection_object) ) {
+      if( kConnectionObjectStateEstablished ==
+          ConnectionObjectGetState(connection_object) ) {
         /* client connection */
-        if( (0 != ConnectionObjectGetExpectedPacketRate(connection_object) )
+        if( ( 0 != ConnectionObjectGetExpectedPacketRate(connection_object) )
             && (kEipInvalidSocket !=
                 connection_object->socket[kUdpCommuncationDirectionProducing]) ) /* only produce for the master connection */
         {
-          if(kConnectionObjectTransportClassTriggerProductionTriggerCyclic !=
-             ConnectionObjectGetTransportClassTriggerProductionTrigger(
-               connection_object) ) {
+          if( kConnectionObjectTransportClassTriggerProductionTriggerCyclic !=
+              ConnectionObjectGetTransportClassTriggerProductionTrigger(
+                connection_object) ) {
             /* non cyclic connections have to decrement production inhibit timer */
             if(elapsed_time <= connection_object->production_inhibit_timer) {
               //The connection is allowed to send again
@@ -985,13 +986,15 @@ EipStatus ManageConnections(MilliSeconds elapsed_time) {
               connection_object->transmission_trigger_timer -= elapsed_time;
             } else {  /* elapsed time was longer than RPI */
               connection_object->transmission_trigger_timer = 0;
-              OPENER_TRACE_INFO("elapsed time: %lu ms was longer than RPI: %u ms\n",
-                                elapsed_time,
-                                ConnectionObjectGetRequestedPacketInterval(connection_object));
+              OPENER_TRACE_INFO(
+                "elapsed time: %lu ms was longer than RPI: %u ms\n",
+                elapsed_time,
+                ConnectionObjectGetRequestedPacketInterval(
+                  connection_object) );
             }
-            if(kConnectionObjectTransportClassTriggerProductionTriggerCyclic !=
-               ConnectionObjectGetTransportClassTriggerProductionTrigger(
-                 connection_object) ) {
+            if( kConnectionObjectTransportClassTriggerProductionTriggerCyclic !=
+                ConnectionObjectGetTransportClassTriggerProductionTrigger(
+                  connection_object) ) {
               /* non cyclic connections have to reload the production inhibit timer */
               ConnectionObjectResetProductionInhibitTimer(connection_object);
             }
@@ -1056,7 +1059,10 @@ EipStatus AssembleForwardOpenResponse(CipConnectionObject *connection_object,
                      &message_router_response->message);
   } else {
     /* we have an connection creation error */
-    OPENER_TRACE_WARN("AssembleForwardOpenResponse: sending error response, general/extended status=%d/%d\n", general_status, extended_status);
+    OPENER_TRACE_WARN(
+      "AssembleForwardOpenResponse: sending error response, general/extended status=%d/%d\n",
+      general_status,
+      extended_status);
     ConnectionObjectSetState(connection_object,
                              kConnectionObjectStateNonExistent);
     /* Expected data length is 10 octets */
@@ -1200,10 +1206,10 @@ CipConnectionObject *GetConnectedObject(const EipUint32 connection_id) {
   DoublyLinkedListNode *iterator = connection_list.first;
 
   while(NULL != iterator) {
-    if(kConnectionObjectStateEstablished ==
-       ConnectionObjectGetState(iterator->data)
-       && connection_id ==
-       ConnectionObjectGetCipConsumedConnectionID(iterator->data) ) {
+    if( kConnectionObjectStateEstablished ==
+        ConnectionObjectGetState(iterator->data)
+        && connection_id ==
+        ConnectionObjectGetCipConsumedConnectionID(iterator->data) ) {
       return iterator->data;
     }
     iterator = iterator->next;
@@ -1218,10 +1224,10 @@ CipConnectionObject *GetConnectedOutputAssembly(
   while(NULL != iterator) {
     if(kConnectionObjectInstanceTypeIOExclusiveOwner ==
        ConnectionObjectGetInstanceType(iterator->data)
-       && (kConnectionObjectStateEstablished ==
-           ConnectionObjectGetState(iterator->data)
-           || kConnectionObjectStateTimedOut ==
-           ConnectionObjectGetState(iterator->data) )
+       && ( kConnectionObjectStateEstablished ==
+            ConnectionObjectGetState(iterator->data)
+            || kConnectionObjectStateTimedOut ==
+            ConnectionObjectGetState(iterator->data) )
        && output_assembly_id ==
        ( (CipConnectionObject *) iterator->data )->produced_path.instance_id) {
       return iterator->data;
@@ -1237,9 +1243,9 @@ CipConnectionObject *CheckForExistingConnection(
   DoublyLinkedListNode *iterator = connection_list.first;
 
   while(NULL != iterator) {
-    if(kConnectionObjectStateEstablished ==
-       ConnectionObjectGetState(iterator->data) ) {
-      if(EqualConnectionTriad(connection_object, iterator->data) ) {
+    if( kConnectionObjectStateEstablished ==
+        ConnectionObjectGetState(iterator->data) ) {
+      if( EqualConnectionTriad(connection_object, iterator->data) ) {
         return iterator->data;
       }
     }
@@ -1289,7 +1295,7 @@ EipStatus CheckElectronicKeyData(EipUint8 key_format,
 
       if(false == compatiblity_mode) {
         /* Major = 0 is valid */
-        if(0 == ElectronicKeyFormat4GetMajorRevision(key_data) ) {
+        if( 0 == ElectronicKeyFormat4GetMajorRevision(key_data) ) {
           return kEipStatusOk;
         }
 
@@ -1369,13 +1375,13 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
 
   if(remaining_path > 0) {
     /* first look if there is an electronic key */
-    if(kSegmentTypeLogicalSegment == GetPathSegmentType(message) ) {
-      if(kLogicalSegmentLogicalTypeSpecial ==
-         GetPathLogicalSegmentLogicalType(message) ) {
-        if(kLogicalSegmentSpecialTypeLogicalFormatElectronicKey ==
-           GetPathLogicalSegmentSpecialTypeLogicalType(message) ) {
-          if(kElectronicKeySegmentFormatKeyFormat4 ==
-             GetPathLogicalSegmentElectronicKeyFormat(message) ) {
+    if( kSegmentTypeLogicalSegment == GetPathSegmentType(message) ) {
+      if( kLogicalSegmentLogicalTypeSpecial ==
+          GetPathLogicalSegmentLogicalType(message) ) {
+        if( kLogicalSegmentSpecialTypeLogicalFormatElectronicKey ==
+            GetPathLogicalSegmentSpecialTypeLogicalType(message) ) {
+          if( kElectronicKeySegmentFormatKeyFormat4 ==
+              GetPathLogicalSegmentElectronicKeyFormat(message) ) {
             /* Check if there is enough data for holding the electronic key segment */
             if(remaining_path < 5) {
               *extended_error = 0;
@@ -1402,12 +1408,12 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
                                                    electronic_key.key_data),
               ElectronicKeyFormat4GetMinorRevision(connection_object->
                                                    electronic_key.key_data) );
-            if(kEipStatusOk
-               != CheckElectronicKeyData(connection_object->electronic_key.
-                                         key_format,
-                                         connection_object->electronic_key.
-                                         key_data,
-                                         extended_error) ) {
+            if( kEipStatusOk
+                != CheckElectronicKeyData(connection_object->electronic_key.
+                                          key_format,
+                                          connection_object->electronic_key.
+                                          key_data,
+                                          extended_error) ) {
               ElectronicKeyFormat4Delete(&electronic_key);
               return kCipErrorConnectionFailure;
             }
@@ -1421,12 +1427,12 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
     }
 
     //TODO: Refactor this afterwards
-    if(kConnectionObjectTransportClassTriggerProductionTriggerCyclic !=
-       ConnectionObjectGetTransportClassTriggerProductionTrigger(
-         connection_object) )
+    if( kConnectionObjectTransportClassTriggerProductionTriggerCyclic !=
+        ConnectionObjectGetTransportClassTriggerProductionTrigger(
+          connection_object) )
     {
       /*non cyclic connections may have a production inhibit */
-      if(kSegmentTypeNetworkSegment == GetPathSegmentType(message) ) {
+      if( kSegmentTypeNetworkSegment == GetPathSegmentType(message) ) {
         NetworkSegmentSubtype network_segment_subtype =
           GetPathNetworkSegmentSubtype(message);
         if(kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds ==
@@ -1439,9 +1445,9 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
       }
     }
 
-    if(kSegmentTypeLogicalSegment == GetPathSegmentType(message) &&
-       kLogicalSegmentLogicalTypeClassId ==
-       GetPathLogicalSegmentLogicalType(message) ) {
+    if( kSegmentTypeLogicalSegment == GetPathSegmentType(message) &&
+        kLogicalSegmentLogicalTypeClassId ==
+        GetPathLogicalSegmentLogicalType(message) ) {
 
       class_id = CipEpathGetLogicalValue(&message);
       class = GetCipClass(class_id);
@@ -1470,14 +1476,14 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
     remaining_path -= 1; /* 1 16Bit word for the class part of the path */
 
     /* Get instance ID */
-    if(kSegmentTypeLogicalSegment == GetPathSegmentType(message) &&
-       kLogicalSegmentLogicalTypeInstanceId ==
-       GetPathLogicalSegmentLogicalType(message) ) { /* store the configuration ID for later checking in the application connection types */
+    if( kSegmentTypeLogicalSegment == GetPathSegmentType(message) &&
+        kLogicalSegmentLogicalTypeInstanceId ==
+        GetPathLogicalSegmentLogicalType(message) ) { /* store the configuration ID for later checking in the application connection types */
       instance_id = CipEpathGetLogicalValue(&message);
 
       OPENER_TRACE_INFO("Configuration instance id %" PRId32 "\n",
                         instance_id);
-      if(NULL == GetCipInstance(class, instance_id) ) {
+      if( NULL == GetCipInstance(class, instance_id) ) {
         /*according to the test tool we should respond with this extended error code */
         *extended_error =
           kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
@@ -1489,8 +1495,9 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
       OPENER_TRACE_INFO("no config data\n");
     }
 
-    if(kConnectionObjectTransportClassTriggerTransportClass3 ==
-       ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
+    if( kConnectionObjectTransportClassTriggerTransportClass3 ==
+        ConnectionObjectGetTransportClassTriggerTransportClass(
+          connection_object) )
     {
       /*we have Class 3 connection*/
       if(remaining_path > 0) {
@@ -1512,20 +1519,20 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
       { .class_id = class_id, .instance_id = instance_id,
         .attribute_id_or_connection_point = 0 };
 
-      memcpy(&(connection_object->configuration_path),
-             &connection_epath,
-             sizeof(connection_object->configuration_path) );
-      memcpy(&(connection_object->produced_path), &connection_epath,
-             sizeof(connection_object->produced_path) );
+      memcpy( &(connection_object->configuration_path),
+              &connection_epath,
+              sizeof(connection_object->configuration_path) );
+      memcpy( &(connection_object->produced_path), &connection_epath,
+              sizeof(connection_object->produced_path) );
 
       /* End class 3 connection handling */
     } else { /* we have an IO connection */
       CipConnectionPathEpath connection_epath =
       { .class_id = class_id, .instance_id = instance_id,
         .attribute_id_or_connection_point = 0 };
-      memcpy(&(connection_object->configuration_path),
-             &connection_epath,
-             sizeof(connection_object->configuration_path) );
+      memcpy( &(connection_object->configuration_path),
+              &connection_epath,
+              sizeof(connection_object->configuration_path) );
       ConnectionObjectConnectionType originator_to_target_connection_type =
         ConnectionObjectGetOToTConnectionType(connection_object);
       ConnectionObjectConnectionType target_to_originator_connection_type =
@@ -1564,22 +1571,22 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
 
       for(size_t i = 0; i < number_of_encoded_paths; i++) /* process up to 2 encoded paths */
       {
-        if(kSegmentTypeLogicalSegment == GetPathSegmentType(message)
-           && (kLogicalSegmentLogicalTypeInstanceId ==
-               GetPathLogicalSegmentLogicalType(message)
-               || kLogicalSegmentLogicalTypeConnectionPoint ==
-               GetPathLogicalSegmentLogicalType(message) ) ) /* Connection Point interpreted as InstanceNr -> only in Assembly Objects */
+        if( kSegmentTypeLogicalSegment == GetPathSegmentType(message)
+            && ( kLogicalSegmentLogicalTypeInstanceId ==
+                 GetPathLogicalSegmentLogicalType(message)
+                 || kLogicalSegmentLogicalTypeConnectionPoint ==
+                 GetPathLogicalSegmentLogicalType(message) ) ) /* Connection Point interpreted as InstanceNr -> only in Assembly Objects */
         {   /* Attribute Id or Connection Point */
           CipDword attribute_id = CipEpathGetLogicalValue(&message);
           CipConnectionPathEpath path =
           { .class_id = class_id, .instance_id = attribute_id,
             .attribute_id_or_connection_point = 0 };
-          memcpy(paths_to_encode[i], &path,
-                 sizeof(connection_object->produced_path) );
+          memcpy( paths_to_encode[i], &path,
+                  sizeof(connection_object->produced_path) );
           OPENER_TRACE_INFO(
             "connection point %" PRIu32 "\n",
             attribute_id);
-          if(NULL == GetCipInstance(class, attribute_id) ) { /* Old code - Probably here the attribute ID marks the instance for the assembly object  */
+          if( NULL == GetCipInstance(class, attribute_id) ) { /* Old code - Probably here the attribute ID marks the instance for the assembly object  */
             *extended_error =
               kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
             return kCipErrorConnectionFailure;
@@ -1621,9 +1628,10 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
               GetPathNetworkSegmentSubtype(message);
             switch(subtype) {
               case kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds:
-                if(kConnectionObjectTransportClassTriggerProductionTriggerCyclic
-                   != ConnectionObjectGetTransportClassTriggerProductionTrigger(
-                     connection_object) ) {
+                if(
+                  kConnectionObjectTransportClassTriggerProductionTriggerCyclic
+                  != ConnectionObjectGetTransportClassTriggerProductionTrigger(
+                    connection_object) ) {
                   /* only non cyclic connections may have a production inhibit */
                   connection_object->production_inhibit_time = message[1];
                   message += 2;
@@ -1660,11 +1668,12 @@ EipUint8 ParseConnectionPath(CipConnectionObject *connection_object,
 
 void CloseConnection(CipConnectionObject *RESTRICT connection_object) {
 
-  OPENER_TRACE_INFO("cipconnectionmanager: CloseConnection, trigger: %d \n",
-  	ConnectionObjectGetTransportClassTriggerTransportClass(connection_object));
+  OPENER_TRACE_INFO( "cipconnectionmanager: CloseConnection, trigger: %d \n",
+                     ConnectionObjectGetTransportClassTriggerTransportClass(
+                       connection_object) );
 
-  if(kConnectionObjectTransportClassTriggerTransportClass3 !=
-     ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
+  if( kConnectionObjectTransportClassTriggerTransportClass3 !=
+      ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
   {
     /* only close the UDP connection for not class 3 connections */
     CloseUdpSocket(connection_object->socket[kUdpCommuncationDirectionConsuming]);
@@ -1704,8 +1713,8 @@ EipBool8 IsConnectedOutputAssembly(const EipUint32 instance_number) {
     CipConnectionObject *connection_object = (CipConnectionObject *) node->data;
     CipDword consumed_connection_point =
       connection_object->consumed_path.instance_id;
-    if(instance_number == consumed_connection_point &&
-       true == ConnectionObjectIsTypeIOConnection(connection_object) ) {
+    if( instance_number == consumed_connection_point &&
+        true == ConnectionObjectIsTypeIOConnection(connection_object) ) {
       is_connected = true;
       break;
     }
@@ -1775,18 +1784,17 @@ EipStatus TriggerConnections(unsigned int output_assembly,
 
 void CheckForTimedOutConnectionsAndCloseTCPConnections(
   const CipConnectionObject *const connection_object,
-  CloseSessionFunction CloseSessions)
-{
+  CloseSessionFunction CloseSessions) {
 
   DoublyLinkedListNode *search_node = connection_list.first;
   bool non_timed_out_connection_found = false;
   while(NULL != search_node) {
     CipConnectionObject *search_connection = search_node->data;
-    if(ConnectionObjectEqualOriginator(connection_object,
-                                       search_connection) &&
-       connection_object != search_connection
-       && kConnectionObjectStateTimedOut !=
-       ConnectionObjectGetState(search_connection) ) {
+    if( ConnectionObjectEqualOriginator(connection_object,
+                                        search_connection) &&
+        connection_object != search_connection
+        && kConnectionObjectStateTimedOut !=
+        ConnectionObjectGetState(search_connection) ) {
       non_timed_out_connection_found = true;
       break;
     }
@@ -1798,9 +1806,10 @@ void CheckForTimedOutConnectionsAndCloseTCPConnections(
 }
 
 void InitializeConnectionManagerData() {
-  memset(g_connection_management_list,
-         0,
-         g_kNumberOfConnectableObjects * sizeof(ConnectionManagementHandling) );
+  memset( g_connection_management_list,
+          0,
+          g_kNumberOfConnectableObjects *
+          sizeof(ConnectionManagementHandling) );
   InitializeClass3ConnectionData();
   InitializeIoConnectionData();
 }

+ 60 - 60
source/src/cip/cipconnectionobject.c

@@ -81,7 +81,7 @@ void CipConnectionObjectListArrayFree(DoublyLinkedListNode **node) {
 
   if(NULL != node) {
     if(NULL != *node) {
-      memset(*node, 0, sizeof(DoublyLinkedListNode) );
+      memset( *node, 0, sizeof(DoublyLinkedListNode) );
       *node = NULL;
     } else {
       OPENER_TRACE_ERR("Attempt to delete NULL pointer to node\n");
@@ -102,7 +102,7 @@ void ConnectionObjectSetInitialInactivityWatchdogTimerValue(
 
 void ConnectionObjectInitializeEmpty(
   CipConnectionObject *const connection_object) {
-  memset(connection_object, 0, sizeof(*connection_object) );
+  memset( connection_object, 0, sizeof(*connection_object) );
   ConnectionObjectSetState(connection_object,
                            kConnectionObjectStateNonExistent);
   connection_object->socket[0] = kEipInvalidSocket;
@@ -127,19 +127,19 @@ void ConnectionObjectInitializeFromMessage(const CipOctet **message,
   (void) timeout_ticks;
 
   /* O_to_T Conn ID */
-  ConnectionObjectSetCipConsumedConnectionID(connection_object,
-                                             GetUdintFromMessage(message) );
+  ConnectionObjectSetCipConsumedConnectionID( connection_object,
+                                              GetUdintFromMessage(message) );
   /* T_to_O Conn ID */
-  ConnectionObjectSetCipProducedConnectionID(connection_object,
+  ConnectionObjectSetCipProducedConnectionID( connection_object,
+                                              GetUdintFromMessage(message) );
+
+  ConnectionObjectSetConnectionSerialNumber( connection_object,
+                                             GetUintFromMessage(message) );
+  ConnectionObjectSetOriginatorVendorId( connection_object,
+                                         GetUintFromMessage(message) );
+  ConnectionObjectSetOriginatorSerialNumber( connection_object,
                                              GetUdintFromMessage(message) );
 
-  ConnectionObjectSetConnectionSerialNumber(connection_object,
-                                            GetUintFromMessage(message) );
-  ConnectionObjectSetOriginatorVendorId(connection_object,
-                                        GetUintFromMessage(message) );
-  ConnectionObjectSetOriginatorSerialNumber(connection_object,
-                                            GetUdintFromMessage(message) );
-
   ConnectionObjectSetConnectionNumber(connection_object);
 
   /* keep it to none existent till the setup is done this eases error handling and
@@ -150,8 +150,8 @@ void ConnectionObjectInitializeFromMessage(const CipOctet **message,
                            kConnectionObjectStateNonExistent);
   connection_object->sequence_count_producing = 0; /* set the sequence count to zero */
 
-  ConnectionObjectSetConnectionTimeoutMultiplier(connection_object,
-                                                 GetUsintFromMessage(message) );
+  ConnectionObjectSetConnectionTimeoutMultiplier( connection_object,
+                                                  GetUsintFromMessage(message) );
 
   (*message) += 3; /* 3 bytes reserved */
 
@@ -163,34 +163,34 @@ void ConnectionObjectInitializeFromMessage(const CipOctet **message,
     connection_object->cip_produced_connection_id,
     connection_object->connection_serial_number);
 
-  ConnectionObjectSetOToTRequestedPacketInterval(connection_object,
-                                                 GetUdintFromMessage(message) );
+  ConnectionObjectSetOToTRequestedPacketInterval( connection_object,
+                                                  GetUdintFromMessage(message) );
 
   ConnectionObjectSetInitialInactivityWatchdogTimerValue(connection_object);
 
   if(connection_object->is_large_forward_open == true) {
-    ConnectionObjectSetOToTNetworkConnectionParameters(connection_object,
-                                                       GetDwordFromMessage(
-                                                         message) );
+    ConnectionObjectSetOToTNetworkConnectionParameters( connection_object,
+                                                        GetDwordFromMessage(
+                                                          message) );
   } else {
-    ConnectionObjectSetOToTNetworkConnectionParameters(connection_object,
-                                                       GetWordFromMessage(
-                                                         message) );
+    ConnectionObjectSetOToTNetworkConnectionParameters( connection_object,
+                                                        GetWordFromMessage(
+                                                          message) );
   }
 
-  ConnectionObjectSetTToORequestedPacketInterval(connection_object,
-                                                 GetUdintFromMessage(message) );
+  ConnectionObjectSetTToORequestedPacketInterval( connection_object,
+                                                  GetUdintFromMessage(message) );
 
   ConnectionObjectSetExpectedPacketRate(connection_object);
 
   if(connection_object->is_large_forward_open == true) {
-    ConnectionObjectSetTToONetworkConnectionParameters(connection_object,
-                                                       GetDwordFromMessage(
-                                                         message) );
+    ConnectionObjectSetTToONetworkConnectionParameters( connection_object,
+                                                        GetDwordFromMessage(
+                                                          message) );
   } else {
-    ConnectionObjectSetTToONetworkConnectionParameters(connection_object,
-                                                       GetWordFromMessage(
-                                                         message) );
+    ConnectionObjectSetTToONetworkConnectionParameters( connection_object,
+                                                        GetWordFromMessage(
+                                                          message) );
   }
 
   connection_object->transport_class_trigger = GetByteFromMessage(message);
@@ -653,29 +653,29 @@ CipUdint ConnectionObjectGetConnectionlNumber(
   return connection_object->connection_number;
 }
 
-void ConnectionObjectSetConnectionNumber(
-  CipConnectionObject *connection_object) {
+void ConnectionObjectSetConnectionNumber(CipConnectionObject *connection_object)
+{
   connection_object->connection_number = GenerateRandomConnectionNumber();
 }
 
 CipUint GenerateRandomConnectionNumber(void) {
-	CipUint rand_num = (CipUint)rand(); //TODO: update to random.c functions
+  CipUint rand_num = (CipUint)rand();       //TODO: update to random.c functions
 
-	//search for existing connection_numbers
-	DoublyLinkedListNode *iterator = connection_list.first;
-	CipConnectionObject *search_connection_object = NULL;
+  //search for existing connection_numbers
+  DoublyLinkedListNode *iterator = connection_list.first;
+  CipConnectionObject *search_connection_object = NULL;
 
-	while (NULL != iterator) {
-		search_connection_object = iterator->data;
+  while (NULL != iterator) {
+    search_connection_object = iterator->data;
 
-		if ((search_connection_object->connection_number == rand_num)) {
+    if ( (search_connection_object->connection_number == rand_num) ) {
 
-			rand_num = GenerateRandomConnectionNumber();
-		}
-		iterator = iterator->next;
-	}
+      rand_num = GenerateRandomConnectionNumber();
+    }
+    iterator = iterator->next;
+  }
 
-	return rand_num;
+  return rand_num;
 }
 
 CipUsint ConnectionObjectGetConnectionTimeoutMultiplier(
@@ -731,9 +731,9 @@ void ConnectionObjectSetOToTNetworkConnectionParameters(
 bool ConnectionObjectIsRedundantOwner(const CipDword connection_parameters,
                                       const CipBool is_lfo) {
   if(is_lfo) {
-    return (connection_parameters & (1 << 31) );
+    return ( connection_parameters & (1 << 31) );
   } else {
-    return (connection_parameters & (1 << 15) );
+    return ( connection_parameters & (1 << 15) );
   }
 }
 
@@ -757,9 +757,9 @@ ConnectionObjectConnectionType ConnectionObjectGetConnectionType(
 
   CipUsint connection_type;
   if(is_lfo) {
-    connection_type = (connection_parameters & (3 << 29) ) >> 29;
+    connection_type = ( connection_parameters & (3 << 29) ) >> 29;
   } else {
-    connection_type = (connection_parameters & (3 << 13) ) >> 13;
+    connection_type = ( connection_parameters & (3 << 13) ) >> 13;
   }
 
   switch(connection_type) {
@@ -794,9 +794,9 @@ ConnectionObjectPriority ConnectionObjectGetPriority(
 
   CipUsint priority;
   if(is_lfo) {
-    priority = (connection_parameters & (3 << 26) ) >> 26;
+    priority = ( connection_parameters & (3 << 26) ) >> 26;
   } else {
-    priority = (connection_parameters & (3 << 10) ) >> 10;
+    priority = ( connection_parameters & (3 << 10) ) >> 10;
   }
 
   ConnectionObjectPriority result;
@@ -841,9 +841,9 @@ ConnectionObjectConnectionSizeType ConnectionObjectGetConnectionSizeType(
 
   bool connection_size_type;
   if(is_lfo) {
-    connection_size_type = (connection_parameters & (1 << 25) );
+    connection_size_type = ( connection_parameters & (1 << 25) );
   } else {
-    connection_size_type = (connection_parameters & (1 << 9) );
+    connection_size_type = ( connection_parameters & (1 << 9) );
   }
 
   if(connection_size_type) {
@@ -922,22 +922,22 @@ void ConnectionObjectGeneralConfiguration(
   connection_object->socket[0] = kEipInvalidSocket;
   connection_object->socket[1] = kEipInvalidSocket;
 
-  if(kConnectionObjectConnectionTypePointToPoint ==
-     ConnectionObjectGetOToTConnectionType(connection_object) ) {
+  if( kConnectionObjectConnectionTypePointToPoint ==
+      ConnectionObjectGetOToTConnectionType(connection_object) ) {
     /* if we have a point to point connection for the O to T direction
      * the target shall choose the connection ID.
      */
-    ConnectionObjectSetCipConsumedConnectionID(connection_object,
-                                               GetConnectionId() );
+    ConnectionObjectSetCipConsumedConnectionID( connection_object,
+                                                GetConnectionId() );
   }
 
-  if(kConnectionObjectConnectionTypeMulticast ==
-     ConnectionObjectGetTToOConnectionType(connection_object) ) {
+  if( kConnectionObjectConnectionTypeMulticast ==
+      ConnectionObjectGetTToOConnectionType(connection_object) ) {
     /* if we have a multi-cast connection for the T to O direction the
      * target shall choose the connection ID.
      */
-    ConnectionObjectSetCipProducedConnectionID(connection_object,
-                                               GetConnectionId() );
+    ConnectionObjectSetCipProducedConnectionID( connection_object,
+                                                GetConnectionId() );
   }
 
   ConnectionObjectResetSequenceCounts(connection_object);

+ 2 - 2
source/src/cip/cipconnectionobject.h

@@ -168,8 +168,8 @@ struct cip_connection_object {
                                                    different
                                                    value than SequenceCountProducing */
   CipBool eip_first_level_sequence_count_received; /**< False if eip_level_sequence_count_consuming
-                                                   hasn't been initialized with a sequence
-                                                   count yet, true otherwise */
+                                                      hasn't been initialized with a sequence
+                                                      count yet, true otherwise */
   CipInt correct_originator_to_target_size;
   CipInt correct_target_to_originator_size;
 

+ 5 - 5
source/src/cip/cipdlr.h

@@ -48,8 +48,8 @@ typedef enum {
  *  participant of the DLR protocol.
  */
 typedef struct {
-  CipUdint  device_ip;  /**< IP address of a participating DLR node */
-  CipUsint  device_mac[6]; /**< MAC address of a participating DLR node */
+  CipUdint device_ip;   /**< IP address of a participating DLR node */
+  CipUsint device_mac[6];  /**< MAC address of a participating DLR node */
 } CipNodeAddress;
 
 /** @brief Type declaration for the DLR object
@@ -59,10 +59,10 @@ typedef struct {
  *  ring participant.
  */
 typedef struct {
-  CipUsint  network_topology; /**< Attribute #1: */
-  CipUsint  network_status; /**< Attribute #2: */
+  CipUsint network_topology;  /**< Attribute #1: */
+  CipUsint network_status;  /**< Attribute #2: */
   CipNodeAddress active_supervisor_address; /**< Attribute #10: */
-  CipDword  capability_flags; /**< Attribute #12: */
+  CipDword capability_flags;  /**< Attribute #12: */
 } CipDlrObject;
 
 

+ 46 - 46
source/src/cip/cipepath.c

@@ -93,8 +93,8 @@ void SetPathSegmentType(SegmentType segment_type,
 bool GetPathPortSegmentExtendedLinkAddressSizeBit(
   const unsigned char *const cip_path) {
   const unsigned int kExtendedLinkAddressSizeMask = 0x10;
-  if(kExtendedLinkAddressSizeMask ==
-     (*cip_path & kExtendedLinkAddressSizeMask) ) {
+  if( kExtendedLinkAddressSizeMask ==
+      (*cip_path & kExtendedLinkAddressSizeMask) ) {
     return true;
   }
   return false;
@@ -105,7 +105,7 @@ unsigned int GetPathPortSegmentPortIdentifier(
   const unsigned int kPortIdentifierMask = 0x0F;
   unsigned int port_identifier = *cip_path & kPortIdentifierMask;
 
-  OPENER_ASSERT(kSegmentTypePortSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kSegmentTypePortSegment == GetPathSegmentType(cip_path) );
   /* Use of reserved port identifier 0 */
   OPENER_ASSERT(0 != port_identifier);
   return port_identifier;
@@ -124,8 +124,8 @@ unsigned int GetPathPortSegmentLinkAddressSize(
   const unsigned char *const cip_path) {
   /*  OPENER_ASSERT(false == GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path),
      "Call to non existent extended link address size\n"); */
-  OPENER_ASSERT(true ==
-                GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) );
+  OPENER_ASSERT( true ==
+                 GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) );
   return *(cip_path + 1);
 }
 
@@ -133,8 +133,8 @@ unsigned int GetPathPortSegmentExtendedPortNumber(
   const unsigned char *const cip_path) {
   /*  OPENER_ASSERT(kPortSegmentExtendedPort == GetPathPortSegmentPortIdentifier(cip_path),
      "There is no extended port available!\n");*/
-  OPENER_ASSERT(kPortSegmentExtendedPort ==
-                GetPathPortSegmentPortIdentifier(cip_path) );
+  OPENER_ASSERT( kPortSegmentExtendedPort ==
+                 GetPathPortSegmentPortIdentifier(cip_path) );
   const unsigned int kExtendedPortSegmentPosition =
     GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) == true ? 2 : 1;
   return cip_path[kExtendedPortSegmentPosition] +
@@ -158,7 +158,7 @@ void SetPathPortSegmentExtendedPortIdentifier(
 
 LogicalSegmentLogicalType GetPathLogicalSegmentLogicalType(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
   const unsigned int kLogicalTypeMask = 0x1C;
   const unsigned int logical_type = (*cip_path) & kLogicalTypeMask;
   LogicalSegmentLogicalType result = kLogicalSegmentLogicalTypeInvalid;
@@ -197,7 +197,7 @@ LogicalSegmentLogicalType GetPathLogicalSegmentLogicalType(
 
 void SetPathLogicalSegmentLogicalType(LogicalSegmentLogicalType logical_type,
                                       CipOctet *const cip_path) {
-  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
   switch(logical_type) {
     case kLogicalSegmentLogicalTypeClassId:
       (*cip_path) |= LOGICAL_SEGMENT_TYPE_CLASS_ID;
@@ -233,7 +233,7 @@ void SetPathLogicalSegmentLogicalType(LogicalSegmentLogicalType logical_type,
 
 LogicalSegmentLogicalFormat GetPathLogicalSegmentLogicalFormat(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
   const unsigned int kLogicalFormatMask = 0x03;
   const unsigned int logical_format = (*cip_path) & kLogicalFormatMask;
   LogicalSegmentLogicalFormat result = kLogicalSegmentLogicalFormatInvalid;
@@ -257,8 +257,8 @@ LogicalSegmentLogicalFormat GetPathLogicalSegmentLogicalFormat(
 
 void SetPathLogicalSegmentLogicalFormat(LogicalSegmentLogicalFormat format,
                                         CipOctet *const cip_path) {
-  OPENER_ASSERT(kSegmentTypeLogicalSegment ==
-                GetPathSegmentType( (const CipOctet * )cip_path ) );
+  OPENER_ASSERT( kSegmentTypeLogicalSegment ==
+                 GetPathSegmentType( (const CipOctet * )cip_path ) );
   switch(format) {
     case kLogicalSegmentLogicalFormatEightBit:
       (*cip_path) |= LOGICAL_SEGMENT_FORMAT_EIGHT_BIT;
@@ -327,8 +327,8 @@ LogicalSegmentExtendedLogicalType GetPathLogicalSegmentExtendedLogicalType(
   const unsigned char *const cip_path) {
   /*  OPENER_ASSERT(LOGICAL_SEGMENT_TYPE_EXTENDED_kLogicalSegmentLogicalTypeExtendedLogicalMessageValue == GetPathLogicalSegmentLogicalType(cip_path),
      "Trying to extract non-existent extended logical type") */
-  OPENER_ASSERT(kLogicalSegmentLogicalTypeExtendedLogical == GetPathLogicalSegmentLogicalType(
-                  cip_path) );
+  OPENER_ASSERT( kLogicalSegmentLogicalTypeExtendedLogical == GetPathLogicalSegmentLogicalType(
+                   cip_path) );
   const unsigned int extended_logical_type = *(cip_path + 1);
   LogicalSegmentExtendedLogicalType result =
     kLogicalSegmentExtendedLogicalTypeInvalid;
@@ -365,9 +365,9 @@ LogicalSegmentSpecialTypeLogicalFormat
 GetPathLogicalSegmentSpecialTypeLogicalType(const unsigned char *const cip_path)
 {
   /*  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path), "Not a logical segment!\n") */
-  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT(kLogicalSegmentLogicalTypeSpecial == GetPathLogicalSegmentLogicalType(
-                  cip_path) );
+  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kLogicalSegmentLogicalTypeSpecial == GetPathLogicalSegmentLogicalType(
+                   cip_path) );
   const unsigned int kLogicalFormatMask = 0x03;
   const unsigned int logical_format = (*cip_path) & kLogicalFormatMask;
 
@@ -388,10 +388,10 @@ ElectronicKeySegmentFormat GetPathLogicalSegmentElectronicKeyFormat(
   const unsigned char *const cip_path) {
   /*  OPENER_ASSERT(kLogicalSegmentSpecialTypeLogicalFormatElectronicKey ==
      GetPathLogicalSegmentSpecialTypeLogicalType(cip_path), "Not an electronic key!\n") */
-  OPENER_ASSERT(kLogicalSegmentSpecialTypeLogicalFormatElectronicKey == GetPathLogicalSegmentSpecialTypeLogicalType(
-                  cip_path) );
+  OPENER_ASSERT( kLogicalSegmentSpecialTypeLogicalFormatElectronicKey == GetPathLogicalSegmentSpecialTypeLogicalType(
+                   cip_path) );
   ElectronicKeySegmentFormat result = kElectronicKeySegmentFormatReserved;
-  switch(*(cip_path + 1) ) {
+  switch( *(cip_path + 1) ) {
     case ELECTRONIC_KEY_SEGMENT_KEY_FORMAT_4:
       result = kElectronicKeySegmentFormatKeyFormat4;
       break;
@@ -404,16 +404,16 @@ ElectronicKeySegmentFormat GetPathLogicalSegmentElectronicKeyFormat(
 
 void GetElectronicKeyFormat4FromMessage(const CipOctet **const message,
                                         ElectronicKeyFormat4 *key) {
-  OPENER_ASSERT(kElectronicKeySegmentFormatKeyFormat4 == GetPathLogicalSegmentElectronicKeyFormat(
-                  *message) );
+  OPENER_ASSERT( kElectronicKeySegmentFormatKeyFormat4 == GetPathLogicalSegmentElectronicKeyFormat(
+                   *message) );
 
   (*message) += 2;
-  ElectronicKeyFormat4SetVendorId(key, GetUintFromMessage(message) );
-  ElectronicKeyFormat4SetDeviceType(key, GetUintFromMessage(message) );
-  ElectronicKeyFormat4SetProductCode(key, GetUintFromMessage(message) );
-  ElectronicKeyFormat4SetMajorRevisionCompatibility(key,
-                                                    GetByteFromMessage(message) );
-  ElectronicKeyFormat4SetMinorRevision(key, GetUsintFromMessage(message) );
+  ElectronicKeyFormat4SetVendorId( key, GetUintFromMessage(message) );
+  ElectronicKeyFormat4SetDeviceType( key, GetUintFromMessage(message) );
+  ElectronicKeyFormat4SetProductCode( key, GetUintFromMessage(message) );
+  ElectronicKeyFormat4SetMajorRevisionCompatibility( key,
+                                                     GetByteFromMessage(message) );
+  ElectronicKeyFormat4SetMinorRevision( key, GetUsintFromMessage(message) );
 }
 
 /*** Logical Segment ***/
@@ -427,7 +427,7 @@ void GetElectronicKeyFormat4FromMessage(const CipOctet **const message,
  */
 NetworkSegmentSubtype GetPathNetworkSegmentSubtype(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
   const unsigned int kSubtypeMask = 0x1F;
   const unsigned int subtype = (*cip_path) & kSubtypeMask;
   NetworkSegmentSubtype result = kNetworkSegmentSubtypeReserved;
@@ -469,9 +469,9 @@ CipUsint GetPathNetworkSegmentProductionInhibitTimeInMilliseconds(
   /*  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path),"Not a network segment!\n")
      OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(cip_path),
      "Not a Production Inhibit Time milliseconds segment!\n") */
-  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(
-                  cip_path) );
+  OPENER_ASSERT( kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(
+                   cip_path) );
   return *(cip_path + 1);
 }
 
@@ -488,10 +488,10 @@ CipUdint GetPathNetworkSegmentProductionInhibitTimeInMicroseconds(
      "Not a Production Inhibit Time microseconds segment!\n")
      OPENER_ASSERT(2 == *(cip_path + 1), "Data Words length is incorrect! See CIP Spec Vol.1 C-1.4.3.3.2\n") */
 
-  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds == GetPathNetworkSegmentSubtype(
-                  cip_path) );
-  OPENER_ASSERT(2 == *(cip_path + 1) );
+  OPENER_ASSERT( kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds == GetPathNetworkSegmentSubtype(
+                   cip_path) );
+  OPENER_ASSERT( 2 == *(cip_path + 1) );
 
   const unsigned char *message_runner = cip_path + 2;
   return GetUdintFromMessage(&message_runner);
@@ -504,8 +504,8 @@ CipUdint GetPathNetworkSegmentProductionInhibitTimeInMicroseconds(
 SymbolicSegmentFormat GetPathSymbolicSegmentFormat(
   const unsigned char *const cip_path) {
   const unsigned int kSymbolicSegmentFormatMask = 0x1F;
-  if(SYMBOLIC_SEGMENT_FORMAT_EXTENDED_STRING ==
-     (*cip_path & kSymbolicSegmentFormatMask) ) {
+  if( SYMBOLIC_SEGMENT_FORMAT_EXTENDED_STRING ==
+      (*cip_path & kSymbolicSegmentFormatMask) ) {
     return kSymbolicSegmentFormatExtendedString;
   }
   return kSymbolicSegmentFormatASCII;
@@ -544,9 +544,9 @@ SymbolicSegmentExtendedFormat GetPathSymbolicSegmentNumericType(
 
 SymbolicSegmentExtendedFormat GetPathSymbolicSegmentExtendedFormat(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT(kSegmentTypeSymbolicSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT(kSymbolicSegmentFormatExtendedString == GetPathSymbolicSegmentFormat(
-                  cip_path) );
+  OPENER_ASSERT( kSegmentTypeSymbolicSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kSymbolicSegmentFormatExtendedString == GetPathSymbolicSegmentFormat(
+                   cip_path) );
   const unsigned int kSymbolicSegmentExtendedFormatMask = 0xE0;
   const unsigned int extended_type = *(cip_path + 1) &
                                      kSymbolicSegmentExtendedFormatMask;
@@ -572,8 +572,8 @@ SymbolicSegmentExtendedFormat GetPathSymbolicSegmentExtendedFormat(
 
 /*** Data Segment ***/
 
-DataSegmentSubtype GetPathDataSegmentSubtype(const unsigned char *const cip_path)
-{
+DataSegmentSubtype GetPathDataSegmentSubtype(
+  const unsigned char *const cip_path) {
   const unsigned int kDataSegmentSubtypeMask = 0x1F;
   const unsigned int data_subtype = (*cip_path) & kDataSegmentSubtypeMask;
 
@@ -601,9 +601,9 @@ CipUsint GetPathDataSegmentSimpleDataWordLength(
   const unsigned char *const cip_path) {
   /*  OPENER_ASSERT(kSegmentTypeDataSegment == GetPathSegmentType(cip_path),"Not a data segment!\n");
      OPENER_ASSERT(kDataSegmentSubtypeSimpleData == GetPathDataSegmentSubtype(cip_path), "Not a simple data segment!\n") */
-  OPENER_ASSERT(kSegmentTypeDataSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT(kDataSegmentSubtypeSimpleData ==
-                GetPathDataSegmentSubtype(cip_path) );
+  OPENER_ASSERT( kSegmentTypeDataSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT( kDataSegmentSubtypeSimpleData ==
+                 GetPathDataSegmentSubtype(cip_path) );
 
   const unsigned char *message_runner = cip_path + 1;
   return GetUsintFromMessage(&message_runner);

+ 52 - 52
source/src/cip/cipethernetlink.c

@@ -40,7 +40,7 @@
  *        This service should only implemented for the attributes 4, 5, 12,
  *        13 and 15.
  *  - SetAttributeSingle (0 != OPENER_ETHLINK_IFACE_CTRL_ENABLE)
- *  		This service should only be implemented if attribute 6 is enabled.
+ *              This service should only be implemented if attribute 6 is enabled.
  *
  */
 
@@ -122,9 +122,9 @@ EipStatus GetAndClearEthernetLink(
  *          -1 .. error
  */
 int DecodeCipEthernetLinkInterfaceControl(
-		CipEthernetLinkInterfaceControl *const data,
-		const CipMessageRouterRequest *const message_router_request,
-		CipMessageRouterResponse *const message_router_response);
+  CipEthernetLinkInterfaceControl *const data,
+  const CipMessageRouterRequest *const message_router_request,
+  CipMessageRouterResponse *const message_router_response);
 #endif
 
 
@@ -270,8 +270,8 @@ EipStatus CipEthernetLinkInit(void) {
 #if defined(OPENER_ETHLINK_IFACE_CTRL_ENABLE) && \
     0 != OPENER_ETHLINK_IFACE_CTRL_ENABLE
     InsertService(ethernet_link_class, kSetAttributeSingle,
-    				&SetAttributeSingle,
-                      "SetAttributeSingle");
+                  &SetAttributeSingle,
+                  "SetAttributeSingle");
 #endif
 
     /* bind attributes to the instance */
@@ -473,7 +473,7 @@ static void EncodeCipEthernetLinkInterfaceControl(const void *const data,
   EncodeCipUint(&interface_control->forced_interface_speed, outgoing_message);
 }
 
-#define NELEMENTS(x)  ( (sizeof(x) / sizeof(x[0]) ) )
+#define NELEMENTS(x)  ( ( sizeof(x) / sizeof(x[0]) ) )
 static void EncodeCipEthernetLinkInterfaceCaps(const void *const data,
                                                ENIPMessage *const outgoing_message)
 {
@@ -488,8 +488,8 @@ static void EncodeCipEthernetLinkInterfaceCaps(const void *const data,
   EncodeCipUsint(&count, outgoing_message);
 
   for (size_t i = 0; i < NELEMENTS(speed_duplex_table); i++) {
-    if (interface_caps->speed_duplex_selector &
-        (1U << i) ) {
+    if ( interface_caps->speed_duplex_selector &
+         (1U << i) ) {
       EncodeCipUint(&speed_duplex_table[i].interface_speed, outgoing_message);
       EncodeCipUsint(&speed_duplex_table[i].interface_duplex_mode,
                      outgoing_message);
@@ -557,8 +557,8 @@ static bool IsIfaceControlAllowed(CipUdint instance_id,
   const CipUsint duplex_mode =
     (iface_cntrl->control_bits & kEthLinkIfCntrlForceDuplexFD) ? 1 : 0;
   for (size_t i = 0; i < NELEMENTS(speed_duplex_table); i++) {
-    if (g_ethernet_link[instance_id - 1].interface_caps.speed_duplex_selector &
-        (1U << i) ) {
+    if ( g_ethernet_link[instance_id - 1].interface_caps.speed_duplex_selector &
+         (1U << i) ) {
       if (duplex_mode == speed_duplex_table[i].interface_duplex_mode &&
           iface_cntrl->forced_interface_speed ==
           speed_duplex_table[i].interface_speed) {
@@ -574,47 +574,47 @@ int DecodeCipEthernetLinkInterfaceControl(
 		CipMessageRouterRequest *const message_router_request,
 		CipMessageRouterResponse *const message_router_response) {
 
-	CipInstance *const instance = GetCipInstance(
-				GetCipClass(message_router_request->request_path.class_id),
-				message_router_request->request_path.instance_number);
-
-	int number_of_decoded_bytes = -1;
-
-	CipEthernetLinkInterfaceControl if_cntrl;
-
-	DecodeCipWord(&if_cntrl.control_bits, message_router_request,
-			message_router_response);
-	DecodeCipUint(&if_cntrl.forced_interface_speed, message_router_request,
-			message_router_response);
-
-	if (if_cntrl.control_bits > kEthLinkIfCntrlMaxValid) {
-		message_router_response->general_status =
-				kCipErrorInvalidAttributeValue;
-		return number_of_decoded_bytes;
-
-	} else {
-		if ((0 != (if_cntrl.control_bits & kEthLinkIfCntrlAutonegotiate))
-				&& ((0 != (if_cntrl.control_bits & kEthLinkIfCntrlForceDuplexFD))
-						|| (0 != if_cntrl.forced_interface_speed))) {
-			message_router_response->general_status =
-					kCipErrorObjectStateConflict;
-			return number_of_decoded_bytes;
-		} else {
-			if (0 == (if_cntrl.control_bits & kEthLinkIfCntrlAutonegotiate)) {
-				/* Need to check if a supported mode is forced. */
-				if (!IsIfaceControlAllowed(instance->instance_number,
-						&if_cntrl)) {
-					message_router_response->general_status =
-							kCipErrorInvalidAttributeValue;
-					return number_of_decoded_bytes;
-				}
-			}
-			*data = if_cntrl; //write data to attribute
-			message_router_response->general_status = kCipErrorSuccess;
-			number_of_decoded_bytes = 4;
-		}
-	}
-	return number_of_decoded_bytes;
+  CipInstance *const instance = GetCipInstance(
+    GetCipClass(message_router_request->request_path.class_id),
+    message_router_request->request_path.instance_number);
+
+  int number_of_decoded_bytes = -1;
+
+  CipEthernetLinkInterfaceControl if_cntrl;
+
+  DecodeCipWord(&if_cntrl.control_bits, message_router_request,
+                message_router_response);
+  DecodeCipUint(&if_cntrl.forced_interface_speed, message_router_request,
+                message_router_response);
+
+  if (if_cntrl.control_bits > kEthLinkIfCntrlMaxValid) {
+    message_router_response->general_status =
+      kCipErrorInvalidAttributeValue;
+    return number_of_decoded_bytes;
+
+  } else {
+    if ( ( 0 != (if_cntrl.control_bits & kEthLinkIfCntrlAutonegotiate) )
+         && ( ( 0 != (if_cntrl.control_bits & kEthLinkIfCntrlForceDuplexFD) )
+              || (0 != if_cntrl.forced_interface_speed) ) ) {
+      message_router_response->general_status =
+        kCipErrorObjectStateConflict;
+      return number_of_decoded_bytes;
+    } else {
+      if ( 0 == (if_cntrl.control_bits & kEthLinkIfCntrlAutonegotiate) ) {
+        /* Need to check if a supported mode is forced. */
+        if ( !IsIfaceControlAllowed(instance->instance_number,
+                                    &if_cntrl) ) {
+          message_router_response->general_status =
+            kCipErrorInvalidAttributeValue;
+          return number_of_decoded_bytes;
+        }
+      }
+      *data = if_cntrl;                   //write data to attribute
+      message_router_response->general_status = kCipErrorSuccess;
+      number_of_decoded_bytes = 4;
+    }
+  }
+  return number_of_decoded_bytes;
 }
 
  #endif

+ 15 - 12
source/src/cip/cipidentity.c

@@ -52,10 +52,11 @@ CipIdentityObject g_identity = { .vendor_id = OPENER_DEVICE_VENDOR_ID, /* Attrib
                                  .ext_status = kSelftestingUnknown, /* Attribute 5: Extended Device Status field */
                                  .serial_number = 0, /* Attribute 6: Serial Number */
                                  /* Attribute 7: Product Name, set by CipIdentityInit() */
-                                 };
+};
 
 /* The Doxygen comment is with the function's prototype in opener_api.h. */
-void SetDeviceRevision(EipUint8 major, EipUint8 minor) {
+void SetDeviceRevision(EipUint8 major,
+                       EipUint8 minor) {
   g_identity.revision.major_revision = major;
   g_identity.revision.minor_revision = minor;
 }
@@ -93,8 +94,9 @@ CipUint GetDeviceVendorId(void) {
 
 /* The Doxygen comment is with the function's prototype in opener_api.h. */
 void SetDeviceProductName(const char *product_name) {
-  if (!product_name)
+  if (!product_name) {
     return;
+  }
 
   SetCipShortStringByCstr(&g_identity.product_name, product_name);
 }
@@ -110,8 +112,8 @@ static inline void MergeStatusAndExtStatus(void) {
 
   /* Any major fault will override the current extended status with kMajorFault.
      See comment on Major Fault at Vol. 1, Table 5A-2.4. */
-  if(0 !=
-     (status_flags & (kMajorRecoverableFault | kMajorUnrecoverableFault) ) ) {
+  if( 0 !=
+      ( status_flags & (kMajorRecoverableFault | kMajorUnrecoverableFault) ) ) {
     ext_status = kMajorFault;
   }
   g_identity.status = status_flags | ext_status;
@@ -139,7 +141,7 @@ void CipIdentitySetStatusFlags(const CipWord status_flags) {
  *  value.
  */
 void CipIdentityClearStatusFlags(const CipWord status_flags) {
-  g_identity.status &= ~(status_flags & (~kExtStatusMask) );
+  g_identity.status &= ~( status_flags & (~kExtStatusMask) );
   MergeStatusAndExtStatus();
 }
 
@@ -182,19 +184,19 @@ EipStatus IdentityObjectPreResetCallback(
     }
     switch(reset_type) {
       case 0: /* Reset type 0 -> Emulate power cycle */
-        if(kEipStatusError == ResetDevice() ) {
+        if( kEipStatusError == ResetDevice() ) {
           message_router_response->general_status = kCipErrorInvalidParameter;
         }
         break;
 
       case 1: /* Reset type 1 -> Return to factory defaults & power cycle*/
-        if(kEipStatusError == ResetDeviceToInitialConfiguration() ) {
+        if( kEipStatusError == ResetDeviceToInitialConfiguration() ) {
           message_router_response->general_status = kCipErrorInvalidParameter;
         }
         break;
 
-        /* case 2: Not supported Reset type 2 ->
-           Return to factory defaults except communications parameters & power cycle*/
+      /* case 2: Not supported Reset type 2 ->
+         Return to factory defaults except communications parameters & power cycle*/
 
       default:
         message_router_response->general_status = kCipErrorInvalidParameter;
@@ -202,7 +204,7 @@ EipStatus IdentityObjectPreResetCallback(
     }
   }
   return eip_status;
-  }
+}
 
 void InitializeCipIdentity(CipClass *class) {
 
@@ -263,8 +265,9 @@ EipStatus CipIdentityInit() {
     return kEipStatusError;
   }
 
-  if (g_identity.product_name.length == 0)
+  if (g_identity.product_name.length == 0) {
     SetDeviceProductName(OPENER_DEVICE_NAME);
+  }
 
   CipInstance *instance = GetCipInstance(class, 1);
   InsertAttribute(instance, 1, kCipUint, EncodeCipUint,

+ 2 - 1
source/src/cip/cipioconnection.c

@@ -91,7 +91,8 @@ void CipRunIdleHeaderSetT2O(bool onoff) {
   s_produce_run_idle = onoff;
 }
 
-bool CipRunIdleHeaderGetT2O(void) {
+bool CipRunIdleHeaderGetT2O(void)
+{
   return s_produce_run_idle;
 }
 

+ 5 - 5
source/src/cip/cipmessagerouter.c

@@ -163,7 +163,7 @@ EipStatus RegisterCipClass(CipClass *cip_class) {
 
   }
   *message_router_object =
-    (CipMessageRouterObject *) CipCalloc(1, sizeof(CipMessageRouterObject) );                      /* create a new node at the end of the list*/
+    (CipMessageRouterObject *) CipCalloc( 1, sizeof(CipMessageRouterObject) );                      /* create a new node at the end of the list*/
   if(*message_router_object == 0) {
     return kEipStatusError; /* check for memory error*/
 
@@ -183,10 +183,10 @@ EipStatus NotifyMessageRouter(EipUint8 *data,
   CipError status = kCipErrorSuccess;
 
   OPENER_TRACE_INFO("NotifyMessageRouter: routing unconnected message\n");
-  if(kCipErrorSuccess !=
-     (status =
-        CreateMessageRouterRequestStructure(data, data_length,
-                                            &g_message_router_request) ) ) {                                             /* error from create MR structure*/
+  if( kCipErrorSuccess !=
+      ( status =
+          CreateMessageRouterRequestStructure(data, data_length,
+                                              &g_message_router_request) ) ) {                                           /* error from create MR structure*/
     OPENER_TRACE_ERR(
       "NotifyMessageRouter: error from createMRRequeststructure\n");
     message_router_response->general_status = status;

+ 19 - 19
source/src/cip/cipqos.c

@@ -58,7 +58,7 @@ static CipQosDscpValues s_active_dscp = {
 
 
 /**@brief Retrieve the given data according to CIP encoding from the
- * 		message buffer.
+ *              message buffer.
  *
  *  Implementation of the decode function for the SetAttributeSingle CIP service for QoS
  *  Objects.
@@ -72,31 +72,31 @@ int DecodeCipQoSAttribute(CipUsint *const data,
 		CipMessageRouterRequest *const message_router_request,
 		CipMessageRouterResponse *const message_router_response) {
 
-	const EipUint8 **const cip_message = message_router_request->data;
+  const EipUint8 **const cip_message = message_router_request->data;
 
-	int number_of_decoded_bytes = -1;
+  int number_of_decoded_bytes = -1;
 
-	if (NULL != cip_message) {
+  if (NULL != cip_message) {
 
-		CipUsint attribute_value_received = GetUsintFromMessage(&cip_message);
-		if (attribute_value_received < 64U) {
+    CipUsint attribute_value_received = GetUsintFromMessage(&cip_message);
+    if (attribute_value_received < 64U) {
 
-			*data = attribute_value_received; //write value to attribute
+      *data = attribute_value_received;                   //write value to attribute
 
-			message_router_response->general_status = kCipErrorSuccess;
-			number_of_decoded_bytes = 1;
+      message_router_response->general_status = kCipErrorSuccess;
+      number_of_decoded_bytes = 1;
 
-		} else {
-			message_router_response->general_status =
-					kCipErrorInvalidAttributeValue;
-		}
-	} else {
+    } else {
+      message_router_response->general_status =
+        kCipErrorInvalidAttributeValue;
+    }
+  } else {
 
-		message_router_response->general_status = kCipErrorNotEnoughData;
-		OPENER_TRACE_INFO("CIP QoS not enough data\n");
-	}
+    message_router_response->general_status = kCipErrorNotEnoughData;
+    OPENER_TRACE_INFO("CIP QoS not enough data\n");
+  }
 
-	return number_of_decoded_bytes;
+  return number_of_decoded_bytes;
 
 }
 
@@ -206,7 +206,7 @@ EipStatus CipQoSInit() {
   InsertService(qos_class, kGetAttributeSingle, &GetAttributeSingle,
                 "GetAttributeSingle");
   InsertService(qos_class, kSetAttributeSingle, &SetAttributeSingle,
-                  "SetAttributeSingle");
+                "SetAttributeSingle");
 
   return kEipStatusOk;
 }

+ 14 - 11
source/src/cip/cipstring.c

@@ -61,16 +61,16 @@ CipStringN *SetCipStringNByData(CipStringN *const cip_string,
     /* No trailing '\0' character! */
     cip_string->length = str_len;
     cip_string->size = size;
-    cip_string->string = CipCalloc(cip_string->length,
-                                   cip_string->size * sizeof(CipOctet) );
+    cip_string->string = CipCalloc( cip_string->length,
+                                    cip_string->size * sizeof(CipOctet) );
     if(NULL == cip_string->string) {
       result = NULL;
       cip_string->length = 0;
       cip_string->size = 0;
     } else {
-      memcpy(cip_string->string,
-             data,
-             cip_string->length * cip_string->size * sizeof(CipOctet) );
+      memcpy( cip_string->string,
+              data,
+              cip_string->length * cip_string->size * sizeof(CipOctet) );
     }
   }
   return result;
@@ -128,12 +128,12 @@ CipString2 *SetCipString2ByData(CipString2 *const cip_string,
 
   if(0 != str_len) {
     /* No trailing '\0' character! */
-    cip_string->string = CipCalloc(str_len, 2 * sizeof(CipOctet) );
+    cip_string->string = CipCalloc( str_len, 2 * sizeof(CipOctet) );
     if(NULL == cip_string->string) {
       result = NULL;
     } else {
       cip_string->length = str_len;
-      memcpy(cip_string->string, data, str_len * 2 * sizeof(CipOctet) );
+      memcpy( cip_string->string, data, str_len * 2 * sizeof(CipOctet) );
     }
   }
   return result;
@@ -176,7 +176,7 @@ CipString *SetCipStringByData(CipString *const cip_string,
 
   if(0 != str_len) {
     /* No trailing '\0' character. */
-    cip_string->string = CipCalloc(str_len, sizeof(CipOctet) );
+    cip_string->string = CipCalloc( str_len, sizeof(CipOctet) );
     if(NULL == cip_string->string) {
       result = NULL;
     } else {
@@ -239,7 +239,7 @@ CipShortString *SetCipShortStringByData(CipShortString *const cip_string,
 
   if(0 != str_len) {
     /* No trailing '\0' character. */
-    cip_string->string = CipCalloc(str_len, sizeof(CipOctet) );
+    cip_string->string = CipCalloc( str_len, sizeof(CipOctet) );
     if(NULL == cip_string->string) {
       result = NULL;
     } else {
@@ -265,12 +265,15 @@ CipShortString *SetCipShortStringByCstr(CipShortString *const cip_string,
 }
 
 /* Ensures buf is NUL terminated, provided initial validation is successful */
-int GetCstrFromCipShortString(CipShortString *const string, char *buf, size_t len) {
+int GetCstrFromCipShortString(CipShortString *const string,
+                              char *buf,
+                              size_t len) {
   size_t num;
   int rc = 0;
 
-  if (!string || !buf || len < 1)
+  if (!string || !buf || len < 1) {
     return -1;
+  }
 
   num = (size_t)string->length;
   if (len <= num) {

+ 3 - 2
source/src/cip/cipstring.h

@@ -177,7 +177,8 @@ CipShortString *SetCipShortStringByCstr(CipShortString *const cip_string,
  *
  * @return POSIX OK(0) if the complete string fit in @param buf, otherwise non-zero.
  */
-int GetCstrFromCipShortString(CipShortString *const string, char *buf,
-			      size_t len);
+int GetCstrFromCipShortString(CipShortString *const string,
+                              char *buf,
+                              size_t len);
 
 #endif /* of OPENER_CIPSTRING_H_ */

+ 39 - 39
source/src/cip/cipstringi.c

@@ -76,13 +76,13 @@ bool CipStringIsAnyStringEmpty(const CipStringI *const string) {
 void *CipStringICreateStringStructure(CipStringIStruct *const to) {
   switch(to->char_string_struct) {
     case kCipShortString:
-      return to->string = CipCalloc(1, sizeof(CipShortString) );
+      return to->string = CipCalloc( 1, sizeof(CipShortString) );
     case kCipString:
-      return to->string = CipCalloc(1, sizeof(CipString) );
+      return to->string = CipCalloc( 1, sizeof(CipString) );
     case kCipString2:
-      return to->string = CipCalloc(1, sizeof(CipString2) );
+      return to->string = CipCalloc( 1, sizeof(CipString2) );
     case kCipStringN:
-      return to->string = CipCalloc(1, sizeof(CipStringN) );
+      return to->string = CipCalloc( 1, sizeof(CipStringN) );
     default:
       OPENER_TRACE_ERR("CIP File: No valid String type received!\n");
   }
@@ -96,7 +96,7 @@ void CipStringIDeepCopyInternalString(CipStringIStruct *const to,
       CipShortString *toString = (CipShortString *) to->string;
       CipShortString *fromString = (CipShortString *) from->string;
       toString->length = fromString->length;
-      toString->string = CipCalloc(toString->length, sizeof(CipOctet) );
+      toString->string = CipCalloc( toString->length, sizeof(CipOctet) );
       memcpy(toString->string,
              fromString->string,
              sizeof(CipOctet) * toString->length);
@@ -106,7 +106,7 @@ void CipStringIDeepCopyInternalString(CipStringIStruct *const to,
       CipString *toString = (CipString *) to->string;
       CipString *fromString = (CipString *) from->string;
       toString->length = fromString->length;
-      toString->string = CipCalloc(toString->length, sizeof(CipOctet) );
+      toString->string = CipCalloc( toString->length, sizeof(CipOctet) );
       memcpy(toString->string,
              fromString->string,
              sizeof(CipOctet) * toString->length);
@@ -116,7 +116,7 @@ void CipStringIDeepCopyInternalString(CipStringIStruct *const to,
       CipString2 *toString = (CipString2 *) to->string;
       CipString2 *fromString = (CipString2 *) from->string;
       toString->length = fromString->length;
-      toString->string = CipCalloc(toString->length, 2 * sizeof(CipOctet) );
+      toString->string = CipCalloc( toString->length, 2 * sizeof(CipOctet) );
       memcpy(toString->string,
              fromString->string,
              2 * sizeof(CipOctet) * toString->length);
@@ -128,7 +128,7 @@ void CipStringIDeepCopyInternalString(CipStringIStruct *const to,
       toString->length = fromString->length;
       toString->size = fromString->size;
       toString->string =
-        CipCalloc(toString->length, toString->size * sizeof(CipOctet) );
+        CipCalloc( toString->length, toString->size * sizeof(CipOctet) );
       memcpy(toString->string, fromString->string,
              toString->size * sizeof(CipOctet) * toString->length);
     }
@@ -142,7 +142,7 @@ void CipStringICopy(CipStringI *const to,
                     const CipStringI *const from) {
   to->number_of_strings = from->number_of_strings;
   to->array_of_string_i_structs =
-    CipCalloc(to->number_of_strings, sizeof(CipStringIStruct) );
+    CipCalloc( to->number_of_strings, sizeof(CipStringIStruct) );
   for(size_t i = 0; i < to->number_of_strings; ++i) {
     CipStringIStruct *const toStruct = to->array_of_string_i_structs + i;
     CipStringIStruct *const fromStruct = from->array_of_string_i_structs + i;
@@ -183,9 +183,9 @@ void CipStringIDecodeFromMessage(CipStringI *data_to,
 
     switch (target_stringI->array_of_string_i_structs[i].char_string_struct) {
       case kCipShortString: {
-        target_stringI->array_of_string_i_structs[i].string = CipCalloc(1,
-                                                                        sizeof(
-                                                                          CipShortString) );
+        target_stringI->array_of_string_i_structs[i].string = CipCalloc( 1,
+                                                                         sizeof(
+                                                                           CipShortString) );
         CipShortString *short_string =
           (CipShortString *) (target_stringI->array_of_string_i_structs[i].
                               string);
@@ -198,9 +198,9 @@ void CipStringIDecodeFromMessage(CipStringI *data_to,
       }
       break;
       case kCipString: {
-        target_stringI->array_of_string_i_structs[i].string = CipCalloc(1,
-                                                                        sizeof(
-                                                                          CipString) );
+        target_stringI->array_of_string_i_structs[i].string = CipCalloc( 1,
+                                                                         sizeof(
+                                                                           CipString) );
         CipString *const string =
           (CipString *const ) target_stringI->array_of_string_i_structs[i].
           string;
@@ -210,9 +210,9 @@ void CipStringIDecodeFromMessage(CipStringI *data_to,
       }
       break;
       case kCipString2: {
-        target_stringI->array_of_string_i_structs[i].string = CipCalloc(1,
-                                                                        sizeof(
-                                                                          CipString2) );
+        target_stringI->array_of_string_i_structs[i].string = CipCalloc( 1,
+                                                                         sizeof(
+                                                                           CipString2) );
         CipString2 *const string =
           (CipString2 *const ) target_stringI->array_of_string_i_structs[i].
           string;
@@ -225,9 +225,9 @@ void CipStringIDecodeFromMessage(CipStringI *data_to,
         CipUint size = GetUintFromMessage(&message_router_request->data);
         CipUint length = GetUintFromMessage(&message_router_request->data);
 
-        target_stringI->array_of_string_i_structs[i].string = CipCalloc(1,
-                                                                        sizeof(
-                                                                          CipStringN) );
+        target_stringI->array_of_string_i_structs[i].string = CipCalloc( 1,
+                                                                         sizeof(
+                                                                           CipStringN) );
         CipStringN *const string =
           (CipStringN *const ) target_stringI->array_of_string_i_structs[i].
           string;
@@ -254,26 +254,26 @@ bool CipStringICompare(const CipStringI *const stringI_1,
 
     switch (stringI_1->array_of_string_i_structs[i].char_string_struct) {
       case kCipShortString: {
-        len_1 = ((CipShortString *)string_1)->length;
-        string_1_data = ((CipShortString *)string_1)->string;
+        len_1 = ( (CipShortString *)string_1 )->length;
+        string_1_data = ( (CipShortString *)string_1 )->string;
       }
       break;
       case kCipString: {
-        len_1 = ((CipString *)string_1)->length;
-        string_1_data = ((CipString *)string_1)->string;
+        len_1 = ( (CipString *)string_1 )->length;
+        string_1_data = ( (CipString *)string_1 )->string;
       }
 
       break;
       case kCipString2: {
-        len_1 = ((CipString2 *)string_1)->length * 2;
-        string_1_data = ((CipString2 *)string_1)->string;
+        len_1 = ( (CipString2 *)string_1 )->length * 2;
+        string_1_data = ( (CipString2 *)string_1 )->string;
       }
       break;
       case kCipStringN: {
-        CipUint length = ((CipStringN *)string_1)->length;
-        CipUint size = ((CipStringN *)string_1)->size; //bytes per symbol
+        CipUint length = ( (CipStringN *)string_1 )->length;
+        CipUint size = ( (CipStringN *)string_1 )->size; //bytes per symbol
         len_1 = length * size;
-        string_1_data = ((CipStringN *)string_1)->string;
+        string_1_data = ( (CipStringN *)string_1 )->string;
 
       }
       break;
@@ -290,26 +290,26 @@ bool CipStringICompare(const CipStringI *const stringI_1,
 
       switch (stringI_2->array_of_string_i_structs[j].char_string_struct) {
         case kCipShortString: {
-          len_2 = ((CipShortString *)string_2)->length;
-          string_2_data = ((CipShortString *)string_2)->string;
+          len_2 = ( (CipShortString *)string_2 )->length;
+          string_2_data = ( (CipShortString *)string_2 )->string;
         }
         break;
         case kCipString: {
-          len_2 = ((CipString *)string_2)->length;
-          string_2_data = ((CipString *)string_2)->string;
+          len_2 = ( (CipString *)string_2 )->length;
+          string_2_data = ( (CipString *)string_2 )->string;
         }
 
         break;
         case kCipString2: {
-          len_2 = ((CipString2 *)string_2)->length * 2;
-          string_2_data = ((CipString2 *)string_2)->string;
+          len_2 = ( (CipString2 *)string_2 )->length * 2;
+          string_2_data = ( (CipString2 *)string_2 )->string;
         }
         break;
         case kCipStringN: {
-          CipUint length = ((CipStringN *)string_2)->length;
-          CipUint size = ((CipStringN *)string_2)->size; //bytes per symbol
+          CipUint length = ( (CipStringN *)string_2 )->length;
+          CipUint size = ( (CipStringN *)string_2 )->size; //bytes per symbol
           len_2 = length * size;
-          string_2_data = ((CipStringN *)string_2)->string;
+          string_2_data = ( (CipStringN *)string_2 )->string;
 
         }
         break;

+ 53 - 54
source/src/cip/ciptcpipinterface.c

@@ -120,11 +120,11 @@ static bool isalnum_c(const EipByte byte) {
  *  that has already been enforced on data reception.
  */
 static bool IsValidNameLabel(const EipByte *label) {
-  if (!isalnum_c(*label) ) {
+  if ( !isalnum_c(*label) ) {
     return false;
   }
   ++label;
-  while ('\0' != *label && (isalnum_c(*label) || '-' == *label) ) {
+  while ( '\0' != *label && (isalnum_c(*label) || '-' == *label) ) {
     ++label;
   }
   return ('\0' == *label && '-' != label[-1]);
@@ -186,7 +186,7 @@ static bool IsValidNetmask(in_addr_t netmask) {
 
   v = ~v;   /* Create the host mask */
   ++v;      /* This must be a power of 2 then */
-  bool valid = v && !(v & (v - 1) );  /* Check if it is a power of 2 */
+  bool valid = v && !( v & (v - 1) );  /* Check if it is a power of 2 */
 
   return valid && (INADDR_BROADCAST != netmask);
 }
@@ -255,31 +255,31 @@ static bool IsNetworkOrBroadcastIp(in_addr_t ip_addr,
  * A configured gateway must be reachable according to the network mask.
  */
 static bool IsValidNetworkConfig(const CipTcpIpInterfaceConfiguration *if_cfg) {
-  if (INADDR_ANY == ntohl(if_cfg->ip_address) ) {  /* N0 */
+  if ( INADDR_ANY == ntohl(if_cfg->ip_address) ) {  /* N0 */
     return false;
   }
-  if (INADDR_ANY != ntohl(if_cfg->network_mask) &&  /* MASK */
-      !IsValidNetmask(if_cfg->network_mask) ) {
+  if ( INADDR_ANY != ntohl(if_cfg->network_mask) &&  /* MASK */
+       !IsValidNetmask(if_cfg->network_mask) ) {
     return false;
   }
-  if (!IsInClassAbc(if_cfg->ip_address) ||        /* ABC */
-      !IsInClassAbc(if_cfg->gateway) ||
-      !IsInClassAbc(if_cfg->name_server) ||
-      !IsInClassAbc(if_cfg->name_server_2) ) {
+  if ( !IsInClassAbc(if_cfg->ip_address) ||        /* ABC */
+       !IsInClassAbc(if_cfg->gateway) ||
+       !IsInClassAbc(if_cfg->name_server) ||
+       !IsInClassAbc(if_cfg->name_server_2) ) {
     return false;
   }
-  if (IsOnLoopbackNetwork(if_cfg->ip_address) ||  /* NLCL */
-      IsOnLoopbackNetwork(if_cfg->gateway) ) {
+  if ( IsOnLoopbackNetwork(if_cfg->ip_address) ||  /* NLCL */
+       IsOnLoopbackNetwork(if_cfg->gateway) ) {
     return false;
   }
   /* Check NB */
-  if (IsNetworkOrBroadcastIp(if_cfg->ip_address, if_cfg->network_mask) ||
-      (INADDR_ANY != ntohl(if_cfg->gateway) &&
-       IsNetworkOrBroadcastIp(if_cfg->gateway, if_cfg->network_mask) ) ) {
+  if ( IsNetworkOrBroadcastIp(if_cfg->ip_address, if_cfg->network_mask) ||
+       ( INADDR_ANY != ntohl(if_cfg->gateway) &&
+         IsNetworkOrBroadcastIp(if_cfg->gateway, if_cfg->network_mask) ) ) {
     return false;
   }
-  if (INADDR_ANY != ntohl(if_cfg->gateway) &&
-      INADDR_ANY != ntohl(if_cfg->network_mask) ) {
+  if ( INADDR_ANY != ntohl(if_cfg->gateway) &&
+       INADDR_ANY != ntohl(if_cfg->network_mask) ) {
     /* gateway is configured. Check if it is reachable. */
     if ( (if_cfg->network_mask & if_cfg->ip_address) !=
          (if_cfg->network_mask & if_cfg->gateway) ) {
@@ -294,9 +294,9 @@ static bool IsIOConnectionActive(void) {
 
   while (NULL != node) {
     CipConnectionObject *connection = node->data;
-    if (ConnectionObjectIsTypeIOConnection(connection) &&
-        kConnectionObjectStateTimedOut !=
-        ConnectionObjectGetState(connection) ) {
+    if ( ConnectionObjectIsTypeIOConnection(connection) &&
+         kConnectionObjectStateTimedOut !=
+         ConnectionObjectGetState(connection) ) {
       /* An IO connection is present but is only considered active
        *  if it is NOT in timeout state. */
       return true;
@@ -314,8 +314,7 @@ static CipUsint dummy_data_field = 0; /**< dummy data fiel to provide non-null d
 /************** Functions ****************************************/
 
 void EncodeCipTcpIpInterfaceConfiguration(const void *const data,
-                                           ENIPMessage *const outgoing_message)
-{
+                                          ENIPMessage *const outgoing_message) {
   CipTcpIpInterfaceConfiguration *
     tcp_ip_network_interface_configuration =
     (CipTcpIpInterfaceConfiguration *) data;
@@ -377,31 +376,31 @@ int DecodeTcpIpInterfaceConfigurationControl( /* Attribute 3 */
 		CipMessageRouterRequest *const message_router_request,
 		CipMessageRouterResponse *const message_router_response) {
 
-	int number_of_decoded_bytes = -1;
+  int number_of_decoded_bytes = -1;
 
-	CipDword configuration_control_received = GetDintFromMessage(
-			&(message_router_request->data));
-	if ((configuration_control_received & kTcpipCfgCtrlMethodMask) >= 0x03
-			|| (configuration_control_received & ~kTcpipCfgCtrlMethodMask)) {
-		message_router_response->general_status =
-				kCipErrorInvalidAttributeValue;
+  CipDword configuration_control_received = GetDintFromMessage(
+    &(message_router_request->data) );
+  if ( (configuration_control_received & kTcpipCfgCtrlMethodMask) >= 0x03
+       || (configuration_control_received & ~kTcpipCfgCtrlMethodMask) ) {
+    message_router_response->general_status =
+      kCipErrorInvalidAttributeValue;
 
-	} else {
+  } else {
 
-		/* Set reserved bits to zero on reception. */
-		configuration_control_received &= (kTcpipCfgCtrlMethodMask
-				| kTcpipCfgCtrlDnsEnable);
+    /* Set reserved bits to zero on reception. */
+    configuration_control_received &= (kTcpipCfgCtrlMethodMask
+                                       | kTcpipCfgCtrlDnsEnable);
 
-		*data = configuration_control_received;
-		number_of_decoded_bytes = 4;
-		message_router_response->general_status = kCipErrorSuccess;
-	}
+    *data = configuration_control_received;
+    number_of_decoded_bytes = 4;
+    message_router_response->general_status = kCipErrorSuccess;
+  }
 
-	return number_of_decoded_bytes;
+  return number_of_decoded_bytes;
 }
 
 #if defined (OPENER_TCPIP_IFACE_CFG_SETTABLE) && \
-          0 != OPENER_TCPIP_IFACE_CFG_SETTABLE
+  0 != OPENER_TCPIP_IFACE_CFG_SETTABLE
 
 int DecodeCipTcpIpInterfaceConfiguration( /* Attribute 5 */
 		CipTcpIpInterfaceConfiguration *const data, //kCipUdintUdintUdintUdintUdintString
@@ -514,23 +513,23 @@ int DecodeCipTcpIpInterfaceEncapsulationInactivityTimeout( /* Attribute 13 */
 		CipMessageRouterRequest *const message_router_request,
 		CipMessageRouterResponse *const message_router_response) {
 
-	int number_of_decoded_bytes = -1;
+  int number_of_decoded_bytes = -1;
 
-	CipUint inactivity_timeout_received = GetUintFromMessage(
-			&(message_router_request->data));
+  CipUint inactivity_timeout_received = GetUintFromMessage(
+    &(message_router_request->data) );
 
-	if (inactivity_timeout_received > 3600) {
-		message_router_response->general_status =
-				kCipErrorInvalidAttributeValue;
-	} else {
+  if (inactivity_timeout_received > 3600) {
+    message_router_response->general_status =
+      kCipErrorInvalidAttributeValue;
+  } else {
 
-		*data = inactivity_timeout_received;
-		message_router_response->general_status = kCipErrorSuccess;
-		number_of_decoded_bytes = 2;
+    *data = inactivity_timeout_received;
+    message_router_response->general_status = kCipErrorSuccess;
+    number_of_decoded_bytes = 2;
 
-	}
+  }
 
-	return number_of_decoded_bytes;
+  return number_of_decoded_bytes;
 
 }
 
@@ -584,7 +583,7 @@ EipStatus CipTcpIpInterfaceInit() {
                   kGetableSingleAndAll);
 
 #if defined (OPENER_TCPIP_IFACE_CFG_SETTABLE) && \
-          0 != OPENER_TCPIP_IFACE_CFG_SETTABLE
+  0 != OPENER_TCPIP_IFACE_CFG_SETTABLE
   InsertAttribute(instance,
                   5,
                   kCipUdintUdintUdintUdintUdintString,
@@ -608,7 +607,7 @@ EipStatus CipTcpIpInterfaceInit() {
                   NULL, //not settable
                   &g_tcpip.interface_configuration,
                   kGetableSingleAndAll | kNvDataFunc | IFACE_CFG_SET_MODE);
-    InsertAttribute(instance,
+  InsertAttribute(instance,
                   6,
                   kCipString,
                   EncodeCipString,
@@ -711,7 +710,7 @@ void CipTcpIpCalculateMulticastIp(CipTcpIpObject *const tcpip) {
   host_id &= 0x3ff;
 
   tcpip->mcast_config.starting_multicast_address =
-    htonl(cip_mcast_base_addr + (host_id << 5) );
+    htonl( cip_mcast_base_addr + (host_id << 5) );
 }
 
 

+ 73 - 72
source/src/cip/ciptypes.c

@@ -8,88 +8,89 @@
 #include <trace.h>
 
 /* functions*/
-size_t GetCipDataTypeLength(EipUint8 type, const EipUint8 *data) {
+size_t GetCipDataTypeLength(EipUint8 type,
+                            const EipUint8 *data) {
 
-	size_t length = 0;
+  size_t length = 0;
 
-	switch (type) {
-		case kCipBool:
-		case kCipSint:
-		case kCipUsint:
-		case kCipByte:
-			length = 1;
-			break;
+  switch (type) {
+    case kCipBool:
+    case kCipSint:
+    case kCipUsint:
+    case kCipByte:
+      length = 1;
+      break;
 
-		case kCipInt:
-		case kCipUint:
-		case kCipWord:
-		case kCipUsintUsint:
-		case kCipItime:
-		case kCipDate:
-		case kCipEngUnit:
-			length = 2;
-			break;
+    case kCipInt:
+    case kCipUint:
+    case kCipWord:
+    case kCipUsintUsint:
+    case kCipItime:
+    case kCipDate:
+    case kCipEngUnit:
+      length = 2;
+      break;
 
-		case kCipDint:
-		case kCipUdint:
-		case kCipDword:
-		case kCipStime:
-		case kCipFtime:
-		case kCipTime:
-		case kCipReal:
-		case kCipTimeOfDay:
-			length = 4;
-			break;
+    case kCipDint:
+    case kCipUdint:
+    case kCipDword:
+    case kCipStime:
+    case kCipFtime:
+    case kCipTime:
+    case kCipReal:
+    case kCipTimeOfDay:
+      length = 4;
+      break;
 
-		case kCipLint:
-		case kCipUlint:
-		case kCipLreal:
-		case kCipLword:
-		case kCipLtime:
-			length = 8;
-			break;
+    case kCipLint:
+    case kCipUlint:
+    case kCipLreal:
+    case kCipLword:
+    case kCipLtime:
+      length = 8;
+      break;
 
-		case kCip6Usint:
-			length = 6;
-			break;
+    case kCip6Usint:
+      length = 6;
+      break;
 
-		case kCipString:
-		case kCipString2:
-		case kCipStringN:
-			if(NULL != data){
-				length = GetIntFromMessage(&data) + 2; // string length + 2 bytes length indicator
-			}
-			break;
+    case kCipString:
+    case kCipString2:
+    case kCipStringN:
+      if(NULL != data) {
+        length = GetIntFromMessage(&data) + 2;                         // string length + 2 bytes length indicator
+      }
+      break;
 
-		case kCipShortString:
-			if(NULL != data){
-				length = GetSintFromMessage(&data) + 1; // string length + 1 byte length indicator
-			}
-			break;
+    case kCipShortString:
+      if(NULL != data) {
+        length = GetSintFromMessage(&data) + 1;                         // string length + 1 byte length indicator
+      }
+      break;
 
-		case kCipEpath:
-			if(NULL != data){
-				length = GetIntFromMessage(&data) + 2; // path size + 2 bytes path size indicator
-			}
-			break;
+    case kCipEpath:
+      if(NULL != data) {
+        length = GetIntFromMessage(&data) + 2;                         // path size + 2 bytes path size indicator
+      }
+      break;
 
-		case kCipByteArray:
-			if (NULL != data) {
-				CipByteArray *byte_array = (CipByteArray*) data;
-				length = byte_array->length;
-			}
-			break;
+    case kCipByteArray:
+      if (NULL != data) {
+        CipByteArray *byte_array = (CipByteArray *) data;
+        length = byte_array->length;
+      }
+      break;
 
-		default:
-			OPENER_TRACE_ERR("GetCipDataTypeLength ERROR\n");
-			return 0;
+    default:
+      OPENER_TRACE_ERR("GetCipDataTypeLength ERROR\n");
+      return 0;
 
-		/* TODO: missing data types:
-		 * kCipAny
-		 * kCipDateAndTime
-		 * kCipStringI
-		 * kCipMemberList
-		 */
-	}
-	return length;
+      /* TODO: missing data types:
+       * kCipAny
+       * kCipDateAndTime
+       * kCipStringI
+       * kCipMemberList
+       */
+  }
+  return length;
 }

+ 3 - 3
source/src/cip/ciptypes.h

@@ -348,9 +348,9 @@ typedef EipStatus (*CipGetSetCallback)(CipInstance *const instance,
  *  @return           status of kEipStatusOk or kEipStatusError on failure
  */
 typedef EipStatus (*CipCallback)(
-    CipInstance *RESTRICT const instance,
-    CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response);
+  CipInstance *RESTRICT const instance,
+  CipMessageRouterRequest *message_router_request,
+  CipMessageRouterResponse *message_router_response);
 
 /** @brief Type definition of CipClass that is a subclass of CipInstance */
 typedef struct cip_class {

+ 24 - 24
source/src/enet_encap/cpf.c

@@ -30,7 +30,7 @@ CipCommonPacketFormatData g_common_packet_format_data_item; /**< CPF global data
 
 static void InitializeMessageRouterResponse(
   CipMessageRouterResponse *const message_router_response) {
-  memset(message_router_response, 0, sizeof(*message_router_response) );
+  memset( message_router_response, 0, sizeof(*message_router_response) );
   InitializeENIPMessage(&message_router_response->message);
 }
 
@@ -41,13 +41,13 @@ EipStatus NotifyCommonPacketFormat(const EncapsulationData *const received_data,
   CipMessageRouterResponse message_router_response;
   InitializeMessageRouterResponse(&message_router_response);
 
-  if(kEipStatusError
-     == (return_value =
-           CreateCommonPacketFormatStructure(received_data->
-                                             current_communication_buffer_position,
-                                             received_data->data_length,
-                                             &
-                                             g_common_packet_format_data_item) ) )
+  if( kEipStatusError
+      == ( return_value =
+             CreateCommonPacketFormatStructure(received_data->
+                                               current_communication_buffer_position,
+                                               received_data->data_length,
+                                               &
+                                               g_common_packet_format_data_item) ) )
   {
     OPENER_TRACE_ERR("notifyCPF: error from createCPFstructure\n");
   } else {
@@ -146,9 +146,9 @@ EipStatus NotifyConnectedCommonPacketFormat(
           if(connection_object->sequence_count_consuming ==
              g_common_packet_format_data_item.address_item.data.sequence_number)
           {
-            memcpy(outgoing_message,
-                   &(connection_object->last_reply_sent),
-                   sizeof(ENIPMessage) );
+            memcpy( outgoing_message,
+                    &(connection_object->last_reply_sent),
+                    sizeof(ENIPMessage) );
             outgoing_message->current_message_position =
               outgoing_message->message_buffer;
             /* Regenerate encapsulation header for new message */
@@ -197,9 +197,9 @@ EipStatus NotifyConnectedCommonPacketFormat(
                                         kEncapsulationProtocolSuccess,
                                         outgoing_message);
             outgoing_message->current_message_position = pos;
-            memcpy(&connection_object->last_reply_sent,
-                   outgoing_message,
-                   sizeof(ENIPMessage) );
+            memcpy( &connection_object->last_reply_sent,
+                    outgoing_message,
+                    sizeof(ENIPMessage) );
             return_value = kEipStatusOkSend;
           }
         } else {
@@ -436,11 +436,11 @@ void EncodeDataItemData(
 void EncodeConnectedDataItemLength(
   const CipMessageRouterResponse *const message_router_response,
   ENIPMessage *const outgoing_message) {
-  AddIntToMessage( (EipUint16) (message_router_response->message.
-                                used_message_length + 4 + 2                                 /* TODO: Magic numbers */
-                                + (2 *
-                                   message_router_response->
-                                   size_of_additional_status) ),
+  AddIntToMessage( (EipUint16) ( message_router_response->message.
+                                 used_message_length + 4 + 2                                /* TODO: Magic numbers */
+                                 + (2 *
+                                    message_router_response->
+                                    size_of_additional_status) ),
                    outgoing_message );
 }
 
@@ -552,11 +552,11 @@ void EncodeExtendedStatus(
 void EncodeUnconnectedDataItemLength(
   const CipMessageRouterResponse *const message_router_response,
   ENIPMessage *const outgoing_message) {
-  AddIntToMessage( (EipUint16) (message_router_response->message.
-                                used_message_length + 4                                 /* TODO: Magic number */
-                                + (2 *
-                                   message_router_response->
-                                   size_of_additional_status) ),
+  AddIntToMessage( (EipUint16) ( message_router_response->message.
+                                 used_message_length + 4                                /* TODO: Magic number */
+                                 + (2 *
+                                    message_router_response->
+                                    size_of_additional_status) ),
                    outgoing_message );
 }
 

+ 280 - 126
source/src/enet_encap/encap.c

@@ -74,27 +74,38 @@ EncapsulationServiceInformation g_service_information;
 
 int g_registered_sessions[OPENER_NUMBER_OF_SUPPORTED_SESSIONS];
 
-DelayedEncapsulationMessage g_delayed_encapsulation_messages[ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES];
+DelayedEncapsulationMessage g_delayed_encapsulation_messages[
+  ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES];
 
 /*** private functions ***/
-void HandleReceivedListIdentityCommandTcp(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+void HandleReceivedListIdentityCommandTcp(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message);
 
 void HandleReceivedListIdentityCommandUdp(const int socket,
                                           const struct sockaddr_in *const from_address,
                                           const EncapsulationData *const receive_data);
 
-EipStatus HandleReceivedUnregisterSessionCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+EipStatus HandleReceivedUnregisterSessionCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message);
 
-EipStatus HandleReceivedSendUnitDataCommand(const EncapsulationData *const receive_data, const struct sockaddr *const originator_address,
-    ENIPMessage *const outgoing_message);
+EipStatus HandleReceivedSendUnitDataCommand(
+  const EncapsulationData *const receive_data,
+  const struct sockaddr *const originator_address,
+  ENIPMessage *const outgoing_message);
 
-EipStatus HandleReceivedInvalidCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+EipStatus HandleReceivedInvalidCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message);
 
 int GetFreeSessionIndex(void);
 
-SessionStatus CheckRegisteredSessions(const EncapsulationData *const receive_data);
+SessionStatus CheckRegisteredSessions(
+  const EncapsulationData *const receive_data);
 
-void DetermineDelayTime(const EipByte *buffer_start, DelayedEncapsulationMessage *const delayed_message_buffer);
+void DetermineDelayTime(const EipByte *buffer_start,
+                        DelayedEncapsulationMessage *const delayed_message_buffer);
 
 /*   @brief Initializes session list and interface information. */
 void EncapsulationInit(void) {
@@ -119,24 +130,33 @@ void EncapsulationInit(void) {
   g_service_information.type_code = kCipItemIdListServiceResponse;
   g_service_information.length = sizeof(g_service_information);
   g_service_information.encapsulation_protocol_version = 1;
-  g_service_information.capability_flags = kCapabilityFlagsCipTcp | kCapabilityFlagsCipUdpClass0or1;
-  snprintf((char*) g_service_information.name_of_service, sizeof(g_service_information.name_of_service), "Communications");
+  g_service_information.capability_flags = kCapabilityFlagsCipTcp |
+                                           kCapabilityFlagsCipUdpClass0or1;
+  snprintf( (char *) g_service_information.name_of_service,
+            sizeof(g_service_information.name_of_service), "Communications" );
 }
 
-EipStatus HandleReceivedExplictTcpData(int socket, EipUint8 *buffer, size_t length, int *number_of_remaining_bytes, struct sockaddr *originator_address,
-    ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedExplictTcpData(int socket,
+                                       EipUint8 *buffer,
+                                       size_t length,
+                                       int *number_of_remaining_bytes,
+                                       struct sockaddr *originator_address,
+                                       ENIPMessage *const outgoing_message) {
   OPENER_TRACE_INFO("Handles data for TCP socket: %d\n", socket);
   EipStatus return_value = kEipStatusOk;
   EncapsulationData encapsulation_data = { 0 };
   /* eat the encapsulation header*/
   /* the structure contains a pointer to the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
-  const int remaining_bytes = CreateEncapsulationStructure(buffer, length, &encapsulation_data);
+  const int remaining_bytes = CreateEncapsulationStructure(buffer,
+                                                           length,
+                                                           &encapsulation_data);
 
   if(remaining_bytes >= 0) {
     *number_of_remaining_bytes = remaining_bytes;
   } else {
-    OPENER_TRACE_ERR("Fragmented packet detected! Fragmented packets are not supported!\n");
+    OPENER_TRACE_ERR(
+      "Fragmented packet detected! Fragmented packets are not supported!\n");
     *number_of_remaining_bytes = 0;
     return kEipStatusError;
   }
@@ -149,7 +169,7 @@ EipStatus HandleReceivedExplictTcpData(int socket, EipUint8 *buffer, size_t leng
       encapsulation_data.status = kEncapsulationProtocolSuccess;
       return_value = kEipStatusOkSend;
       /* most of these functions need a reply to be send */
-      switch(encapsulation_data.command_code){
+      switch(encapsulation_data.command_code) {
         case (kEncapsulationCommandNoOperation):
           OPENER_TRACE_INFO("NOP\n");
           /* NOP needs no reply and does nothing */
@@ -158,41 +178,54 @@ EipStatus HandleReceivedExplictTcpData(int socket, EipUint8 *buffer, size_t leng
 
         case (kEncapsulationCommandListServices):
           OPENER_TRACE_INFO("List services\n");
-          HandleReceivedListServicesCommand(&encapsulation_data, outgoing_message);
+          HandleReceivedListServicesCommand(&encapsulation_data,
+                                            outgoing_message);
           break;
 
         case (kEncapsulationCommandListIdentity):
           OPENER_TRACE_INFO("List identity\n");
-          HandleReceivedListIdentityCommandTcp(&encapsulation_data, outgoing_message);
+          HandleReceivedListIdentityCommandTcp(&encapsulation_data,
+                                               outgoing_message);
           break;
 
         case (kEncapsulationCommandListInterfaces):
           OPENER_TRACE_INFO("List interfaces\n");
-          HandleReceivedListInterfacesCommand(&encapsulation_data, outgoing_message);
+          HandleReceivedListInterfacesCommand(&encapsulation_data,
+                                              outgoing_message);
           break;
 
         case (kEncapsulationCommandRegisterSession):
           OPENER_TRACE_INFO("Register session\n");
-          HandleReceivedRegisterSessionCommand(socket, &encapsulation_data, outgoing_message);
+          HandleReceivedRegisterSessionCommand(socket,
+                                               &encapsulation_data,
+                                               outgoing_message);
           break;
 
         case (kEncapsulationCommandUnregisterSession):
           OPENER_TRACE_INFO("unregister session\n");
-          return_value = HandleReceivedUnregisterSessionCommand(&encapsulation_data, outgoing_message);
+          return_value = HandleReceivedUnregisterSessionCommand(
+            &encapsulation_data,
+            outgoing_message);
           break;
 
         case (kEncapsulationCommandSendRequestReplyData):
           OPENER_TRACE_INFO("Send Request/Reply Data\n");
-          return_value = HandleReceivedSendRequestResponseDataCommand(&encapsulation_data, originator_address, outgoing_message);
+          return_value = HandleReceivedSendRequestResponseDataCommand(
+            &encapsulation_data,
+            originator_address,
+            outgoing_message);
           break;
 
         case (kEncapsulationCommandSendUnitData):
           OPENER_TRACE_INFO("Send Unit Data\n");
-          return_value = HandleReceivedSendUnitDataCommand(&encapsulation_data, originator_address, outgoing_message);
+          return_value = HandleReceivedSendUnitDataCommand(&encapsulation_data,
+                                                           originator_address,
+                                                           outgoing_message);
           break;
 
         default:
-          return_value = HandleReceivedInvalidCommand(&encapsulation_data, outgoing_message);
+          return_value = HandleReceivedInvalidCommand(&encapsulation_data,
+                                                      outgoing_message);
           break;
       }
     }
@@ -201,20 +234,27 @@ EipStatus HandleReceivedExplictTcpData(int socket, EipUint8 *buffer, size_t leng
   return return_value;
 }
 
-EipStatus HandleReceivedExplictUdpData(const int socket, const struct sockaddr_in *from_address, const EipUint8 *buffer, const size_t buffer_length,
-    int *number_of_remaining_bytes,
-    bool unicast, ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedExplictUdpData(const int socket,
+                                       const struct sockaddr_in *from_address,
+                                       const EipUint8 *buffer,
+                                       const size_t buffer_length,
+                                       int *number_of_remaining_bytes,
+                                       bool unicast,
+                                       ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusOk;
   EncapsulationData encapsulation_data = { 0 };
   /* eat the encapsulation header*/
   /* the structure contains a pointer to the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
-  const int remaining_bytes = CreateEncapsulationStructure(buffer, buffer_length, &encapsulation_data);
+  const int remaining_bytes = CreateEncapsulationStructure(buffer,
+                                                           buffer_length,
+                                                           &encapsulation_data);
 
   if(remaining_bytes >= 0) {
     *number_of_remaining_bytes = remaining_bytes;
   } else {
-    OPENER_TRACE_ERR("Fragmented packet detected! Fragmented packets are not supported!\n");
+    OPENER_TRACE_ERR(
+      "Fragmented packet detected! Fragmented packets are not supported!\n");
     *number_of_remaining_bytes = 0;
     return kEipStatusError;
   }
@@ -227,16 +267,18 @@ EipStatus HandleReceivedExplictUdpData(const int socket, const struct sockaddr_i
       encapsulation_data.status = kEncapsulationProtocolSuccess;
       return_value = kEipStatusOkSend;
       /* most of these functions need a reply to be send */
-      switch(encapsulation_data.command_code){
+      switch(encapsulation_data.command_code) {
         case (kEncapsulationCommandListServices):
           OPENER_TRACE_INFO("List Service\n");
-          HandleReceivedListServicesCommand(&encapsulation_data, outgoing_message);
+          HandleReceivedListServicesCommand(&encapsulation_data,
+                                            outgoing_message);
           break;
 
         case (kEncapsulationCommandListIdentity):
           OPENER_TRACE_INFO("List Identity\n");
           if(unicast == true) {
-            HandleReceivedListIdentityCommandTcp(&encapsulation_data, outgoing_message);
+            HandleReceivedListIdentityCommandTcp(&encapsulation_data,
+                                                 outgoing_message);
           } else {
             HandleReceivedListIdentityCommandUdp(socket,
                                                  from_address,
@@ -248,10 +290,11 @@ EipStatus HandleReceivedExplictUdpData(const int socket, const struct sockaddr_i
 
         case (kEncapsulationCommandListInterfaces):
           OPENER_TRACE_INFO("List Interfaces\n");
-          HandleReceivedListInterfacesCommand(&encapsulation_data, outgoing_message);
+          HandleReceivedListInterfacesCommand(&encapsulation_data,
+                                              outgoing_message);
           break;
 
-          /* The following commands are not to be sent via UDP */
+        /* The following commands are not to be sent via UDP */
         case (kEncapsulationCommandNoOperation):
         case (kEncapsulationCommandRegisterSession):
         case (kEncapsulationCommandUnregisterSession):
@@ -274,13 +317,18 @@ void SkipEncapsulationHeader(ENIPMessage *const outgoing_message) {
   outgoing_message->current_message_position += ENCAPSULATION_HEADER_LENGTH;
 }
 
-void GenerateEncapsulationHeader(const EncapsulationData *const receive_data, const size_t command_specific_data_length, const size_t session_handle,
-    const EncapsulationProtocolErrorCode encapsulation_protocol_status, ENIPMessage *const outgoing_message) {
+void GenerateEncapsulationHeader(const EncapsulationData *const receive_data,
+                                 const size_t command_specific_data_length,
+                                 const size_t session_handle,
+                                 const EncapsulationProtocolErrorCode encapsulation_protocol_status,
+                                 ENIPMessage *const outgoing_message) {
   AddIntToMessage(receive_data->command_code, outgoing_message);
   AddIntToMessage(command_specific_data_length, outgoing_message);
   AddDintToMessage(session_handle, outgoing_message); //Session handle
   AddDintToMessage(encapsulation_protocol_status, outgoing_message); //Status
-  memcpy(outgoing_message->current_message_position, receive_data->sender_context, kSenderContextSize); // sender context
+  memcpy(outgoing_message->current_message_position,
+         receive_data->sender_context,
+         kSenderContextSize);                                                                           // sender context
   outgoing_message->current_message_position += kSenderContextSize;
   outgoing_message->used_message_length += kSenderContextSize;
   AddDintToMessage(0, outgoing_message); // options
@@ -290,40 +338,59 @@ void GenerateEncapsulationHeader(const EncapsulationData *const receive_data, co
  *  @param receive_data pointer to structure with received data
  *  @param outgoing_message The outgoing ENIP message
  */
-void HandleReceivedListServicesCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+void HandleReceivedListServicesCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message) {
 
   /* Create encapsulation header */
-  const size_t kListServicesCommandSpecificDataLength = sizeof(CipUint) + sizeof(g_service_information);
-  GenerateEncapsulationHeader(receive_data, kListServicesCommandSpecificDataLength, 0,
-  /* Session handle will be ignored */
-  kEncapsulationProtocolSuccess,
-  /* Protocol status */
-  outgoing_message);
+  const size_t kListServicesCommandSpecificDataLength = sizeof(CipUint) +
+                                                        sizeof(
+    g_service_information);
+  GenerateEncapsulationHeader(receive_data,
+                              kListServicesCommandSpecificDataLength,
+                              0,
+                              /* Session handle will be ignored */
+                              kEncapsulationProtocolSuccess,
+                              /* Protocol status */
+                              outgoing_message);
 
   /* Command specific data copy Interface data to msg for sending */
   AddIntToMessage(1, outgoing_message); // Item count
   AddIntToMessage(g_service_information.type_code, outgoing_message);
-  AddIntToMessage((EipUint16) (g_service_information.length - 4), outgoing_message);
-  AddIntToMessage(g_service_information.encapsulation_protocol_version, outgoing_message);
+  AddIntToMessage( (EipUint16) (g_service_information.length - 4),
+                   outgoing_message );
+  AddIntToMessage(g_service_information.encapsulation_protocol_version,
+                  outgoing_message);
   AddIntToMessage(g_service_information.capability_flags, outgoing_message);
-  memcpy(outgoing_message->current_message_position, g_service_information.name_of_service, sizeof(g_service_information.name_of_service));
-  outgoing_message->current_message_position += sizeof(g_service_information.name_of_service);
-  outgoing_message->used_message_length += sizeof(g_service_information.name_of_service);
+  memcpy( outgoing_message->current_message_position,
+          g_service_information.name_of_service,
+          sizeof(g_service_information.name_of_service) );
+  outgoing_message->current_message_position +=
+    sizeof(g_service_information.name_of_service);
+  outgoing_message->used_message_length +=
+    sizeof(g_service_information.name_of_service);
 }
 
-void HandleReceivedListInterfacesCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+void HandleReceivedListInterfacesCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message) {
 
   /* Encapsulation header */
   const size_t kListInterfacesCommandSpecificDataLength = sizeof(CipUint);
 
-  GenerateEncapsulationHeader(receive_data, kListInterfacesCommandSpecificDataLength, 0,
-  /* Session handle will be ignored */
-  kEncapsulationProtocolSuccess, outgoing_message);
+  GenerateEncapsulationHeader(receive_data,
+                              kListInterfacesCommandSpecificDataLength,
+                              0,
+                              /* Session handle will be ignored */
+                              kEncapsulationProtocolSuccess,
+                              outgoing_message);
   /* Command specific data */
   AddIntToMessage(0x0000, outgoing_message); /* Set Item Count to 0: no Target Items follow. */
 }
 
-void HandleReceivedListIdentityCommandTcp(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+void HandleReceivedListIdentityCommandTcp(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message) {
   EncapsulateListIdentityResponseMessage(receive_data, outgoing_message);
 }
 
@@ -346,17 +413,22 @@ void HandleReceivedListIdentityCommandUdp(const int socket,
 
   if(NULL != delayed_message_buffer) {
     delayed_message_buffer->socket = socket;
-    memcpy((&delayed_message_buffer->receiver), from_address, sizeof(struct sockaddr_in));
+    memcpy( (&delayed_message_buffer->receiver), from_address,
+            sizeof(struct sockaddr_in) );
 
-    DetermineDelayTime(receive_data->communication_buffer_start, delayed_message_buffer);
+    DetermineDelayTime(receive_data->communication_buffer_start,
+                       delayed_message_buffer);
 
     EncapsulateListIdentityResponseMessage(receive_data, p_outgoing_message);
   }
 }
 
 CipUint ListIdentityGetCipIdentityItemLength() {
-  return sizeof(CipUint) + sizeof(CipInt) + sizeof(CipUint) + sizeof(CipUdint) + 8 * sizeof(CipUsint) + sizeof(CipUint) + sizeof(CipUint) + sizeof(CipUint)
-    + 2 * sizeof(CipUsint) + sizeof(CipWord) + sizeof(CipUdint) + sizeof(CipUsint) + g_identity.product_name.length + sizeof(CipUsint);
+  return sizeof(CipUint) + sizeof(CipInt) + sizeof(CipUint) + sizeof(CipUdint) +
+         8 * sizeof(CipUsint) + sizeof(CipUint) + sizeof(CipUint) +
+         sizeof(CipUint)
+         + 2 * sizeof(CipUsint) + sizeof(CipWord) + sizeof(CipUdint) +
+         sizeof(CipUsint) + g_identity.product_name.length + sizeof(CipUsint);
 }
 
 void EncodeListIdentityCipIdentityItem(ENIPMessage *const outgoing_message) {
@@ -368,7 +440,9 @@ void EncodeListIdentityCipIdentityItem(ENIPMessage *const outgoing_message) {
 
   AddIntToMessage(kSupportedProtocolVersion, outgoing_message);
 
-  EncapsulateIpAddress(htons(kOpenerEthernetPort), g_tcpip.interface_configuration.ip_address, outgoing_message);
+  EncapsulateIpAddress(htons(kOpenerEthernetPort),
+                       g_tcpip.interface_configuration.ip_address,
+                       outgoing_message);
 
   /** Array of USINT - length 8 shall be set to zero */
   FillNextNMessageOctetsWithValueAndMoveToNextPosition(0, 8, outgoing_message);
@@ -380,32 +454,45 @@ void EncodeListIdentityCipIdentityItem(ENIPMessage *const outgoing_message) {
   AddSintToMessage(g_identity.revision.minor_revision, outgoing_message);
   AddIntToMessage(g_identity.status, outgoing_message);
   AddDintToMessage(g_identity.serial_number, outgoing_message);
-  AddSintToMessage((unsigned char) g_identity.product_name.length, outgoing_message);
+  AddSintToMessage( (unsigned char) g_identity.product_name.length,
+                    outgoing_message );
 //TODO Change to EncodeCipString
-  memcpy(outgoing_message->current_message_position, g_identity.product_name.string, g_identity.product_name.length);
+  memcpy(outgoing_message->current_message_position,
+         g_identity.product_name.string,
+         g_identity.product_name.length);
   outgoing_message->current_message_position += g_identity.product_name.length;
   outgoing_message->used_message_length += g_identity.product_name.length;
 
   AddSintToMessage(g_identity.state, outgoing_message);
 }
 
-void EncapsulateListIdentityResponseMessage(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+void EncapsulateListIdentityResponseMessage(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message) {
 
-  const CipUint kEncapsulationCommandListIdentityLength = ListIdentityGetCipIdentityItemLength() + sizeof(CipUint) + sizeof(CipUint) + sizeof(CipUint); /* Last element is item count */
+  const CipUint kEncapsulationCommandListIdentityLength =
+    ListIdentityGetCipIdentityItemLength() + sizeof(CipUint) + sizeof(CipUint) +
+    sizeof(CipUint);                                                                                                                                    /* Last element is item count */
 
-  GenerateEncapsulationHeader(receive_data, kEncapsulationCommandListIdentityLength, 0,
-  /* Session handle will be ignored by receiver */
-  kEncapsulationProtocolSuccess, outgoing_message);
+  GenerateEncapsulationHeader(receive_data,
+                              kEncapsulationCommandListIdentityLength,
+                              0,
+                              /* Session handle will be ignored by receiver */
+                              kEncapsulationProtocolSuccess,
+                              outgoing_message);
 
   AddIntToMessage(1, outgoing_message); /* Item count: one item */
   EncodeListIdentityCipIdentityItem(outgoing_message);
 
 }
 
-void DetermineDelayTime(const EipByte *buffer_start, DelayedEncapsulationMessage *const delayed_message_buffer) {
+void DetermineDelayTime(const EipByte *buffer_start,
+                        DelayedEncapsulationMessage *const delayed_message_buffer)
+{
 
   buffer_start += 12; /* start of the sender context */
-  EipUint16 maximum_delay_time = GetUintFromMessage((const EipUint8** const ) &buffer_start);
+  EipUint16 maximum_delay_time = GetUintFromMessage(
+    (const EipUint8 **const ) &buffer_start );
 
   if(0 == maximum_delay_time) {
     maximum_delay_time = kListIdentityDefaultDelayTime;
@@ -416,13 +503,21 @@ void DetermineDelayTime(const EipByte *buffer_start, DelayedEncapsulationMessage
   delayed_message_buffer->time_out = rand() % maximum_delay_time;
 }
 
-void EncapsulateRegisterSessionCommandResponseMessage(const EncapsulationData *const receive_data, const size_t session_handle,
-    const EncapsulationProtocolErrorCode encapsulation_protocol_status, ENIPMessage *const outgoing_message) {
+void EncapsulateRegisterSessionCommandResponseMessage(
+  const EncapsulationData *const receive_data,
+  const size_t session_handle,
+  const EncapsulationProtocolErrorCode encapsulation_protocol_status,
+  ENIPMessage *const outgoing_message) {
 
   /* Encapsulation header */
-  const size_t kListInterfacesCommandSpecificDataLength = sizeof(CipUint) + sizeof(CipUint);
+  const size_t kListInterfacesCommandSpecificDataLength = sizeof(CipUint) +
+                                                          sizeof(CipUint);
   assert(kListInterfacesCommandSpecificDataLength == 4);
-  GenerateEncapsulationHeader(receive_data, kListInterfacesCommandSpecificDataLength, session_handle, encapsulation_protocol_status, outgoing_message);
+  GenerateEncapsulationHeader(receive_data,
+                              kListInterfacesCommandSpecificDataLength,
+                              session_handle,
+                              encapsulation_protocol_status,
+                              outgoing_message);
 
   AddIntToMessage(1, outgoing_message); /* protocol version*/
   AddIntToMessage(0, outgoing_message); /* Options flag, shall be set to zero */
@@ -432,23 +527,29 @@ void EncapsulateRegisterSessionCommandResponseMessage(const EncapsulationData *c
  * @param socket Socket this request is associated to. Needed for double register check
  * @param receive_data Pointer to received data with request/response.
  */
-void HandleReceivedRegisterSessionCommand(int socket, const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+void HandleReceivedRegisterSessionCommand(int socket,
+                                          const EncapsulationData *const receive_data,
+                                          ENIPMessage *const outgoing_message) {
   int session_index = 0;
   size_t session_handle = 0;
-  EncapsulationProtocolErrorCode encapsulation_protocol_status = kEncapsulationProtocolSuccess;
+  EncapsulationProtocolErrorCode encapsulation_protocol_status =
+    kEncapsulationProtocolSuccess;
 
-  EipUint16 protocol_version = GetUintFromMessage((const EipUint8** const ) &receive_data->current_communication_buffer_position);
-  EipUint16 option_flag = GetUintFromMessage((const EipUint8** const ) &receive_data->current_communication_buffer_position);
+  EipUint16 protocol_version = GetUintFromMessage(
+    (const EipUint8 **const ) &receive_data->current_communication_buffer_position );
+  EipUint16 option_flag = GetUintFromMessage(
+    (const EipUint8 **const ) &receive_data->current_communication_buffer_position );
 
   /* check if requested protocol version is supported and the register session option flag is zero*/
-  if((0 < protocol_version) && (protocol_version <= kSupportedProtocolVersion) && (0 == option_flag)) { /*Option field should be zero*/
+  if( (0 < protocol_version) &&
+      (protocol_version <= kSupportedProtocolVersion) && (0 == option_flag) ) {                         /*Option field should be zero*/
     /* check if the socket has already a session open */
     for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
       if(g_registered_sessions[i] == socket) {
         /* the socket has already registered a session this is not allowed*/
         OPENER_TRACE_INFO(
-            "Error: A session is already registered at socket %d\n",
-            socket);
+          "Error: A session is already registered at socket %d\n",
+          socket);
         session_handle = i + 1; /*return the already assigned session back, the cip spec is not clear about this needs to be tested*/
         encapsulation_protocol_status = kEncapsulationProtocolInvalidCommand;
         session_index = kSessionStatusInvalid;
@@ -460,10 +561,12 @@ void HandleReceivedRegisterSessionCommand(int socket, const EncapsulationData *c
       session_index = GetFreeSessionIndex();
       if(kSessionStatusInvalid == session_index) /* no more sessions available */
       {
-        encapsulation_protocol_status = kEncapsulationProtocolInsufficientMemory;
+        encapsulation_protocol_status =
+          kEncapsulationProtocolInsufficientMemory;
       } else { /* successful session registered */
-        SocketTimer *socket_timer = SocketTimerArrayGetEmptySocketTimer(g_timestamps,
-        OPENER_NUMBER_OF_SUPPORTED_SESSIONS);
+        SocketTimer *socket_timer = SocketTimerArrayGetEmptySocketTimer(
+          g_timestamps,
+          OPENER_NUMBER_OF_SUPPORTED_SESSIONS);
         SocketTimerSetSocket(socket_timer, socket);
         SocketTimerSetLastUpdate(socket_timer, g_actual_time);
         g_registered_sessions[session_index] = socket; /* store associated socket */
@@ -475,7 +578,10 @@ void HandleReceivedRegisterSessionCommand(int socket, const EncapsulationData *c
     encapsulation_protocol_status = kEncapsulationProtocolUnsupportedProtocol;
   }
 
-  EncapsulateRegisterSessionCommandResponseMessage(receive_data, session_handle, encapsulation_protocol_status, outgoing_message);
+  EncapsulateRegisterSessionCommandResponseMessage(receive_data,
+                                                   session_handle,
+                                                   encapsulation_protocol_status,
+                                                   outgoing_message);
 
 }
 
@@ -486,10 +592,13 @@ void HandleReceivedRegisterSessionCommand(int socket, const EncapsulationData *c
  *
  * Close all corresponding TCP connections and delete session handle.
  */
-EipStatus HandleReceivedUnregisterSessionCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedUnregisterSessionCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message) {
   OPENER_TRACE_INFO("encap.c: Unregister Session Command\n");
-  if((0 < receive_data->session_handle) && (receive_data->session_handle <=
-  OPENER_NUMBER_OF_SUPPORTED_SESSIONS)) {
+  if( (0 < receive_data->session_handle) && (receive_data->session_handle <=
+                                             OPENER_NUMBER_OF_SUPPORTED_SESSIONS) )
+  {
     size_t i = receive_data->session_handle - 1;
     if(kEipInvalidSocket != g_registered_sessions[i]) {
       CloseTcpSocket(g_registered_sessions[i]);
@@ -500,7 +609,11 @@ EipStatus HandleReceivedUnregisterSessionCommand(const EncapsulationData *const
   }
 
   /* no such session registered */
-  GenerateEncapsulationHeader(receive_data, 0, receive_data->session_handle, kEncapsulationProtocolInvalidSessionHandle, outgoing_message);
+  GenerateEncapsulationHeader(receive_data,
+                              0,
+                              receive_data->session_handle,
+                              kEncapsulationProtocolInvalidSessionHandle,
+                              outgoing_message);
   return kEipStatusOkSend;
 }
 
@@ -509,24 +622,34 @@ EipStatus HandleReceivedUnregisterSessionCommand(const EncapsulationData *const
  *  @param originator_address Address of the originator as received from socket
  *  @param outgoing_message The outgoing ENIP message
  */
-EipStatus HandleReceivedSendUnitDataCommand(const EncapsulationData *const receive_data, const struct sockaddr *const originator_address,
-    ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedSendUnitDataCommand(
+  const EncapsulationData *const receive_data,
+  const struct sockaddr *const originator_address,
+  ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusOkSend;
-  /*EipStatus*/return_value = kEipStatusOk; /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
+  /*EipStatus*/ return_value = kEipStatusOk; /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
 
   if(receive_data->data_length >= 6) {
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* don't use the data yet */
-    GetDintFromMessage((const EipUint8** const ) &receive_data->current_communication_buffer_position); /* skip over null interface handle*/
-    GetIntFromMessage((const EipUint8** const ) &receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
-    ((EncapsulationData* const ) receive_data)->data_length -= 6; /* the rest is in CPF format*/
+    GetDintFromMessage(
+      (const EipUint8 **const ) &receive_data->current_communication_buffer_position );                 /* skip over null interface handle*/
+    GetIntFromMessage(
+      (const EipUint8 **const ) &receive_data->current_communication_buffer_position );                /* skip over unused timeout value*/
+    ( (EncapsulationData *const ) receive_data )->data_length -= 6; /* the rest is in CPF format*/
 
-    if(kSessionStatusValid == CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
+    if( kSessionStatusValid == CheckRegisteredSessions(receive_data) ) /* see if the EIP session is registered*/
     {
-      return_value = NotifyConnectedCommonPacketFormat(receive_data, originator_address, outgoing_message);
+      return_value = NotifyConnectedCommonPacketFormat(receive_data,
+                                                       originator_address,
+                                                       outgoing_message);
     } else { /* received a package with non registered session handle */
       InitializeENIPMessage(outgoing_message);
-      GenerateEncapsulationHeader(receive_data, 0, receive_data->session_handle, kEncapsulationProtocolInvalidSessionHandle, outgoing_message);
+      GenerateEncapsulationHeader(receive_data,
+                                  0,
+                                  receive_data->session_handle,
+                                  kEncapsulationProtocolInvalidSessionHandle,
+                                  outgoing_message);
       return_value = kEipStatusOkSend; /* TODO: Needs to be here if line with first TODO of this function is adjusted. */
     }
   }
@@ -541,34 +664,50 @@ EipStatus HandleReceivedSendUnitDataCommand(const EncapsulationData *const recei
  *                      kEipStatusOkSend .. success & need to send response
  *                      kEipStatusError .. error
  */
-EipStatus HandleReceivedSendRequestResponseDataCommand(const EncapsulationData *const receive_data, const struct sockaddr *const originator_address,
-    ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedSendRequestResponseDataCommand(
+  const EncapsulationData *const receive_data,
+  const struct sockaddr *const originator_address,
+  ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusOkSend;
-  /* EipStatus*/return_value = kEipStatusOk; /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
+  /* EipStatus*/ return_value = kEipStatusOk; /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
 
   if(receive_data->data_length >= 6) {
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* don't use the data yet */
-    GetDintFromMessage((const EipUint8** const ) &receive_data->current_communication_buffer_position); /* skip over null interface handle*/
-    GetIntFromMessage((const EipUint8** const ) &receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
-    ((EncapsulationData* const ) receive_data)->data_length -= 6; /* the rest is in CPF format*/
+    GetDintFromMessage(
+      (const EipUint8 **const ) &receive_data->current_communication_buffer_position );                 /* skip over null interface handle*/
+    GetIntFromMessage(
+      (const EipUint8 **const ) &receive_data->current_communication_buffer_position );                /* skip over unused timeout value*/
+    ( (EncapsulationData *const ) receive_data )->data_length -= 6; /* the rest is in CPF format*/
 
-    if(kSessionStatusValid == CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
+    if( kSessionStatusValid == CheckRegisteredSessions(receive_data) ) /* see if the EIP session is registered*/
     {
-      return_value = NotifyCommonPacketFormat(receive_data, originator_address, outgoing_message);
+      return_value = NotifyCommonPacketFormat(receive_data,
+                                              originator_address,
+                                              outgoing_message);
     } else { /* received a package with non registered session handle */
       InitializeENIPMessage(outgoing_message);
-      GenerateEncapsulationHeader(receive_data, 0, receive_data->session_handle, kEncapsulationProtocolInvalidSessionHandle, outgoing_message);
+      GenerateEncapsulationHeader(receive_data,
+                                  0,
+                                  receive_data->session_handle,
+                                  kEncapsulationProtocolInvalidSessionHandle,
+                                  outgoing_message);
       return_value = kEipStatusOkSend; /* TODO: Needs to be here if line with first TODO of this function is adjusted. */
     }
   }
   return return_value;
 }
 
-EipStatus HandleReceivedInvalidCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedInvalidCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message) {
 
   /* Encapsulation header */
-  GenerateEncapsulationHeader(receive_data, 0, receive_data->session_handle, kEncapsulationProtocolInvalidCommand, outgoing_message);
+  GenerateEncapsulationHeader(receive_data,
+                              0,
+                              receive_data->session_handle,
+                              kEncapsulationProtocolInvalidCommand,
+                              outgoing_message);
   return kEipStatusOkSend;
 
 }
@@ -605,7 +744,8 @@ int_fast32_t CreateEncapsulationStructure(const EipUint8 *receive_buffer,
   encapsulation_data->session_handle = GetUdintFromMessage(&receive_buffer);
   encapsulation_data->status = GetUdintFromMessage(&receive_buffer);
 
-  memcpy(encapsulation_data->sender_context, receive_buffer, kSenderContextSize);
+  memcpy(encapsulation_data->sender_context, receive_buffer,
+         kSenderContextSize);
   receive_buffer += kSenderContextSize;
   encapsulation_data->options = GetUdintFromMessage(&receive_buffer);
   encapsulation_data->current_communication_buffer_position = (EipUint8*) receive_buffer;
@@ -622,26 +762,30 @@ int_fast32_t CreateEncapsulationStructure(const EipUint8 *receive_buffer,
  *  @return 0 .. Session registered
  *              kInvalidSession .. invalid session -> return unsupported command received
  */
-SessionStatus CheckRegisteredSessions(const EncapsulationData *const receive_data) {
+SessionStatus CheckRegisteredSessions(
+  const EncapsulationData *const receive_data) {
 
   /* Skip the check when fuzzing
-   in order to increase our code coverage
-   we are simply bypassing all the session checks
+     in order to increase our code coverage
+     we are simply bypassing all the session checks
    */
 #ifdef FUZZING_AFL
   return kSessionStatusValid;
 #endif
 
-  if((0 < receive_data->session_handle) && (receive_data->session_handle <=
-  OPENER_NUMBER_OF_SUPPORTED_SESSIONS)) {
-    if(kEipInvalidSocket != g_registered_sessions[receive_data->session_handle - 1]) {
+  if( (0 < receive_data->session_handle) && (receive_data->session_handle <=
+                                             OPENER_NUMBER_OF_SUPPORTED_SESSIONS) )
+  {
+    if(kEipInvalidSocket !=
+       g_registered_sessions[receive_data->session_handle - 1]) {
       return kSessionStatusValid;
     }
   }
   return kSessionStatusInvalid;
 }
 
-void CloseSessionBySessionHandle(const CipConnectionObject *const connection_object) {
+void CloseSessionBySessionHandle(
+  const CipConnectionObject *const connection_object) {
   OPENER_TRACE_INFO("encap.c: Close session by handle\n");
   size_t session_handle = connection_object->associated_encapsulation_session;
   CloseTcpSocket(g_registered_sessions[session_handle - 1]);
@@ -658,7 +802,7 @@ void CloseSession(int socket) {
       CloseClass3ConnectionBasedOnSession(i + 1);
       break;
     }
-  }OPENER_TRACE_INFO("encap.c: Close session done\n");
+  } OPENER_TRACE_INFO("encap.c: Close session done\n");
 }
 
 void RemoveSession(const int socket) {
@@ -669,7 +813,7 @@ void RemoveSession(const int socket) {
       CloseClass3ConnectionBasedOnSession(i + 1);
       break;
     }
-  }OPENER_TRACE_INFO("encap.c: Session removed\n");
+  } OPENER_TRACE_INFO("encap.c: Session removed\n");
 }
 
 void EncapsulationShutDown(void) {
@@ -688,29 +832,37 @@ void ManageEncapsulationMessages(const MilliSeconds elapsed_time) {
       g_delayed_encapsulation_messages[i].time_out -= elapsed_time;
       if(0 >= g_delayed_encapsulation_messages[i].time_out) {
         /* If delay is reached or passed, send the UDP message */
-        sendto(g_delayed_encapsulation_messages[i].socket, (char*) g_delayed_encapsulation_messages[i].outgoing_message.message_buffer,
-          g_delayed_encapsulation_messages[i].outgoing_message.used_message_length, 0, (struct sockaddr*) &(g_delayed_encapsulation_messages[i].receiver),
-          sizeof(struct sockaddr));
+        sendto( g_delayed_encapsulation_messages[i].socket,
+                (char *) g_delayed_encapsulation_messages[i].outgoing_message.message_buffer,
+                g_delayed_encapsulation_messages[i].outgoing_message.used_message_length,
+                0,
+                (struct sockaddr *) &(g_delayed_encapsulation_messages[i].
+                                      receiver),
+                sizeof(struct sockaddr) );
         g_delayed_encapsulation_messages[i].socket = kEipInvalidSocket;
       }
     }
   }
 }
 
-void CloseEncapsulationSessionBySockAddr(const CipConnectionObject *const connection_object) {
+void CloseEncapsulationSessionBySockAddr(
+  const CipConnectionObject *const connection_object) {
   for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
     if(kEipInvalidSocket != g_registered_sessions[i]) {
       struct sockaddr_in encapsulation_session_addr = { 0 };
       socklen_t addrlength = sizeof(encapsulation_session_addr);
-      if(getpeername(g_registered_sessions[i], (struct sockaddr*) &encapsulation_session_addr, &addrlength) < 0) { /* got error */
+      if(getpeername(g_registered_sessions[i],
+                     (struct sockaddr *) &encapsulation_session_addr,
+                     &addrlength) < 0) {                                                                           /* got error */
         int error_code = GetSocketErrorNumber();
         char *error_message = GetErrorMessage(error_code);
         OPENER_TRACE_ERR(
-            "encap.c: error on getting peer name on closing session: %d - %s\n",
-            error_code, error_message);
+          "encap.c: error on getting peer name on closing session: %d - %s\n",
+          error_code, error_message);
         FreeErrorMessage(error_message);
       }
-      if(encapsulation_session_addr.sin_addr.s_addr == connection_object->originator_address.sin_addr.s_addr) {
+      if(encapsulation_session_addr.sin_addr.s_addr ==
+         connection_object->originator_address.sin_addr.s_addr) {
         CloseSession(g_registered_sessions[i]);
       }
     }
@@ -730,8 +882,10 @@ void CloseClass3ConnectionBasedOnSession(size_t encapsulation_session_handle) {
   DoublyLinkedListNode *node = connection_list.first;
   while(NULL != node) {
     CipConnectionObject *connection_object = node->data;
-    if(kConnectionObjectTransportClassTriggerTransportClass3 == ConnectionObjectGetTransportClassTriggerTransportClass(connection_object)
-      && connection_object->associated_encapsulation_session == encapsulation_session_handle) {
+    if(kConnectionObjectTransportClassTriggerTransportClass3 ==
+       ConnectionObjectGetTransportClassTriggerTransportClass(connection_object)
+       && connection_object->associated_encapsulation_session ==
+       encapsulation_session_handle) {
       connection_object->connection_close_function(connection_object);
     }
     node = node->next;

+ 25 - 10
source/src/enet_encap/encap.h

@@ -83,16 +83,20 @@ size_t GetSessionFromSocket(const int socket_handle);
 
 void RemoveSession(const int socket);
 
-void CloseSessionBySessionHandle(const CipConnectionObject *const connection_object);
+void CloseSessionBySessionHandle(
+  const CipConnectionObject *const connection_object);
 
-void CloseEncapsulationSessionBySockAddr(const CipConnectionObject *const connection_object);
+void CloseEncapsulationSessionBySockAddr(
+  const CipConnectionObject *const connection_object);
 
 void CloseClass3ConnectionBasedOnSession(size_t encapsulation_session_handle);
 
 /* No reason to use this functions outside the encapsulation layer, they are here for testing */
 typedef struct enip_message ENIPMessage;
 
-void EncapsulateListIdentityResponseMessage(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+void EncapsulateListIdentityResponseMessage(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message);
 
 int_fast32_t CreateEncapsulationStructure(const EipUint8 *receive_buffer,
                                           size_t receive_buffer_length,
@@ -100,16 +104,27 @@ int_fast32_t CreateEncapsulationStructure(const EipUint8 *receive_buffer,
 
 void SkipEncapsulationHeader(ENIPMessage *const outgoing_message);
 
-void GenerateEncapsulationHeader(const EncapsulationData *const receive_data, const size_t command_specific_data_length, const size_t session_handle,
-    const EncapsulationProtocolErrorCode encapsulation_protocol_status, ENIPMessage *const outgoing_message);
+void GenerateEncapsulationHeader(const EncapsulationData *const receive_data,
+                                 const size_t command_specific_data_length,
+                                 const size_t session_handle,
+                                 const EncapsulationProtocolErrorCode encapsulation_protocol_status,
+                                 ENIPMessage *const outgoing_message);
 
-void HandleReceivedListServicesCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+void HandleReceivedListServicesCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message);
 
-void HandleReceivedListInterfacesCommand(const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+void HandleReceivedListInterfacesCommand(
+  const EncapsulationData *const receive_data,
+  ENIPMessage *const outgoing_message);
 
-void HandleReceivedRegisterSessionCommand(int socket, const EncapsulationData *const receive_data, ENIPMessage *const outgoing_message);
+void HandleReceivedRegisterSessionCommand(int socket,
+                                          const EncapsulationData *const receive_data,
+                                          ENIPMessage *const outgoing_message);
 
-EipStatus HandleReceivedSendRequestResponseDataCommand(const EncapsulationData *const receive_data, const struct sockaddr *const originator_address,
-    ENIPMessage *const outgoing_message);
+EipStatus HandleReceivedSendRequestResponseDataCommand(
+  const EncapsulationData *const receive_data,
+  const struct sockaddr *const originator_address,
+  ENIPMessage *const outgoing_message);
 
 #endif /* OPENER_ENCAP_H_ */

+ 4 - 4
source/src/ports/MINGW/main.c

@@ -66,7 +66,7 @@ int main(int argc,
   /* Fetch MAC address from the platform. This tests also if the interface
    *  is present. */
   uint8_t iface_mac[6];
-  if (kEipStatusError == IfaceGetMacAddress(arg[1], iface_mac) ) {
+  if ( kEipStatusError == IfaceGetMacAddress(arg[1], iface_mac) ) {
     printf("Network interface %s not found.\n", arg[1]);
     exit(EXIT_FAILURE);
   }
@@ -79,7 +79,7 @@ int main(int argc,
    *  16 bits of the connection id. Here we use random number approach, first seed
    *  the PRNG to ensure we don't get the same value on every startup.
    */
-  srand(time(NULL));
+  srand( time(NULL) );
   EipUint16 unique_connection_id = rand();
 
   /* Setup the CIP Layer. All objects are initialized with the default
@@ -99,7 +99,7 @@ int main(int argc,
    *  After that any NV data values are loaded to change the attribute contents
    *  to the stored configuration.
    */
-  if (kEipStatusError == NvdataLoad() ) {
+  if ( kEipStatusError == NvdataLoad() ) {
     OPENER_TRACE_WARN("Loading of some NV data failed. Maybe the first start?\n");
   }
 
@@ -143,7 +143,7 @@ int main(int argc,
 
 
   /* The network initialization of the EIP stack for the NetworkHandler. */
-  if (!g_end_stack && kEipStatusOk == NetworkHandlerInitialize() ) {
+  if ( !g_end_stack && kEipStatusOk == NetworkHandlerInitialize() ) {
 
     (void) executeEventLoop(NULL);
 

+ 13 - 13
source/src/ports/MINGW/networkconfig.c

@@ -96,7 +96,7 @@ static DWORD ConvertToIndexFromFakeAlias(const char *iface,
 
   (void) mbstowcs(p_if_alias, iface, wc_cnt);
   DWORD cnv_status = ConvertInterfaceAliasToLuid(p_if_alias, &if_luid);
-  if(NETIO_SUCCESS(cnv_status) ) {
+  if( NETIO_SUCCESS(cnv_status) ) {
     cnv_status = ConvertInterfaceLuidToIndex(&if_luid, iface_idx);
   }
   FREE(p_if_alias);
@@ -266,7 +266,7 @@ EipStatus IfaceGetMacAddress(const char *iface,
                              uint8_t *physical_address) {
   ULONG iface_idx;
 
-  if(kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
+  if( kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
     return kEipStatusError;
   }
 
@@ -275,7 +275,7 @@ EipStatus IfaceGetMacAddress(const char *iface,
                       GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER |
                       GAA_FLAG_SKIP_FRIENDLY_NAME;
   PIP_ADAPTER_ADDRESSES p_addr_table = NULL;
-  if(kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
+  if( kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
     return kEipStatusError;
   }
 
@@ -311,7 +311,7 @@ EipStatus IfaceGetConfiguration(const char *iface,
                                 CipTcpIpInterfaceConfiguration *iface_cfg) {
   ULONG iface_idx;
 
-  if(kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
+  if( kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
     return kEipStatusError;
   }
 
@@ -319,7 +319,7 @@ EipStatus IfaceGetConfiguration(const char *iface,
   const ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
                       GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAG_INCLUDE_PREFIX;
   PIP_ADAPTER_ADDRESSES p_addr_table = NULL;
-  if(kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
+  if( kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
     return kEipStatusError;
   }
 
@@ -349,7 +349,7 @@ EipStatus IfaceGetConfiguration(const char *iface,
         PIP_ADAPTER_PREFIX pPrefix = p_addr_entry->FirstPrefix;
         if(NULL != pPrefix) {
           local_cfg.network_mask =
-            htonl(0xffffffff << (32U - pPrefix->PrefixLength) );
+            htonl( 0xffffffff << (32U - pPrefix->PrefixLength) );
         }
       }
       {
@@ -404,7 +404,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
                          volatile int *const abort_wait) {
   ULONG iface_idx;
 
-  if(kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
+  if( kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
     return kEipStatusError;
   }
 
@@ -445,10 +445,10 @@ EipStatus IfaceWaitForIp(const char *const iface,
       /* Search entry matching the interface index and determine IP address. */
       for(int i = 0; i < (int) pmib_ipaddr_table->dwNumEntries; i++) {
         if(pmib_ipaddr_table->table[i].dwIndex == iface_idx) {
-          if(0 ==
-             (pmib_ipaddr_table->table[i].wType &
-              (MIB_IPADDR_DELETED | MIB_IPADDR_DISCONNECTED |
-               MIB_IPADDR_TRANSIENT) ) ) {
+          if( 0 ==
+              ( pmib_ipaddr_table->table[i].wType &
+                (MIB_IPADDR_DELETED | MIB_IPADDR_DISCONNECTED |
+                 MIB_IPADDR_TRANSIENT) ) ) {
             ipaddr = pmib_ipaddr_table->table[i].dwAddr;
           }
         }
@@ -458,7 +458,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
         --timeout;
       }
     } while( (0 == ipaddr) && (0 != timeout) && (0 == *abort_wait) &&
-             (0 == SleepEx(WAIT_CYCLE_MS, FALSE) ) );
+             ( 0 == SleepEx(WAIT_CYCLE_MS, FALSE) ) );
 
     OPENER_TRACE_INFO("IP=%08" PRIx32 ", timeout=%d\n",
                       (uint32_t)ntohl(ipaddr),
@@ -489,7 +489,7 @@ void GetHostName(CipString *hostname) {
   }
 
   char name_buf[HOST_NAME_MAX] = "";
-  err = gethostname(name_buf, sizeof(name_buf) );
+  err = gethostname( name_buf, sizeof(name_buf) );
   if(0 != err) {
     int error_code = GetSocketErrorNumber();
     char *error_message = GetErrorMessage(error_code);

+ 5 - 5
source/src/ports/MINGW/networkhandler.c

@@ -57,9 +57,9 @@ int SetQosOnSocket(int socket,
    *  Note that the DSCP value, if placed directly in the ToS field
    *  in the IP header, must be shifted left 2 bits. */
   DWORD set_tos = qos_value << 2;
-  return setsockopt(socket,
-                    IPPROTO_IP,
-                    IP_TOS,
-                    (char *)&set_tos,
-                    sizeof(set_tos) );
+  return setsockopt( socket,
+                     IPPROTO_IP,
+                     IP_TOS,
+                     (char *)&set_tos,
+                     sizeof(set_tos) );
 }

+ 137 - 66
source/src/ports/MINGW/sample_application/ethlinkcbs.c

@@ -52,66 +52,138 @@ static CipUdint media_calls[OPENER_ETHLINK_INSTANCE_CNT];
 /* This is meant as debugging aid and to check if the individual counter     */
 /*  value is sent at the right position in the Get* service response.        */
 
-#define MAKE_CNTR(inst, attr, idx, cnt) ((10000000U * inst) + (100000U * attr) + (1000U * idx) + cnt)
+#define MAKE_CNTR(inst, attr, idx, \
+                  cnt) ( (10000000U * inst) + (100000U * attr) + (1000U * idx) + \
+                         cnt )
 
 EipStatus EthLnkPreGetCallback
 (
   CipInstance *const instance,
   CipAttributeStruct *const attribute,
   CipByte service
-)
-{
+) {
   bool hadAction = true;
   EipStatus status = kEipStatusOk;
 
   CipUint attr_no = attribute->attribute_number;
   /* ATTENTION: Array indices run from 0..(N-1), instance numbers from 1..N */
   CipUdint inst_no  = instance->instance_number;
-  unsigned idx = inst_no-1;
+  unsigned idx = inst_no - 1;
   switch (attr_no) {
-  case 4: {
-    CipEthernetLinkInterfaceCounters *p_iface_cntrs = &g_ethernet_link[idx].interface_cntrs;
-
-    ++iface_calls[idx];  /* Count successful calls */
-    p_iface_cntrs->ul.in_octets   = MAKE_CNTR(inst_no, attr_no,  0, iface_calls[idx]);
-    p_iface_cntrs->ul.in_ucast    = MAKE_CNTR(inst_no, attr_no,  1, iface_calls[idx]);
-    p_iface_cntrs->ul.in_nucast   = MAKE_CNTR(inst_no, attr_no,  2, iface_calls[idx]);
-    p_iface_cntrs->ul.in_discards = MAKE_CNTR(inst_no, attr_no,  3, iface_calls[idx]);
-    p_iface_cntrs->ul.in_errors   = MAKE_CNTR(inst_no, attr_no,  4, iface_calls[idx]);
-    p_iface_cntrs->ul.in_unknown_protos = MAKE_CNTR(inst_no, attr_no, 5, iface_calls[idx]);
-    p_iface_cntrs->ul.out_octets  = MAKE_CNTR(inst_no, attr_no,  6, iface_calls[idx]);
-    p_iface_cntrs->ul.out_ucast   = MAKE_CNTR(inst_no, attr_no,  7, iface_calls[idx]);
-    p_iface_cntrs->ul.out_nucast  = MAKE_CNTR(inst_no, attr_no,  8, iface_calls[idx]);
-    p_iface_cntrs->ul.out_discards = MAKE_CNTR(inst_no, attr_no, 9, iface_calls[idx]);
-    p_iface_cntrs->ul.out_errors  = MAKE_CNTR(inst_no, attr_no, 10, iface_calls[idx]);
-    break;
-  }
-  case 5: {
-    CipEthernetLinkMediaCounters *p_media_cntrs = &g_ethernet_link[idx].media_cntrs;
-
-    ++media_calls[idx];  /* Count successful calls */
-    /* The 1 != mediaCalls[idx] is a concession to the conformance test tool that
-     *  expects the media counters to be zero after a GetAndClear service.
-     * This way we always transmit zeros after reset or a GetAndClear service. */
-    if (1 != media_calls[idx]) {
-      p_media_cntrs->ul.align_errs    = MAKE_CNTR(inst_no, attr_no,  0, media_calls[idx]);
-      p_media_cntrs->ul.fcs_errs      = MAKE_CNTR(inst_no, attr_no,  1, media_calls[idx]);
-      p_media_cntrs->ul.single_coll   = MAKE_CNTR(inst_no, attr_no,  2, media_calls[idx]);
-      p_media_cntrs->ul.multi_coll    = MAKE_CNTR(inst_no, attr_no,  3, media_calls[idx]);
-      p_media_cntrs->ul.sqe_test_errs = MAKE_CNTR(inst_no, attr_no,  4, media_calls[idx]);
-      p_media_cntrs->ul.def_trans     = MAKE_CNTR(inst_no, attr_no,  5, media_calls[idx]);
-      p_media_cntrs->ul.late_coll     = MAKE_CNTR(inst_no, attr_no,  6, media_calls[idx]);
-      p_media_cntrs->ul.exc_coll      = MAKE_CNTR(inst_no, attr_no,  7, media_calls[idx]);
-      p_media_cntrs->ul.mac_tx_errs   = MAKE_CNTR(inst_no, attr_no,  8, media_calls[idx]);
-      p_media_cntrs->ul.crs_errs      = MAKE_CNTR(inst_no, attr_no,  9, media_calls[idx]);
-      p_media_cntrs->ul.frame_too_long= MAKE_CNTR(inst_no, attr_no, 10, media_calls[idx]);
-      p_media_cntrs->ul.mac_rx_errs   = MAKE_CNTR(inst_no, attr_no, 11, media_calls[idx]);
+    case 4: {
+      CipEthernetLinkInterfaceCounters *p_iface_cntrs =
+        &g_ethernet_link[idx].interface_cntrs;
+
+      ++iface_calls[idx]; /* Count successful calls */
+      p_iface_cntrs->ul.in_octets   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                0,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_ucast    = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                1,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_nucast   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                2,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_discards = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                3,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_errors   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                4,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_unknown_protos = MAKE_CNTR(inst_no,
+                                                      attr_no,
+                                                      5,
+                                                      iface_calls[idx]);
+      p_iface_cntrs->ul.out_octets  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                6,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_ucast   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                7,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_nucast  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                8,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_discards = MAKE_CNTR(inst_no,
+                                                 attr_no,
+                                                 9,
+                                                 iface_calls[idx]);
+      p_iface_cntrs->ul.out_errors  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                10,
+                                                iface_calls[idx]);
+      break;
     }
-    break;
-  }
-  default:
-    hadAction = false;
-    break;
+    case 5: {
+      CipEthernetLinkMediaCounters *p_media_cntrs =
+        &g_ethernet_link[idx].media_cntrs;
+
+      ++media_calls[idx]; /* Count successful calls */
+      /* The 1 != mediaCalls[idx] is a concession to the conformance test tool that
+       *  expects the media counters to be zero after a GetAndClear service.
+       * This way we always transmit zeros after reset or a GetAndClear service. */
+      if (1 != media_calls[idx]) {
+        p_media_cntrs->ul.align_errs    = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    0,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.fcs_errs      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    1,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.single_coll   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    2,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.multi_coll    = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    3,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.sqe_test_errs = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    4,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.def_trans     = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    5,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.late_coll     = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    6,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.exc_coll      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    7,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.mac_tx_errs   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    8,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.crs_errs      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    9,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.frame_too_long = MAKE_CNTR(inst_no,
+                                                     attr_no,
+                                                     10,
+                                                     media_calls[idx]);
+        p_media_cntrs->ul.mac_rx_errs   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    11,
+                                                    media_calls[idx]);
+      }
+      break;
+    }
+    default:
+      hadAction = false;
+      break;
   }
 
   if (hadAction) {
@@ -131,12 +203,11 @@ EipStatus EthLnkPostGetCallback
   CipInstance *const instance,
   CipAttributeStruct *const attribute,
   CipByte service
-)
-{
-  CipUdint  inst_no = instance->instance_number;
+) {
+  CipUdint inst_no = instance->instance_number;
   EipStatus status = kEipStatusOk;
 
-  if (kEthLinkGetAndClear == (service & 0x7f)) {
+  if ( kEthLinkGetAndClear == (service & 0x7f) ) {
     OPENER_TRACE_INFO(
       "Eth Link PostCallback: %s, i %" PRIu32 ", a %" PRIu16 ", s %" PRIu8 "\n",
       instance->cip_class->class_name,
@@ -146,22 +217,22 @@ EipStatus EthLnkPostGetCallback
     /* Clear the instance specific object counters. In this dummy function we only
      *  clear our GetAttributeSingle PreCallback execution counters. */
     switch (attribute->attribute_number) {
-    case 4:
-      iface_calls[inst_no-1] = 0U;
-      break;
-    case 5:
-      media_calls[inst_no-1] = 0U;
-      /* This is a concession to the conformance test tool that expects
-       *  the media counters to be zero after a GetAndClear service. */
-      for (int idx = 0; idx < 12; ++idx) {
-        g_ethernet_link[inst_no-1].media_cntrs.cntr32[idx] = 0U;
-      }
-      break;
-    default:
-      OPENER_TRACE_INFO(
-        "Wrong attribute number %" PRIu16 " in GetAndClear callback\n",
-        attribute->attribute_number);
-      break;
+      case 4:
+        iface_calls[inst_no - 1] = 0U;
+        break;
+      case 5:
+        media_calls[inst_no - 1] = 0U;
+        /* This is a concession to the conformance test tool that expects
+         *  the media counters to be zero after a GetAndClear service. */
+        for (int idx = 0; idx < 12; ++idx) {
+          g_ethernet_link[inst_no - 1].media_cntrs.cntr32[idx] = 0U;
+        }
+        break;
+      default:
+        OPENER_TRACE_INFO(
+          "Wrong attribute number %" PRIu16 " in GetAndClear callback\n",
+          attribute->attribute_number);
+        break;
     }
   }
   return status;

+ 6 - 6
source/src/ports/MINGW/sample_application/ethlinkcbs.h

@@ -26,16 +26,16 @@
 
 EipStatus EthLnkPreGetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 EipStatus EthLnkPostGetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 

+ 1 - 1
source/src/ports/MINGW/sample_application/opener_user_conf.h

@@ -206,7 +206,7 @@ static const MilliSeconds kOpenerTimerTickInMilliSeconds = 10;
 /* If you still want assertions to stop execution but without tracing,
  *  use the following */
         #define OPENER_ASSERT(assertion)                    \
-  do { if(!(assertion) ) { while(1) {} } } while (0)
+  do { if( !(assertion) ) { while(1) {} } } while (0)
     #elif 0
 /* Even for debug builds remove assertion. May solicit unused variable
  *  warnings. */

+ 6 - 6
source/src/ports/POSIX/main.c

@@ -79,7 +79,7 @@ int main(int argc,
   /* Fetch MAC address from the platform. This tests also if the interface
    *  is present. */
   uint8_t iface_mac[6];
-  if(kEipStatusError == IfaceGetMacAddress(arg[1], iface_mac) ) {
+  if( kEipStatusError == IfaceGetMacAddress(arg[1], iface_mac) ) {
     printf("Network interface %s not found.\n", arg[1]);
     exit(EXIT_FAILURE);
   }
@@ -92,7 +92,7 @@ int main(int argc,
    *  16 bits of the connection id. Here we use random number approach, first seed
    *  the PRNG to ensure we don't get the same value on every startup.
    */
-  srand(time(NULL));
+  srand( time(NULL) );
   EipUint16 unique_connection_id = rand();
 
   /* Setup the CIP Layer. All objects are initialized with the default
@@ -118,7 +118,7 @@ int main(int argc,
    *  After that any NV data values are loaded to change the attribute contents
    *  to the stored configuration.
    */
-  if(kEipStatusError == NvdataLoad() ) {
+  if( kEipStatusError == NvdataLoad() ) {
     OPENER_TRACE_WARN("Loading of some NV data failed. Maybe the first start?\n");
   }
 
@@ -163,7 +163,7 @@ int main(int argc,
   }
 
   /* The network initialization of the EIP stack for the NetworkHandler. */
-  if(!g_end_stack && kEipStatusOk == NetworkHandlerInitialize() ) {
+  if( !g_end_stack && kEipStatusOk == NetworkHandlerInitialize() ) {
 #ifdef OPENER_RT
     int ret;
 
@@ -256,7 +256,7 @@ static void *executeEventLoop(void *pthread_arg) {
 
   /* The event loop. Put other processing you need done continually in here */
   while(!g_end_stack) {
-    if(kEipStatusOk != NetworkHandlerProcessCyclic() ) {
+    if( kEipStatusOk != NetworkHandlerProcessCyclic() ) {
       OPENER_TRACE_ERR("Error in NetworkHandler loop! Exiting OpENer!\n");
       break;
     }
@@ -274,7 +274,7 @@ static void fuzzHandlePacketFlow(void) {
   ENIPMessage outgoing_message;
 
   /* AFL persistent mode */
-  while(__AFL_LOOP(100000) ) {
+  while( __AFL_LOOP(100000) ) {
     /* Read input from STDIN and enter the handle receive flow */
     memset(buff, 0, 512);
     ssize_t received_size = read(STDIN_FILENO, buff, 512);

+ 16 - 16
source/src/ports/POSIX/networkconfig.c

@@ -30,7 +30,7 @@ EipStatus IfaceGetMacAddress(const char *iface,
   size_t if_name_len = strlen(iface);
   EipStatus status = kEipStatusError;
 
-  if(if_name_len < sizeof(ifr.ifr_name) ) {
+  if( if_name_len < sizeof(ifr.ifr_name) ) {
     memcpy(ifr.ifr_name, iface, if_name_len);
     ifr.ifr_name[if_name_len] = '\0';
 
@@ -54,7 +54,7 @@ static EipStatus GetIpAndNetmaskFromInterface(const char *iface,
 {
   struct ifreq ifr;
   size_t if_name_len = strlen(iface);
-  if(if_name_len < sizeof(ifr.ifr_name) ) {
+  if( if_name_len < sizeof(ifr.ifr_name) ) {
     memcpy(ifr.ifr_name, iface, if_name_len);
     ifr.ifr_name[if_name_len] = 0;
   } else {
@@ -103,11 +103,11 @@ static EipStatus GetGatewayFromRoute(const char *iface,
   } else {
     char *needle_start;
     file_buffer[0] = '\0'; /* To enter the while loop */
-    while(NULL ==
-          (needle_start =
-             strstr(file_buffer,
-                    iface) ) &&
-          fgets(file_buffer, sizeof(file_buffer), file_handle) ) {
+    while( NULL ==
+           ( needle_start =
+               strstr(file_buffer,
+                      iface) ) &&
+           fgets(file_buffer, sizeof(file_buffer), file_handle) ) {
       /* Skip each non matching line */
     }
     fclose(file_handle);
@@ -146,8 +146,8 @@ static EipStatus GetGatewayFromRoute(const char *iface,
 #if defined(OPENER_TRACE_ENABLED)
   {
     char ip_str[INET_ADDRSTRLEN];
-    OPENER_TRACE_INFO("Decoded gateway: %s\n",
-                      inet_ntop(AF_INET, &gateway, ip_str, sizeof ip_str) );
+    OPENER_TRACE_INFO( "Decoded gateway: %s\n",
+                       inet_ntop(AF_INET, &gateway, ip_str, sizeof ip_str) );
   }
 #endif
 
@@ -206,8 +206,8 @@ static EipStatus GetDnsInfoFromResolvConf(
       /* fall through */
       case 's':
         strtok_r(line, " \t", &strtok_key);
-        if(0 == strcmp("search", line) || 0 == strcmp("domain", line) ) {
-          if(NULL != (value_string = strtok_r(NULL, " \t", &strtok_key) ) ) {
+        if( 0 == strcmp("search", line) || 0 == strcmp("domain", line) ) {
+          if( NULL != ( value_string = strtok_r(NULL, " \t", &strtok_key) ) ) {
             SetCipStringByCstr(&iface_cfg->domain_name, value_string);
           }
         }
@@ -215,8 +215,8 @@ static EipStatus GetDnsInfoFromResolvConf(
 
       case 'n':
         strtok_r(line, " \t", &strtok_key);
-        if(0 == strcmp("nameserver", line) ) {
-          if(NULL != (value_string = strtok_r(NULL, " \t", &strtok_key) ) ) {
+        if( 0 == strcmp("nameserver", line) ) {
+          if( NULL != ( value_string = strtok_r(NULL, " \t", &strtok_key) ) ) {
             inet_pton(AF_INET, value_string, dns);
             /* Adjust destination for next nameserver occurrence. */
             if(dns != &dmy_dns) {
@@ -284,7 +284,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
   int rc;
 
   size_t if_name_len = strlen(iface);
-  if(if_name_len < sizeof(ifr.ifr_name) ) {
+  if( if_name_len < sizeof(ifr.ifr_name) ) {
     memcpy(ifr.ifr_name, iface, if_name_len);
     ifr.ifr_name[if_name_len] = 0;
   } else {
@@ -301,7 +301,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
     do {
       ipaddr = 0U;
 
-      if(0 == (rc = ioctl(fd, SIOCGIFADDR, &ifr) ) ) {
+      if( 0 == ( rc = ioctl(fd, SIOCGIFADDR, &ifr) ) ) {
         ipaddr = ( (struct sockaddr_in *) &ifr.ifr_addr )->sin_addr.s_addr;
       } else {
         if(EADDRNOTAVAIL != errno) {
@@ -312,7 +312,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
         --timeout;
       }
     } while( (0 == ipaddr) && (0 != timeout) && (0 == *p_abort_wait) &&
-             (0 == nanosleep_simple32(WAIT_CYCLE_NS) ) );
+             ( 0 == nanosleep_simple32(WAIT_CYCLE_NS) ) );
 
     OPENER_TRACE_INFO("ip=%08x, timeout=%d\n", ntohl(ipaddr), timeout);
     close(fd);

+ 2 - 2
source/src/ports/POSIX/networkhandler.c

@@ -39,7 +39,7 @@ EipStatus NetworkHandlerInitializePlatform(void) {
 }
 
 void ShutdownSocketPlatform(int socket_handle) {
-  if(0 != shutdown(socket_handle, SHUT_RDWR) ) {
+  if( 0 != shutdown(socket_handle, SHUT_RDWR) ) {
     int error_code = GetSocketErrorNumber();
     char *error_message = GetErrorMessage(error_code);
     OPENER_TRACE_ERR("Failed shutdown() socket %d - Error Code: %d - %s\n",
@@ -66,5 +66,5 @@ int SetQosOnSocket(const int socket,
    *  Note that the DSCP value, if placed directly in the ToS field
    *  in the IP header, must be shifted left 2 bits. */
   int set_tos = qos_value << 2;
-  return setsockopt(socket, IPPROTO_IP, IP_TOS, &set_tos, sizeof(set_tos) );
+  return setsockopt( socket, IPPROTO_IP, IP_TOS, &set_tos, sizeof(set_tos) );
 }

+ 137 - 66
source/src/ports/POSIX/sample_application/ethlinkcbs.c

@@ -52,66 +52,138 @@ static CipUdint media_calls[OPENER_ETHLINK_INSTANCE_CNT];
 /* This is meant as debugging aid and to check if the individual counter     */
 /*  value is sent at the right position in the Get* service response.        */
 
-#define MAKE_CNTR(inst, attr, idx, cnt) ((10000000U * inst) + (100000U * attr) + (1000U * idx) + cnt)
+#define MAKE_CNTR(inst, attr, idx, \
+                  cnt) ( (10000000U * inst) + (100000U * attr) + (1000U * idx) + \
+                         cnt )
 
 EipStatus EthLnkPreGetCallback
 (
   CipInstance *const instance,
   CipAttributeStruct *const attribute,
   CipByte service
-)
-{
+) {
   bool hadAction = true;
   EipStatus status = kEipStatusOk;
 
   CipUint attr_no = attribute->attribute_number;
   /* ATTENTION: Array indices run from 0..(N-1), instance numbers from 1..N */
   CipUdint inst_no  = instance->instance_number;
-  unsigned idx = inst_no-1;
+  unsigned idx = inst_no - 1;
   switch (attr_no) {
-  case 4: {
-    CipEthernetLinkInterfaceCounters *p_iface_cntrs = &g_ethernet_link[idx].interface_cntrs;
-
-    ++iface_calls[idx];  /* Count successful calls */
-    p_iface_cntrs->ul.in_octets   = MAKE_CNTR(inst_no, attr_no,  0, iface_calls[idx]);
-    p_iface_cntrs->ul.in_ucast    = MAKE_CNTR(inst_no, attr_no,  1, iface_calls[idx]);
-    p_iface_cntrs->ul.in_nucast   = MAKE_CNTR(inst_no, attr_no,  2, iface_calls[idx]);
-    p_iface_cntrs->ul.in_discards = MAKE_CNTR(inst_no, attr_no,  3, iface_calls[idx]);
-    p_iface_cntrs->ul.in_errors   = MAKE_CNTR(inst_no, attr_no,  4, iface_calls[idx]);
-    p_iface_cntrs->ul.in_unknown_protos = MAKE_CNTR(inst_no, attr_no, 5, iface_calls[idx]);
-    p_iface_cntrs->ul.out_octets  = MAKE_CNTR(inst_no, attr_no,  6, iface_calls[idx]);
-    p_iface_cntrs->ul.out_ucast   = MAKE_CNTR(inst_no, attr_no,  7, iface_calls[idx]);
-    p_iface_cntrs->ul.out_nucast  = MAKE_CNTR(inst_no, attr_no,  8, iface_calls[idx]);
-    p_iface_cntrs->ul.out_discards = MAKE_CNTR(inst_no, attr_no, 9, iface_calls[idx]);
-    p_iface_cntrs->ul.out_errors  = MAKE_CNTR(inst_no, attr_no, 10, iface_calls[idx]);
-    break;
-  }
-  case 5: {
-    CipEthernetLinkMediaCounters *p_media_cntrs = &g_ethernet_link[idx].media_cntrs;
-
-    ++media_calls[idx];  /* Count successful calls */
-    /* The 1 != mediaCalls[idx] is a concession to the conformance test tool that
-     *  expects the media counters to be zero after a GetAndClear service.
-     * This way we always transmit zeros after reset or a GetAndClear service. */
-    if (1 != media_calls[idx]) {
-      p_media_cntrs->ul.align_errs    = MAKE_CNTR(inst_no, attr_no,  0, media_calls[idx]);
-      p_media_cntrs->ul.fcs_errs      = MAKE_CNTR(inst_no, attr_no,  1, media_calls[idx]);
-      p_media_cntrs->ul.single_coll   = MAKE_CNTR(inst_no, attr_no,  2, media_calls[idx]);
-      p_media_cntrs->ul.multi_coll    = MAKE_CNTR(inst_no, attr_no,  3, media_calls[idx]);
-      p_media_cntrs->ul.sqe_test_errs = MAKE_CNTR(inst_no, attr_no,  4, media_calls[idx]);
-      p_media_cntrs->ul.def_trans     = MAKE_CNTR(inst_no, attr_no,  5, media_calls[idx]);
-      p_media_cntrs->ul.late_coll     = MAKE_CNTR(inst_no, attr_no,  6, media_calls[idx]);
-      p_media_cntrs->ul.exc_coll      = MAKE_CNTR(inst_no, attr_no,  7, media_calls[idx]);
-      p_media_cntrs->ul.mac_tx_errs   = MAKE_CNTR(inst_no, attr_no,  8, media_calls[idx]);
-      p_media_cntrs->ul.crs_errs      = MAKE_CNTR(inst_no, attr_no,  9, media_calls[idx]);
-      p_media_cntrs->ul.frame_too_long= MAKE_CNTR(inst_no, attr_no, 10, media_calls[idx]);
-      p_media_cntrs->ul.mac_rx_errs   = MAKE_CNTR(inst_no, attr_no, 11, media_calls[idx]);
+    case 4: {
+      CipEthernetLinkInterfaceCounters *p_iface_cntrs =
+        &g_ethernet_link[idx].interface_cntrs;
+
+      ++iface_calls[idx]; /* Count successful calls */
+      p_iface_cntrs->ul.in_octets   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                0,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_ucast    = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                1,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_nucast   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                2,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_discards = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                3,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_errors   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                4,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_unknown_protos = MAKE_CNTR(inst_no,
+                                                      attr_no,
+                                                      5,
+                                                      iface_calls[idx]);
+      p_iface_cntrs->ul.out_octets  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                6,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_ucast   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                7,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_nucast  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                8,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_discards = MAKE_CNTR(inst_no,
+                                                 attr_no,
+                                                 9,
+                                                 iface_calls[idx]);
+      p_iface_cntrs->ul.out_errors  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                10,
+                                                iface_calls[idx]);
+      break;
     }
-    break;
-  }
-  default:
-    hadAction = false;
-    break;
+    case 5: {
+      CipEthernetLinkMediaCounters *p_media_cntrs =
+        &g_ethernet_link[idx].media_cntrs;
+
+      ++media_calls[idx]; /* Count successful calls */
+      /* The 1 != mediaCalls[idx] is a concession to the conformance test tool that
+       *  expects the media counters to be zero after a GetAndClear service.
+       * This way we always transmit zeros after reset or a GetAndClear service. */
+      if (1 != media_calls[idx]) {
+        p_media_cntrs->ul.align_errs    = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    0,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.fcs_errs      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    1,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.single_coll   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    2,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.multi_coll    = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    3,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.sqe_test_errs = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    4,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.def_trans     = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    5,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.late_coll     = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    6,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.exc_coll      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    7,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.mac_tx_errs   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    8,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.crs_errs      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    9,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.frame_too_long = MAKE_CNTR(inst_no,
+                                                     attr_no,
+                                                     10,
+                                                     media_calls[idx]);
+        p_media_cntrs->ul.mac_rx_errs   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    11,
+                                                    media_calls[idx]);
+      }
+      break;
+    }
+    default:
+      hadAction = false;
+      break;
   }
 
   if (hadAction) {
@@ -131,12 +203,11 @@ EipStatus EthLnkPostGetCallback
   CipInstance *const instance,
   CipAttributeStruct *const attribute,
   CipByte service
-)
-{
-  CipUdint  inst_no = instance->instance_number;
+) {
+  CipUdint inst_no = instance->instance_number;
   EipStatus status = kEipStatusOk;
 
-  if (kEthLinkGetAndClear == (service & 0x7f)) {
+  if ( kEthLinkGetAndClear == (service & 0x7f) ) {
     OPENER_TRACE_INFO(
       "Eth Link PostCallback: %s, i %" PRIu32 ", a %" PRIu16 ", s %" PRIu8 "\n",
       instance->cip_class->class_name,
@@ -146,22 +217,22 @@ EipStatus EthLnkPostGetCallback
     /* Clear the instance specific object counters. In this dummy function we only
      *  clear our GetAttributeSingle PreCallback execution counters. */
     switch (attribute->attribute_number) {
-    case 4:
-      iface_calls[inst_no-1] = 0U;
-      break;
-    case 5:
-      media_calls[inst_no-1] = 0U;
-      /* This is a concession to the conformance test tool that expects
-       *  the media counters to be zero after a GetAndClear service. */
-      for (int idx = 0; idx < 12; ++idx) {
-        g_ethernet_link[inst_no-1].media_cntrs.cntr32[idx] = 0U;
-      }
-      break;
-    default:
-      OPENER_TRACE_INFO(
-        "Wrong attribute number %" PRIu16 " in GetAndClear callback\n",
-        attribute->attribute_number);
-      break;
+      case 4:
+        iface_calls[inst_no - 1] = 0U;
+        break;
+      case 5:
+        media_calls[inst_no - 1] = 0U;
+        /* This is a concession to the conformance test tool that expects
+         *  the media counters to be zero after a GetAndClear service. */
+        for (int idx = 0; idx < 12; ++idx) {
+          g_ethernet_link[inst_no - 1].media_cntrs.cntr32[idx] = 0U;
+        }
+        break;
+      default:
+        OPENER_TRACE_INFO(
+          "Wrong attribute number %" PRIu16 " in GetAndClear callback\n",
+          attribute->attribute_number);
+        break;
     }
   }
   return status;

+ 6 - 6
source/src/ports/POSIX/sample_application/ethlinkcbs.h

@@ -26,16 +26,16 @@
 
 EipStatus EthLnkPreGetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 EipStatus EthLnkPostGetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 

+ 2 - 2
source/src/ports/POSIX/sample_application/opener_user_conf.h

@@ -50,7 +50,7 @@
  *  "-OPENER_CIP_SECURITY:BOOL=ON"
  */
 #ifndef OPENER_CIP_SECURITY
-  #define OPENER_CIP_SECURITY 0 
+  #define OPENER_CIP_SECURITY 0
 #endif
 
 #ifdef OPENER_UNIT_TEST
@@ -233,7 +233,7 @@ static const MilliSeconds kOpenerTimerTickInMilliSeconds = 10;
 /* If you still want assertions to stop execution but without tracing,
  *  use the following */
         #define OPENER_ASSERT(assertion)                    \
-  do { if(!(assertion) ) { while(1) {} } } while (0)
+  do { if( !(assertion) ) { while(1) {} } } while (0)
     #elif 0
 /* Even for debug builds remove assertion. May solicit unused variable
  *  warnings. */

+ 143 - 141
source/src/ports/WIN32/main.c

@@ -1,8 +1,8 @@
 /*******************************************************************************
-* Copyright (c) 2009, Rockwell Automation, Inc.
-* All rights reserved.
-*
-******************************************************************************/
+ * Copyright (c) 2009, Rockwell Automation, Inc.
+ * All rights reserved.
+ *
+ ******************************************************************************/
 #include <stdio.h>
 #include <stdlib.h>
 #include <signal.h>
@@ -22,163 +22,165 @@
 #define ShutdownNetwork(if_name)  (0)
 
 /** If OpENer is aborted by a signal it returns the sum of the signal number
-*  and this define. */
+ *  and this define. */
 #define RET_SHOW_SIGNAL 200
 
 /******************************************************************************/
 /** @brief Signal handler function for ending stack execution
-*
-* @param signal  the signal we received
-*/
+ *
+ * @param signal  the signal we received
+ */
 static void LeaveStack(int signal);
 
 /******************************************************************************/
 /** @brief Execute OpENer stack loop function
-*
-* @param   thread_arg  dummy argument
-* @returns             NO_ERROR at the moment
-*
-*  The call signature is chosen to be able to pass this function directly as
-*  parameter for CreateThread().
-*/
+ *
+ * @param   thread_arg  dummy argument
+ * @returns             NO_ERROR at the moment
+ *
+ *  The call signature is chosen to be able to pass this function directly as
+ *  parameter for CreateThread().
+ */
 static DWORD executeEventLoop(LPVOID thread_arg);
 
 
 /*****************************************************************************/
 /** @brief Flag indicating if the stack should end its execution
-*/
+ */
 volatile int g_end_stack = 0;
 
 /******************************************************************************/
-int main(int argc, char *arg[]) {
-
-	if (argc != 2) {
-		fprintf(stderr, "Wrong number of command line parameters!\n");
-		fprintf(stderr, "Usage: %s [interface index | interface name]\n", arg[0]);
-		fprintf(stderr, "\te.g. ./OpENer \"Ethernet 2\"\n");
-		exit(EXIT_FAILURE);
-	}
-
-	DoublyLinkedListInitialize(&connection_list,
-		CipConnectionObjectListArrayAllocator,
-		CipConnectionObjectListArrayFree);
-	/* Fetch MAC address from the platform. This tests also if the interface
-	*  is present. */
-	uint8_t iface_mac[6];
-	if (kEipStatusError == IfaceGetMacAddress(arg[1], iface_mac)) {
-		printf("Network interface %s not found.\n", arg[1]);
-		exit(EXIT_FAILURE);
-	}
-
-	/* for a real device the serial number should be unique per device */
-	SetDeviceSerialNumber(123456789);
-
-	/* unique_connection_id should be sufficiently random or incremented and stored
-	*  in non-volatile memory each time the device boots. This is used as the upper
-	*  16 bits of the connection id. Here we use random number approach, first seed
-	*  the PRNG to ensure we don't get the same value on every startup.
-	*/
-	srand(time(NULL));
-	EipUint16 unique_connection_id = rand();
-
-	/* Setup the CIP Layer. All objects are initialized with the default
-	* values for the attribute contents. */
-	CipStackInit(unique_connection_id);
-
-	CipEthernetLinkSetMac(iface_mac);
-
-	/* The current host name is used as a default. This value is kept in the
-	*  case NvdataLoad() needs to recreate the TCP/IP object's settings from
-	*  the defaults on the first start without a valid TCP/IP configuration
-	*  file.
-	*/
-	GetHostName(&g_tcpip.hostname);
-
-	/* The CIP objects are now created and initialized with their default values.
-	*  After that any NV data values are loaded to change the attribute contents
-	*  to the stored configuration.
-	*/
-	if (kEipStatusError == NvdataLoad()) {
-		OPENER_TRACE_WARN("Loading of some NV data failed. Maybe the first start?\n");
-	}
-
-	/* Bring up network interface or start DHCP client ... */
-	EipStatus status = BringupNetwork(arg[1],
-		g_tcpip.config_control,
-		&g_tcpip.interface_configuration,
-		&g_tcpip.hostname);
-	if (status < 0) {
-		OPENER_TRACE_ERR("BringUpNetwork() failed\n");
-	}
-
-	/* Register signal handler for SIGINT and SIGTERM that are "supported"
-	*  under Windows. */
-	g_end_stack = 0;
-	signal(SIGINT, LeaveStack);
-	signal(SIGTERM, LeaveStack);
-
-	/* Next actions depend on the set network configuration method. */
-	CipDword network_config_method = g_tcpip.config_control & kTcpipCfgCtrlMethodMask;
-	if (kTcpipCfgCtrlStaticIp == network_config_method) {
-		OPENER_TRACE_INFO("Static network configuration done\n");
-	}
-	if (kTcpipCfgCtrlDhcp == network_config_method) {
-		OPENER_TRACE_INFO("DHCP network configuration started\n");
-		/* DHCP should already have been started with BringupNetwork(). Wait
-		* here for IP present (DHCP done) or abort through g_end_stack. */
-		status = IfaceWaitForIp(arg[1], -1, &g_end_stack);
-		OPENER_TRACE_INFO("DHCP wait for interface: status %d, g_end_stack=%d\n",
-			status, g_end_stack);
-		if (kEipStatusOk == status && 0 == g_end_stack) {
-			/* Read IP configuration received via DHCP from interface and store in
-			*  the TCP/IP object.*/
-			status = IfaceGetConfiguration(arg[1], &g_tcpip.interface_configuration);
-			if (status < 0) {
-				OPENER_TRACE_WARN("Problems getting interface configuration\n");
-			}
-		}
-	}
-
-
-	/* The network initialization of the EIP stack for the NetworkHandler. */
-	if (!g_end_stack && kEipStatusOk == NetworkHandlerInitialize()) {
-
-		(void)executeEventLoop(NULL);
-
-		/* clean up network state */
-		NetworkHandlerFinish();
-	}
-
-	/* close remaining sessions and connections, clean up used data */
-	ShutdownCipStack();
-
-	/* Shut down the network interface now. */
-	(void)ShutdownNetwork(arg[1]);
-
-	if (0 != g_end_stack) {
-		printf("OpENer aborted by signal %d.\n", g_end_stack);
-		return RET_SHOW_SIGNAL + g_end_stack;
-	}
-
-	return EXIT_SUCCESS;
+int main(int argc,
+         char *arg[]) {
+
+  if (argc != 2) {
+    fprintf(stderr, "Wrong number of command line parameters!\n");
+    fprintf(stderr, "Usage: %s [interface index | interface name]\n", arg[0]);
+    fprintf(stderr, "\te.g. ./OpENer \"Ethernet 2\"\n");
+    exit(EXIT_FAILURE);
+  }
+
+  DoublyLinkedListInitialize(&connection_list,
+                             CipConnectionObjectListArrayAllocator,
+                             CipConnectionObjectListArrayFree);
+  /* Fetch MAC address from the platform. This tests also if the interface
+   *  is present. */
+  uint8_t iface_mac[6];
+  if ( kEipStatusError == IfaceGetMacAddress(arg[1], iface_mac) ) {
+    printf("Network interface %s not found.\n", arg[1]);
+    exit(EXIT_FAILURE);
+  }
+
+  /* for a real device the serial number should be unique per device */
+  SetDeviceSerialNumber(123456789);
+
+  /* unique_connection_id should be sufficiently random or incremented and stored
+   *  in non-volatile memory each time the device boots. This is used as the upper
+   *  16 bits of the connection id. Here we use random number approach, first seed
+   *  the PRNG to ensure we don't get the same value on every startup.
+   */
+  srand( time(NULL) );
+  EipUint16 unique_connection_id = rand();
+
+  /* Setup the CIP Layer. All objects are initialized with the default
+   * values for the attribute contents. */
+  CipStackInit(unique_connection_id);
+
+  CipEthernetLinkSetMac(iface_mac);
+
+  /* The current host name is used as a default. This value is kept in the
+   *  case NvdataLoad() needs to recreate the TCP/IP object's settings from
+   *  the defaults on the first start without a valid TCP/IP configuration
+   *  file.
+   */
+  GetHostName(&g_tcpip.hostname);
+
+  /* The CIP objects are now created and initialized with their default values.
+   *  After that any NV data values are loaded to change the attribute contents
+   *  to the stored configuration.
+   */
+  if ( kEipStatusError == NvdataLoad() ) {
+    OPENER_TRACE_WARN("Loading of some NV data failed. Maybe the first start?\n");
+  }
+
+  /* Bring up network interface or start DHCP client ... */
+  EipStatus status = BringupNetwork(arg[1],
+                                    g_tcpip.config_control,
+                                    &g_tcpip.interface_configuration,
+                                    &g_tcpip.hostname);
+  if (status < 0) {
+    OPENER_TRACE_ERR("BringUpNetwork() failed\n");
+  }
+
+  /* Register signal handler for SIGINT and SIGTERM that are "supported"
+   *  under Windows. */
+  g_end_stack = 0;
+  signal(SIGINT, LeaveStack);
+  signal(SIGTERM, LeaveStack);
+
+  /* Next actions depend on the set network configuration method. */
+  CipDword network_config_method = g_tcpip.config_control &
+                                   kTcpipCfgCtrlMethodMask;
+  if (kTcpipCfgCtrlStaticIp == network_config_method) {
+    OPENER_TRACE_INFO("Static network configuration done\n");
+  }
+  if (kTcpipCfgCtrlDhcp == network_config_method) {
+    OPENER_TRACE_INFO("DHCP network configuration started\n");
+    /* DHCP should already have been started with BringupNetwork(). Wait
+     * here for IP present (DHCP done) or abort through g_end_stack. */
+    status = IfaceWaitForIp(arg[1], -1, &g_end_stack);
+    OPENER_TRACE_INFO("DHCP wait for interface: status %d, g_end_stack=%d\n",
+                      status, g_end_stack);
+    if (kEipStatusOk == status && 0 == g_end_stack) {
+      /* Read IP configuration received via DHCP from interface and store in
+       *  the TCP/IP object.*/
+      status = IfaceGetConfiguration(arg[1], &g_tcpip.interface_configuration);
+      if (status < 0) {
+        OPENER_TRACE_WARN("Problems getting interface configuration\n");
+      }
+    }
+  }
+
+
+  /* The network initialization of the EIP stack for the NetworkHandler. */
+  if ( !g_end_stack && kEipStatusOk == NetworkHandlerInitialize() ) {
+
+    (void)executeEventLoop(NULL);
+
+    /* clean up network state */
+    NetworkHandlerFinish();
+  }
+
+  /* close remaining sessions and connections, clean up used data */
+  ShutdownCipStack();
+
+  /* Shut down the network interface now. */
+  (void)ShutdownNetwork(arg[1]);
+
+  if (0 != g_end_stack) {
+    printf("OpENer aborted by signal %d.\n", g_end_stack);
+    return RET_SHOW_SIGNAL + g_end_stack;
+  }
+
+  return EXIT_SUCCESS;
 }
 
 static void LeaveStack(int signal) {
-	if (SIGINT == signal || SIGTERM == signal) {
-		g_end_stack = signal;
-	}
-	OPENER_TRACE_STATE("got signal %d\n", signal);
+  if (SIGINT == signal || SIGTERM == signal) {
+    g_end_stack = signal;
+  }
+  OPENER_TRACE_STATE("got signal %d\n", signal);
 }
 
 static DWORD executeEventLoop(LPVOID thread_arg) {
-	/* Suppress unused parameter compiler warning. */
-	(void)thread_arg;
-
-	/* The event loop. Put other processing you need done continually in here */
-	while (0 == g_end_stack) {
-		if (kEipStatusOk != NetworkHandlerProcessCyclic()) {
-			break;
-		}
-	}
-	return NO_ERROR;
+  /* Suppress unused parameter compiler warning. */
+  (void)thread_arg;
+
+  /* The event loop. Put other processing you need done continually in here */
+  while (0 == g_end_stack) {
+    if ( kEipStatusOk != NetworkHandlerProcessCyclic() ) {
+      break;
+    }
+  }
+  return NO_ERROR;
 }

+ 13 - 13
source/src/ports/WIN32/networkconfig.c

@@ -96,7 +96,7 @@ static DWORD ConvertToIndexFromFakeAlias(const char *iface,
 
   (void) mbstowcs(p_if_alias, iface, wc_cnt);
   DWORD cnv_status = ConvertInterfaceAliasToLuid(p_if_alias, &if_luid);
-  if(NETIO_SUCCESS(cnv_status) ) {
+  if( NETIO_SUCCESS(cnv_status) ) {
     cnv_status = ConvertInterfaceLuidToIndex(&if_luid, iface_idx);
   }
   FREE(p_if_alias);
@@ -266,7 +266,7 @@ EipStatus IfaceGetMacAddress(const char *iface,
                              uint8_t *const physical_address) {
   ULONG iface_idx;
 
-  if(kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
+  if( kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
     return kEipStatusError;
   }
 
@@ -275,7 +275,7 @@ EipStatus IfaceGetMacAddress(const char *iface,
                       GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER |
                       GAA_FLAG_SKIP_FRIENDLY_NAME;
   PIP_ADAPTER_ADDRESSES p_addr_table = NULL;
-  if(kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
+  if( kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
     return kEipStatusError;
   }
 
@@ -311,7 +311,7 @@ EipStatus IfaceGetConfiguration(const char *iface,
                                 CipTcpIpInterfaceConfiguration *iface_cfg) {
   ULONG iface_idx;
 
-  if(kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
+  if( kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
     return kEipStatusError;
   }
 
@@ -319,7 +319,7 @@ EipStatus IfaceGetConfiguration(const char *iface,
   const ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
                       GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAG_INCLUDE_PREFIX;
   PIP_ADAPTER_ADDRESSES p_addr_table = NULL;
-  if(kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
+  if( kEipStatusOk != RetrieveAdapterAddressesTable(flags, &p_addr_table) ) {
     return kEipStatusError;
   }
 
@@ -349,7 +349,7 @@ EipStatus IfaceGetConfiguration(const char *iface,
         PIP_ADAPTER_PREFIX pPrefix = p_addr_entry->FirstPrefix;
         if(NULL != pPrefix) {
           local_cfg.network_mask =
-            htonl(0xffffffff << (32U - pPrefix->PrefixLength) );
+            htonl( 0xffffffff << (32U - pPrefix->PrefixLength) );
         }
       }
       {
@@ -404,7 +404,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
                          volatile int *const abort_wait) {
   ULONG iface_idx;
 
-  if(kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
+  if( kEipStatusOk != DetermineIfaceIndexByString(iface, &iface_idx) ) {
     return kEipStatusError;
   }
 
@@ -445,10 +445,10 @@ EipStatus IfaceWaitForIp(const char *const iface,
       /* Search entry matching the interface index and determine IP address. */
       for(int i = 0; i < (int) pmib_ipaddr_table->dwNumEntries; i++) {
         if(pmib_ipaddr_table->table[i].dwIndex == iface_idx) {
-          if(0 ==
-             (pmib_ipaddr_table->table[i].wType &
-              (MIB_IPADDR_DELETED | MIB_IPADDR_DISCONNECTED |
-               MIB_IPADDR_TRANSIENT) ) ) {
+          if( 0 ==
+              ( pmib_ipaddr_table->table[i].wType &
+                (MIB_IPADDR_DELETED | MIB_IPADDR_DISCONNECTED |
+                 MIB_IPADDR_TRANSIENT) ) ) {
             ipaddr = pmib_ipaddr_table->table[i].dwAddr;
           }
         }
@@ -458,7 +458,7 @@ EipStatus IfaceWaitForIp(const char *const iface,
         --timeout;
       }
     } while( (0 == ipaddr) && (0 != timeout) && (0 == *abort_wait) &&
-             (0 == SleepEx(WAIT_CYCLE_MS, FALSE) ) );
+             ( 0 == SleepEx(WAIT_CYCLE_MS, FALSE) ) );
 
     OPENER_TRACE_INFO("IP=%08" PRIx32 ", timeout=%d\n",
                       (uint32_t)ntohl(ipaddr),
@@ -489,7 +489,7 @@ void GetHostName(CipString *hostname) {
   }
 
   char name_buf[HOST_NAME_MAX] = "";
-  err = gethostname(name_buf, sizeof(name_buf) );
+  err = gethostname( name_buf, sizeof(name_buf) );
   if(0 != err) {
     int error_code = GetSocketErrorNumber();
     char *error_message = GetErrorMessage(error_code);

+ 137 - 66
source/src/ports/WIN32/sample_application/ethlinkcbs.c

@@ -52,66 +52,138 @@ static CipUdint media_calls[OPENER_ETHLINK_INSTANCE_CNT];
 /* This is meant as debugging aid and to check if the individual counter     */
 /*  value is sent at the right position in the Get* service response.        */
 
-#define MAKE_CNTR(inst, attr, idx, cnt) ((10000000U * inst) + (100000U * attr) + (1000U * idx) + cnt)
+#define MAKE_CNTR(inst, attr, idx, \
+                  cnt) ( (10000000U * inst) + (100000U * attr) + (1000U * idx) + \
+                         cnt )
 
 EipStatus EthLnkPreGetCallback
 (
   CipInstance *const instance,
   CipAttributeStruct *const attribute,
   CipByte service
-)
-{
+) {
   bool hadAction = true;
   EipStatus status = kEipStatusOk;
 
   CipUint attr_no = attribute->attribute_number;
   /* ATTENTION: Array indices run from 0..(N-1), instance numbers from 1..N */
   CipUdint inst_no  = instance->instance_number;
-  unsigned idx = inst_no-1;
+  unsigned idx = inst_no - 1;
   switch (attr_no) {
-  case 4: {
-    CipEthernetLinkInterfaceCounters *p_iface_cntrs = &g_ethernet_link[idx].interface_cntrs;
-
-    ++iface_calls[idx];  /* Count successful calls */
-    p_iface_cntrs->ul.in_octets   = MAKE_CNTR(inst_no, attr_no,  0, iface_calls[idx]);
-    p_iface_cntrs->ul.in_ucast    = MAKE_CNTR(inst_no, attr_no,  1, iface_calls[idx]);
-    p_iface_cntrs->ul.in_nucast   = MAKE_CNTR(inst_no, attr_no,  2, iface_calls[idx]);
-    p_iface_cntrs->ul.in_discards = MAKE_CNTR(inst_no, attr_no,  3, iface_calls[idx]);
-    p_iface_cntrs->ul.in_errors   = MAKE_CNTR(inst_no, attr_no,  4, iface_calls[idx]);
-    p_iface_cntrs->ul.in_unknown_protos = MAKE_CNTR(inst_no, attr_no, 5, iface_calls[idx]);
-    p_iface_cntrs->ul.out_octets  = MAKE_CNTR(inst_no, attr_no,  6, iface_calls[idx]);
-    p_iface_cntrs->ul.out_ucast   = MAKE_CNTR(inst_no, attr_no,  7, iface_calls[idx]);
-    p_iface_cntrs->ul.out_nucast  = MAKE_CNTR(inst_no, attr_no,  8, iface_calls[idx]);
-    p_iface_cntrs->ul.out_discards = MAKE_CNTR(inst_no, attr_no, 9, iface_calls[idx]);
-    p_iface_cntrs->ul.out_errors  = MAKE_CNTR(inst_no, attr_no, 10, iface_calls[idx]);
-    break;
-  }
-  case 5: {
-    CipEthernetLinkMediaCounters *p_media_cntrs = &g_ethernet_link[idx].media_cntrs;
-
-    ++media_calls[idx];  /* Count successful calls */
-    /* The 1 != mediaCalls[idx] is a concession to the conformance test tool that
-     *  expects the media counters to be zero after a GetAndClear service.
-     * This way we always transmit zeros after reset or a GetAndClear service. */
-    if (1 != media_calls[idx]) {
-      p_media_cntrs->ul.align_errs    = MAKE_CNTR(inst_no, attr_no,  0, media_calls[idx]);
-      p_media_cntrs->ul.fcs_errs      = MAKE_CNTR(inst_no, attr_no,  1, media_calls[idx]);
-      p_media_cntrs->ul.single_coll   = MAKE_CNTR(inst_no, attr_no,  2, media_calls[idx]);
-      p_media_cntrs->ul.multi_coll    = MAKE_CNTR(inst_no, attr_no,  3, media_calls[idx]);
-      p_media_cntrs->ul.sqe_test_errs = MAKE_CNTR(inst_no, attr_no,  4, media_calls[idx]);
-      p_media_cntrs->ul.def_trans     = MAKE_CNTR(inst_no, attr_no,  5, media_calls[idx]);
-      p_media_cntrs->ul.late_coll     = MAKE_CNTR(inst_no, attr_no,  6, media_calls[idx]);
-      p_media_cntrs->ul.exc_coll      = MAKE_CNTR(inst_no, attr_no,  7, media_calls[idx]);
-      p_media_cntrs->ul.mac_tx_errs   = MAKE_CNTR(inst_no, attr_no,  8, media_calls[idx]);
-      p_media_cntrs->ul.crs_errs      = MAKE_CNTR(inst_no, attr_no,  9, media_calls[idx]);
-      p_media_cntrs->ul.frame_too_long= MAKE_CNTR(inst_no, attr_no, 10, media_calls[idx]);
-      p_media_cntrs->ul.mac_rx_errs   = MAKE_CNTR(inst_no, attr_no, 11, media_calls[idx]);
+    case 4: {
+      CipEthernetLinkInterfaceCounters *p_iface_cntrs =
+        &g_ethernet_link[idx].interface_cntrs;
+
+      ++iface_calls[idx]; /* Count successful calls */
+      p_iface_cntrs->ul.in_octets   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                0,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_ucast    = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                1,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_nucast   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                2,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_discards = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                3,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_errors   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                4,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.in_unknown_protos = MAKE_CNTR(inst_no,
+                                                      attr_no,
+                                                      5,
+                                                      iface_calls[idx]);
+      p_iface_cntrs->ul.out_octets  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                6,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_ucast   = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                7,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_nucast  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                8,
+                                                iface_calls[idx]);
+      p_iface_cntrs->ul.out_discards = MAKE_CNTR(inst_no,
+                                                 attr_no,
+                                                 9,
+                                                 iface_calls[idx]);
+      p_iface_cntrs->ul.out_errors  = MAKE_CNTR(inst_no,
+                                                attr_no,
+                                                10,
+                                                iface_calls[idx]);
+      break;
     }
-    break;
-  }
-  default:
-    hadAction = false;
-    break;
+    case 5: {
+      CipEthernetLinkMediaCounters *p_media_cntrs =
+        &g_ethernet_link[idx].media_cntrs;
+
+      ++media_calls[idx]; /* Count successful calls */
+      /* The 1 != mediaCalls[idx] is a concession to the conformance test tool that
+       *  expects the media counters to be zero after a GetAndClear service.
+       * This way we always transmit zeros after reset or a GetAndClear service. */
+      if (1 != media_calls[idx]) {
+        p_media_cntrs->ul.align_errs    = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    0,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.fcs_errs      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    1,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.single_coll   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    2,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.multi_coll    = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    3,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.sqe_test_errs = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    4,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.def_trans     = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    5,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.late_coll     = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    6,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.exc_coll      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    7,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.mac_tx_errs   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    8,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.crs_errs      = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    9,
+                                                    media_calls[idx]);
+        p_media_cntrs->ul.frame_too_long = MAKE_CNTR(inst_no,
+                                                     attr_no,
+                                                     10,
+                                                     media_calls[idx]);
+        p_media_cntrs->ul.mac_rx_errs   = MAKE_CNTR(inst_no,
+                                                    attr_no,
+                                                    11,
+                                                    media_calls[idx]);
+      }
+      break;
+    }
+    default:
+      hadAction = false;
+      break;
   }
 
   if (hadAction) {
@@ -131,12 +203,11 @@ EipStatus EthLnkPostGetCallback
   CipInstance *const instance,
   CipAttributeStruct *const attribute,
   CipByte service
-)
-{
-  CipUdint  inst_no = instance->instance_number;
+) {
+  CipUdint inst_no = instance->instance_number;
   EipStatus status = kEipStatusOk;
 
-  if (kEthLinkGetAndClear == (service & 0x7f)) {
+  if ( kEthLinkGetAndClear == (service & 0x7f) ) {
     OPENER_TRACE_INFO(
       "Eth Link PostCallback: %s, i %" PRIu32 ", a %" PRIu16 ", s %" PRIu8 "\n",
       instance->cip_class->class_name,
@@ -146,22 +217,22 @@ EipStatus EthLnkPostGetCallback
     /* Clear the instance specific object counters. In this dummy function we only
      *  clear our GetAttributeSingle PreCallback execution counters. */
     switch (attribute->attribute_number) {
-    case 4:
-      iface_calls[inst_no-1] = 0U;
-      break;
-    case 5:
-      media_calls[inst_no-1] = 0U;
-      /* This is a concession to the conformance test tool that expects
-       *  the media counters to be zero after a GetAndClear service. */
-      for (int idx = 0; idx < 12; ++idx) {
-        g_ethernet_link[inst_no-1].media_cntrs.cntr32[idx] = 0U;
-      }
-      break;
-    default:
-      OPENER_TRACE_INFO(
-        "Wrong attribute number %" PRIu16 " in GetAndClear callback\n",
-        attribute->attribute_number);
-      break;
+      case 4:
+        iface_calls[inst_no - 1] = 0U;
+        break;
+      case 5:
+        media_calls[inst_no - 1] = 0U;
+        /* This is a concession to the conformance test tool that expects
+         *  the media counters to be zero after a GetAndClear service. */
+        for (int idx = 0; idx < 12; ++idx) {
+          g_ethernet_link[inst_no - 1].media_cntrs.cntr32[idx] = 0U;
+        }
+        break;
+      default:
+        OPENER_TRACE_INFO(
+          "Wrong attribute number %" PRIu16 " in GetAndClear callback\n",
+          attribute->attribute_number);
+        break;
     }
   }
   return status;

+ 6 - 6
source/src/ports/WIN32/sample_application/ethlinkcbs.h

@@ -26,16 +26,16 @@
 
 EipStatus EthLnkPreGetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 EipStatus EthLnkPostGetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 

+ 1 - 1
source/src/ports/WIN32/sample_application/opener_user_conf.h

@@ -208,7 +208,7 @@ static const MilliSeconds kOpenerTimerTickInMilliSeconds = 10;
 /* If you still want assertions to stop execution but without tracing,
  *  use the following */
         #define OPENER_ASSERT(assertion)                    \
-  do { if(!(assertion) ) { while(1) {} } } while (0)
+  do { if( !(assertion) ) { while(1) {} } } while (0)
     #elif 0
 /* Even for debug builds remove assertion. May solicit unused variable
  *  warnings. */

+ 1 - 1
source/src/ports/WIN32/sample_application/sampleapplication.c

@@ -98,7 +98,7 @@ EipStatus ApplicationInitialization(void) {
     {
       CipAttributeStruct *p_eth_link_attr;
       CipInstance *p_eth_link_inst =
-        GetCipInstance(p_eth_link_class, idx+1);
+        GetCipInstance(p_eth_link_class, idx + 1);
       OPENER_ASSERT(p_eth_link_inst);
 
       /* Interface counters attribute */

+ 3 - 3
source/src/ports/nvdata/nvdata.h

@@ -26,9 +26,9 @@ EipStatus NvQosSetCallback
 
 EipStatus NvTcpipSetCallback
 (
-    CipInstance *const instance,
-    CipAttributeStruct *const attribute,
-    CipByte service
+  CipInstance *const instance,
+  CipAttributeStruct *const attribute,
+  CipByte service
 );
 
 #endif  /* ifndef NVDATA_H_ */

+ 4 - 4
source/src/ports/nvdata/nvtcpip.c

@@ -44,8 +44,8 @@ int NvTcpipLoad(CipTcpIpObject *p_tcp_ip) {
 
     /* Need to try to close all stuff in any case. */
     eip_status =
-      (kEipStatusError ==
-       ConfFileClose(&p_file) ) ? kEipStatusError : eip_status;
+      ( kEipStatusError ==
+        ConfFileClose(&p_file) ) ? kEipStatusError : eip_status;
   }
 
   return eip_status;
@@ -69,8 +69,8 @@ EipStatus NvTcpipStore(const CipTcpIpObject *p_tcp_ip) {
     EipStatus eip_status = kEipStatusError;
 
     /* Need to try to close all stuff in any case. */
-    return (kEipStatusError ==
-            ConfFileClose(&p_file) ) ? kEipStatusError : eip_status;
+    return ( kEipStatusError ==
+             ConfFileClose(&p_file) ) ? kEipStatusError : eip_status;
   } else {
     return kEipStatusError; /* File could not be openend*/
   }

+ 1 - 1
source/src/utils/enipmessage.c

@@ -8,6 +8,6 @@
 #include "string.h"
 
 void InitializeENIPMessage(ENIPMessage *const message) {
-  memset(message, 0, sizeof(ENIPMessage) );
+  memset( message, 0, sizeof(ENIPMessage) );
   message->current_message_position = message->message_buffer;
 }

+ 3 - 2
source/src/utils/xorshiftrandom.c

@@ -18,8 +18,9 @@ void SetXorShiftSeed(uint32_t seed) {
  * Works directly on the file global variable
  */
 void CalculateNextSeed(void) {
-  if (xor_shift_seed == 0)
-    SetXorShiftSeed(time(NULL));
+  if (xor_shift_seed == 0) {
+    SetXorShiftSeed( time(NULL) );
+  }
 
   xor_shift_seed ^= xor_shift_seed << 13;
   xor_shift_seed ^= xor_shift_seed >> 17;

+ 1 - 1
source/tests/OpENerTests.cpp

@@ -37,7 +37,7 @@ int main(int argc,
 
   DetermineEndianess();
 
-  TestRegistry* reg = TestRegistry::getCurrentRegistry();
+  TestRegistry *reg = TestRegistry::getCurrentRegistry();
 
   MockSupportPlugin mockPlugin;
   reg->installPlugin(&mockPlugin);

+ 6 - 6
source/tests/cip/cipelectronickeyformattest.cpp

@@ -30,7 +30,7 @@ TEST_GROUP(CipElectronicKeyFormat) {
 
 TEST(CipElectronicKeyFormat, CreateElectronicKey) {
   CipOctet dummyArea[kElectronicKeyFormat4Size];
-  memset(dummyArea, 0, sizeof(dummyArea) );
+  memset( dummyArea, 0, sizeof(dummyArea) );
   MEMCMP_EQUAL(dummyArea, key, kElectronicKeyFormat4Size);
 };
 
@@ -41,7 +41,7 @@ TEST(CipElectronicKeyFormat, DeleteElectronicKey) {
 
 TEST(CipElectronicKeyFormat, SetVendorID) {
   CipOctet demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
+  memset( demoArea, 0, sizeof(demoArea) );
   CipUint *vendor_id = (CipUint *)demoArea;
   *vendor_id = 1;
   ElectronicKeyFormat4SetVendorId(key, 1);
@@ -61,7 +61,7 @@ TEST(CipElectronicKeyFormat, GetVendorID) {
 
 TEST(CipElectronicKeyFormat, SetDeviceType) {
   CipOctet demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
+  memset( demoArea, 0, sizeof(demoArea) );
   CipUint *device_type = (CipUint *)demoArea + 1;
   *device_type = 1;
 
@@ -81,7 +81,7 @@ TEST(CipElectronicKeyFormat, GetDeviceType) {
 
 TEST(CipElectronicKeyFormat, SetProductCode) {
   CipOctet demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
+  memset( demoArea, 0, sizeof(demoArea) );
   CipUint *product_code = (CipUint *)demoArea + 2;
   *product_code = 1;
 
@@ -101,7 +101,7 @@ TEST(CipElectronicKeyFormat, GetProductCode) {
 
 TEST(CipElectronicKeyFormat, SetMajorRevisionCompatibility) {
   CipOctet demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
+  memset( demoArea, 0, sizeof(demoArea) );
   CipByte *major_revision_compatiblitiy = (CipByte *)demoArea + 6;
   *major_revision_compatiblitiy = 0x81;
 
@@ -132,7 +132,7 @@ TEST(CipElectronicKeyFormat, GetMajorRevisionCompatibility) {
 
 TEST(CipElectronicKeyFormat, SetMinorRevision) {
   CipOctet demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
+  memset( demoArea, 0, sizeof(demoArea) );
   CipByte *minor_revision_compatiblitiy = (CipByte *)demoArea + 7;
   *minor_revision_compatiblitiy = 0x81;
 

+ 2 - 2
source/tests/cip/cipelectronickeytest.cpp

@@ -28,7 +28,7 @@ TEST(CipElectronicKey, SetKeyFormat) {
 
 TEST(CipElectronicKey, GetKeyFormat) {
   CipElectronicKey key = {.key_format = 4, .key_data = NULL};
-  CHECK_EQUAL(4, ElectronicKeyGetKeyFormat(&key) );
+  CHECK_EQUAL( 4, ElectronicKeyGetKeyFormat(&key) );
 }
 
 TEST(CipElectronicKey, SetKeyData) {
@@ -41,5 +41,5 @@ TEST(CipElectronicKey, SetKeyData) {
 TEST(CipElectronicKey, GetKeyData) {
   char dummyFormatData[] = {0,1,2,3,4,5};
   CipElectronicKey key = {.key_format = 0, .key_data = dummyFormatData};
-  POINTERS_EQUAL(dummyFormatData, ElectronicKeyGetKeyData(&key) );
+  POINTERS_EQUAL( dummyFormatData, ElectronicKeyGetKeyData(&key) );
 }

+ 14 - 14
source/tests/cip/cipepathtest.cpp

@@ -339,7 +339,7 @@ TEST(CipEpath, SetLogicalSegmentLogicalFormatThirtyTwoBits) {
 }
 
 TEST(CipEpath, GetLogicalValue8Bit) {
-  CipOctet *message = (CipOctet *)calloc (6, sizeof(CipOctet) );
+  CipOctet *message = (CipOctet *)calloc ( 6, sizeof(CipOctet) );
   CipOctet *original_address = message;
   message[0] = SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_FORMAT_EIGHT_BIT;
   message[1] = 20;
@@ -353,7 +353,7 @@ TEST(CipEpath, GetLogicalValue8Bit) {
 }
 
 TEST(CipEpath, GetLogicalValue16Bit) {
-  CipOctet *message = (CipOctet *)calloc (6, sizeof(CipOctet) );
+  CipOctet *message = (CipOctet *)calloc ( 6, sizeof(CipOctet) );
   CipOctet *original_address = message;
   message[0] = SEGMENT_TYPE_LOGICAL_SEGMENT |
                LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT;
@@ -368,7 +368,7 @@ TEST(CipEpath, GetLogicalValue16Bit) {
 }
 
 TEST(CipEpath, GetLogicalValue32Bit) {
-  CipOctet *message = (CipOctet *)calloc (6, sizeof(CipOctet) );
+  CipOctet *message = (CipOctet *)calloc ( 6, sizeof(CipOctet) );
   CipOctet *original_address = message;
   message[0] = SEGMENT_TYPE_LOGICAL_SEGMENT |
                LOGICAL_SEGMENT_FORMAT_THIRTY_TWO_BIT;
@@ -398,10 +398,10 @@ TEST(CipEpath, SetLogicalValue16Bit) {
   CipEpathSetLogicalValue(value,
                           kLogicalSegmentLogicalFormatSixteenBit,
                           &response);
-  CHECK_EQUAL(value, *(response.message.message_buffer + 1) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 2) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 3) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 4) );
+  CHECK_EQUAL( value, *(response.message.message_buffer + 1) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 2) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 3) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 4) );
 }
 
 TEST(CipEpath, SetLogicalValue32Bit) {
@@ -411,13 +411,13 @@ TEST(CipEpath, SetLogicalValue32Bit) {
   CipEpathSetLogicalValue(value,
                           kLogicalSegmentLogicalFormatThirtyTwoBit,
                           &response);
-  CHECK_EQUAL(value, *(response.message.message_buffer + 1) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 2) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 3) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 4) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 5) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 6) );
-  CHECK_EQUAL(0, *(response.message.message_buffer + 7) );
+  CHECK_EQUAL( value, *(response.message.message_buffer + 1) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 2) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 3) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 4) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 5) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 6) );
+  CHECK_EQUAL( 0, *(response.message.message_buffer + 7) );
 }
 
 TEST(CipEpath, GetLogicalSegmentExtendedLogicalTypeReserved) {

+ 17 - 18
source/tests/cip/cipstringtests.cpp

@@ -17,8 +17,7 @@ extern "C" {
 }
 
 TEST_GROUP (CipString) {
-  void setup()
-  {
+  void setup() {
     mock().disable();
   }
 };
@@ -59,22 +58,22 @@ TEST (CipString, FreeCipStringNWithContent) {
 TEST (CipString, CreateStringNFromData) {
   const CipOctet data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
   CipStringN *string;
-  string = (CipStringN *) CipCalloc(1, sizeof(CipStringN) );
+  string = (CipStringN *) CipCalloc( 1, sizeof(CipStringN) );
   SetCipStringNByData(string, 4, 3, data);
   CHECK_EQUAL(3, string->size);
   CHECK_EQUAL(4, string->length);
-  MEMCMP_EQUAL(data, string->string, sizeof(data) );
+  MEMCMP_EQUAL( data, string->string, sizeof(data) );
   FreeCipStringN(string);
 }
 
 TEST (CipString, CreateStringNFromCString) {
   const char data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0};
   CipStringN *string;
-  string = (CipStringN *) CipCalloc(1, sizeof(CipStringN) );
+  string = (CipStringN *) CipCalloc( 1, sizeof(CipStringN) );
   SetCipStringNByCstr(string, data, 3);
   CHECK_EQUAL(3, string->size);
   CHECK_EQUAL(4, string->length);
-  MEMCMP_EQUAL(data, string->string, strlen(data) );
+  MEMCMP_EQUAL( data, string->string, strlen(data) );
   FreeCipStringN(string);
 }
 
@@ -112,20 +111,20 @@ TEST (CipString, FreeCipString2WithContent) {
 TEST (CipString, CreateString2FromData) {
   const CipOctet data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
   CipString2 *string;
-  string = (CipString2 *) CipCalloc(1, sizeof(CipString2) );
+  string = (CipString2 *) CipCalloc( 1, sizeof(CipString2) );
   SetCipString2ByData(string, 6, data);
   CHECK_EQUAL(6, string->length);
-  MEMCMP_EQUAL(data, string->string, sizeof(data) );
+  MEMCMP_EQUAL( data, string->string, sizeof(data) );
   FreeCipString2(string);
 }
 
 TEST (CipString, CreateString2FromCString) {
   const char data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0};
   CipString2 *string;
-  string = (CipString2 *) CipCalloc(1, sizeof(CipString2) );
+  string = (CipString2 *) CipCalloc( 1, sizeof(CipString2) );
   SetCipString2ByCstr(string, data);
   CHECK_EQUAL(6, string->length);
-  MEMCMP_EQUAL(data, string->string, strlen(data) );
+  MEMCMP_EQUAL( data, string->string, strlen(data) );
   FreeCipString2(string);
 }
 
@@ -163,20 +162,20 @@ TEST (CipString, FreeCipStringWithContent) {
 TEST (CipString, CreateStringFromData) {
   const CipOctet data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
   CipString *string;
-  string = (CipString *) CipCalloc(1, sizeof(CipString) );
+  string = (CipString *) CipCalloc( 1, sizeof(CipString) );
   SetCipStringByData(string, sizeof(data), data);
   CHECK_EQUAL(12, string->length);
-  MEMCMP_EQUAL(data, string->string, sizeof(data) );
+  MEMCMP_EQUAL( data, string->string, sizeof(data) );
   FreeCipString(string);
 }
 
 TEST (CipString, CreateStringFromCString) {
   const char data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0};
   CipString *string;
-  string = (CipString *) CipCalloc(1, sizeof(CipString) );
+  string = (CipString *) CipCalloc( 1, sizeof(CipString) );
   SetCipStringByCstr(string, data);
   CHECK_EQUAL(12, string->length);
-  MEMCMP_EQUAL(data, string->string, strlen(data) );
+  MEMCMP_EQUAL( data, string->string, strlen(data) );
   FreeCipString(string);
 }
 
@@ -214,19 +213,19 @@ TEST (CipString, FreeCipShortStringWithContent) {
 TEST (CipString, CreateShortStringFromData) {
   const CipOctet data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
   CipShortString *string;
-  string = (CipShortString *) CipCalloc(1, sizeof(CipShortString) );
+  string = (CipShortString *) CipCalloc( 1, sizeof(CipShortString) );
   SetCipShortStringByData(string, sizeof(data), data);
   CHECK_EQUAL(12, string->length);
-  MEMCMP_EQUAL(data, string->string, sizeof(data) );
+  MEMCMP_EQUAL( data, string->string, sizeof(data) );
   FreeCipShortString(string);
 }
 
 TEST (CipString, CreateShortStringFromCString) {
   const char data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0};
   CipShortString *string;
-  string = (CipShortString *) CipCalloc(1, sizeof(CipShortString) );
+  string = (CipShortString *) CipCalloc( 1, sizeof(CipShortString) );
   SetCipShortStringByCstr(string, data);
   CHECK_EQUAL(12, string->length);
-  MEMCMP_EQUAL(data, string->string, strlen(data) );
+  MEMCMP_EQUAL( data, string->string, strlen(data) );
   FreeCipShortString(string);
 }

+ 2 - 2
source/tests/ports/socket_timer_tests.cpp

@@ -32,7 +32,7 @@ TEST(SocketTimer, NoEmptySocketTimerAvailable) {
 
 TEST(SocketTimer, SetSocket) {
   SocketTimer timer = {
-    socket : -1,
+    socket: -1,
     last_update : 0
   };
   SocketTimerSetSocket(&timer, 1);
@@ -42,7 +42,7 @@ TEST(SocketTimer, SetSocket) {
 
 TEST(SocketTimer, UpdateSocketTimer) {
   SocketTimer timer = {
-    socket : -1,
+    socket: -1,
     last_update : 0
   };
   SocketTimerSetLastUpdate(&timer, 10);