cipconnectionmanager.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. /*******************************************************************************
  2. * Copyright (c) 2009, Rockwell Automation, Inc.
  3. * All rights reserved.
  4. *
  5. ******************************************************************************/
  6. #include <string.h>
  7. #include <stdbool.h>
  8. #include "cipconnectionmanager.h"
  9. #include "opener_user_conf.h"
  10. #include "cipcommon.h"
  11. #include "cipmessagerouter.h"
  12. #include "ciperror.h"
  13. #include "endianconv.h"
  14. #include "opener_api.h"
  15. #include "encap.h"
  16. #include "cipidentity.h"
  17. #include "trace.h"
  18. #include "cipconnectionobject.h"
  19. #include "cipclass3connection.h"
  20. #include "cipioconnection.h"
  21. #include "cipassembly.h"
  22. #include "cpf.h"
  23. #include "appcontype.h"
  24. #include "encap.h"
  25. #include "generic_networkhandler.h"
  26. #include "cipepath.h"
  27. #include "cipelectronickey.h"
  28. #include "cipqos.h"
  29. /* values needed from the CIP identity object */
  30. extern EipUint16 vendor_id_;
  31. extern EipUint16 device_type_;
  32. extern EipUint16 product_code_;
  33. extern CipRevision revision_;
  34. const size_t g_kForwardOpenHeaderLength = 36; /**< the length in bytes of the forward open command specific data till the start of the connection path (including con path size)*/
  35. static const int g_kNumberOfConnectableObjects = 2 +
  36. OPENER_CIP_NUM_APPLICATION_SPECIFIC_CONNECTABLE_OBJECTS;
  37. extern DoublyLinkedList connection_list;
  38. typedef struct {
  39. EipUint32 class_id;
  40. OpenConnectionFunction open_connection_function;
  41. } ConnectionManagementHandling;
  42. /* global variables private */
  43. /** List holding information on the object classes and open/close function
  44. * pointers to which connections may be established.
  45. */
  46. ConnectionManagementHandling g_connection_management_list[2 +
  47. OPENER_CIP_NUM_APPLICATION_SPECIFIC_CONNECTABLE_OBJECTS
  48. ];
  49. /** buffer connection object needed for forward open */
  50. CipConnectionObject g_dummy_connection_object;
  51. /** @brief Holds the connection ID's "incarnation ID" in the upper 16 bits */
  52. EipUint32 g_incarnation_id;
  53. /* private functions */
  54. EipStatus ForwardOpen(
  55. CipInstance *instance,
  56. CipMessageRouterRequest *message_router_request,
  57. CipMessageRouterResponse *message_router_response,
  58. struct sockaddr *originator_address,
  59. const int encapsulation_session);
  60. EipStatus ForwardClose(
  61. CipInstance *instance,
  62. CipMessageRouterRequest *message_router_request,
  63. CipMessageRouterResponse *message_router_response,
  64. struct sockaddr *originator_address,
  65. const int encapsulation_session);
  66. EipStatus GetConnectionOwner(
  67. CipInstance *instance,
  68. CipMessageRouterRequest *message_router_request,
  69. CipMessageRouterResponse *message_router_response,
  70. struct sockaddr *originator_address,
  71. const int encapsulation_session);
  72. EipStatus AssembleForwardOpenResponse(
  73. CipConnectionObject *connection_object,
  74. CipMessageRouterResponse *message_router_response,
  75. EipUint8 general_status,
  76. EipUint16 extended_status);
  77. EipStatus AssembleForwardCloseResponse(
  78. EipUint16 connection_serial_number,
  79. EipUint16 originatior_vendor_id,
  80. EipUint32 originator_serial_number,
  81. CipMessageRouterRequest *message_router_request,
  82. CipMessageRouterResponse *message_router_response,
  83. EipUint16 extended_error_code);
  84. /** @brief check if the data given in the connection object match with an already established connection
  85. *
  86. * The comparison is done according to the definitions in the CIP specification Section 3-5.5.2:
  87. * The following elements have to be equal: Vendor ID, Connection Serial Number, Originator Serial Number
  88. * @param connection_object connection object containing the comparison elements from the forward open request
  89. * @return
  90. * - NULL if no equal established connection exists
  91. * - pointer to the equal connection object
  92. */
  93. CipConnectionObject *CheckForExistingConnection(
  94. const CipConnectionObject *const connection_object);
  95. /** @brief Compare the electronic key received with a forward open request with the device's data.
  96. *
  97. * @param key_format format identifier given in the forward open request
  98. * @param key_data pointer to the electronic key data received in the forward open request
  99. * @param extended_status the extended error code in case an error happened
  100. * @return general status on the establishment
  101. * - EIP_OK ... on success
  102. * - On an error the general status code to be put into the response
  103. */
  104. EipStatus CheckElectronicKeyData(
  105. EipUint8 key_format,
  106. void *key_data,
  107. EipUint16 *extended_status);
  108. /** @brief Parse the connection path of a forward open request
  109. *
  110. * This function will take the connection object and the received data stream and parse the connection path.
  111. * @param connection_object pointer to the connection object structure for which the connection should
  112. * be established
  113. * @param message_router_request pointer to the received request structure. The position of the data stream pointer has to be at the connection length entry
  114. * @param extended_error the extended error code in case an error happened
  115. * @return general status on the establishment
  116. * - kEipStatusOk ... on success
  117. * - On an error the general status code to be put into the response
  118. */
  119. EipUint8 ParseConnectionPath(
  120. CipConnectionObject *connection_object,
  121. CipMessageRouterRequest *message_router_request,
  122. EipUint16 *extended_error);
  123. ConnectionManagementHandling *GetConnectionManagementEntry(
  124. const EipUint32 class_id);
  125. void InitializeConnectionManagerData(void);
  126. void AddNullAddressItem(
  127. CipCommonPacketFormatData *common_data_packet_format_data);
  128. /** @brief gets the padded logical path TODO: enhance documentation
  129. * @param logical_path_segment TheLogical Path Segment
  130. *
  131. * @return The padded logical path
  132. */
  133. unsigned int GetPaddedLogicalPath(const EipUint8 **logical_path_segment) {
  134. unsigned int padded_logical_path = *(*logical_path_segment)++;
  135. if ( (padded_logical_path & 3) == 0 ) {
  136. padded_logical_path = *(*logical_path_segment)++;
  137. } else if ( (padded_logical_path & 3) == 1 ) {
  138. (*logical_path_segment)++; /* skip pad */
  139. padded_logical_path = *(*logical_path_segment)++;
  140. padded_logical_path |= *(*logical_path_segment)++ << 8;
  141. } else {
  142. OPENER_TRACE_ERR("illegal logical path segment\n");
  143. }
  144. return padded_logical_path;
  145. }
  146. /** @brief Generate a new connection Id utilizing the Incarnation Id as
  147. * described in the EIP specs.
  148. *
  149. * A unique connectionID is formed from the boot-time-specified "incarnation ID"
  150. * and the per-new-connection-incremented connection number/counter.
  151. * @return new connection id
  152. */
  153. CipUint GetConnectionId(void) {
  154. static CipUint connection_id = 18;
  155. connection_id++;
  156. return ( g_incarnation_id | (connection_id & 0x0000FFFF) );
  157. }
  158. void InitializeConnectionManager(CipClass *class) {
  159. CipClass *meta_class = class->class_instance.cip_class;
  160. InsertAttribute( (CipInstance *) class, 1, kCipUint,
  161. (void *) &class->revision,
  162. kGetableSingleAndAll ); /* revision */
  163. InsertAttribute( (CipInstance *) class, 2, kCipUint,
  164. (void *) &class->number_of_instances, kGetableSingleAndAll ); /* largest instance number */
  165. InsertAttribute( (CipInstance *) class, 3, kCipUint,
  166. (void *) &class->number_of_instances, kGetableSingle ); /* number of instances currently existing*/
  167. InsertAttribute( (CipInstance *) class, 4, kCipUint, (void *) &kCipUintZero,
  168. kNotSetOrGetable ); /* optional attribute list - default = 0 */
  169. InsertAttribute( (CipInstance *) class, 5, kCipUint, (void *) &kCipUintZero,
  170. kNotSetOrGetable ); /* optional service list - default = 0 */
  171. InsertAttribute( (CipInstance *) class, 6, kCipUint,
  172. (void *) &meta_class->highest_attribute_number,
  173. kGetableSingleAndAll ); /* max class attribute number*/
  174. InsertAttribute( (CipInstance *) class, 7, kCipUint,
  175. (void *) &class->highest_attribute_number,
  176. kGetableSingleAndAll ); /* max instance attribute number*/
  177. }
  178. EipStatus ConnectionManagerInit(EipUint16 unique_connection_id) {
  179. InitializeConnectionManagerData();
  180. CipClass *connection_manager = CreateCipClass(
  181. g_kCipConnectionManagerClassCode, /* class ID */
  182. 0, /* # of class attributes */
  183. 7, /* # highest class attribute number*/
  184. 2, /* # of class services */
  185. 0, /* # of instance attributes */
  186. 14, /* # highest instance attribute number*/
  187. 5, /* # of instance services */
  188. 1, /* # of instances */
  189. "connection manager", /* class name */
  190. 1, /* revision */
  191. &InitializeConnectionManager); /* # function pointer for initialization*/
  192. if (connection_manager == NULL) {
  193. return kEipStatusError;
  194. }
  195. InsertService(connection_manager, kGetAttributeSingle, &GetAttributeSingle,
  196. "GetAttributeSingle");
  197. InsertService(connection_manager, kGetAttributeAll, &GetAttributeAll,
  198. "GetAttributeAll");
  199. InsertService(connection_manager, kForwardOpen, &ForwardOpen, "ForwardOpen");
  200. InsertService(connection_manager, kForwardClose, &ForwardClose,
  201. "ForwardClose");
  202. InsertService(connection_manager, kGetConnectionOwner, &GetConnectionOwner,
  203. "GetConnectionOwner");
  204. g_incarnation_id = ( (EipUint32) unique_connection_id ) << 16;
  205. AddConnectableObject(kCipMessageRouterClassCode, EstablishClass3Connection);
  206. AddConnectableObject(kCipAssemblyClassCode, EstablishIoConnection);
  207. return kEipStatusOk;
  208. }
  209. EipStatus HandleReceivedConnectedData(
  210. const EipUint8 *const data,
  211. int data_length,
  212. struct sockaddr_in *from_address
  213. ) {
  214. if ( ( CreateCommonPacketFormatStructure(data, data_length,
  215. &g_common_packet_format_data_item) )
  216. == kEipStatusError ) {
  217. return kEipStatusError;
  218. } else {
  219. /* check if connected address item or sequenced address item received, otherwise it is no connected message and should not be here */
  220. if ( (g_common_packet_format_data_item.address_item.type_id
  221. == kCipItemIdConnectionAddress)
  222. || (g_common_packet_format_data_item.address_item.type_id
  223. == kCipItemIdSequencedAddressItem) ) { /* found connected address item or found sequenced address item -> for now the sequence number will be ignored */
  224. if (g_common_packet_format_data_item.data_item.type_id
  225. == kCipItemIdConnectedDataItem) { /* connected data item received */
  226. CipConnectionObject *connection_object = GetConnectedObject(
  227. g_common_packet_format_data_item.address_item.data
  228. .connection_identifier);
  229. if (connection_object == NULL) {
  230. return kEipStatusError;
  231. }
  232. /* only handle the data if it is coming from the originator */
  233. if (connection_object->originator_address.sin_addr.s_addr
  234. == from_address->sin_addr.s_addr) {
  235. ConnectionObjectResetLastPackageInactivityTimerValue(connection_object);
  236. if ( SEQ_GT32(
  237. g_common_packet_format_data_item.address_item.data.
  238. sequence_number,
  239. connection_object->eip_level_sequence_count_consuming) ) {
  240. /* reset the watchdog timer */
  241. ConnectionObjectResetInactivityWatchdogTimerValue(connection_object);
  242. /* only inform assembly object if the sequence counter is greater or equal */
  243. connection_object->eip_level_sequence_count_consuming =
  244. g_common_packet_format_data_item.address_item.data
  245. .sequence_number;
  246. if (NULL != connection_object->connection_receive_data_function) {
  247. return connection_object->connection_receive_data_function(
  248. connection_object,
  249. g_common_packet_format_data_item.data_item.data,
  250. g_common_packet_format_data_item.data_item.length);
  251. }
  252. }
  253. } else {
  254. OPENER_TRACE_WARN(
  255. "Connected Message Data Received with wrong address information\n");
  256. }
  257. }
  258. }
  259. }
  260. return kEipStatusOk;
  261. }
  262. /** @brief Function prototype for all Forward Open handle functions
  263. *
  264. */
  265. typedef EipStatus (*HandleForwardOpenRequestFunction)(
  266. CipConnectionObject *connection_object,
  267. CipInstance *instance,
  268. CipMessageRouterRequest *message_router_request,
  269. CipMessageRouterResponse *message_router_response);
  270. /** @brief Handles a Null Non Matching Forward Open Request
  271. *
  272. * Null, Non-Matching - Either ping device, or configure a device’s application,
  273. * or return General Status kCipErrorConnectionFailure and
  274. * Extended Status kConnectionManagerExtendedStatusCodeNullForwardOpenNotSupported
  275. */
  276. EipStatus HandleNullNonMatchingForwardOpenRequest(
  277. CipConnectionObject *connection_object,
  278. CipInstance *instance,
  279. CipMessageRouterRequest *message_router_request,
  280. CipMessageRouterResponse *message_router_response);
  281. EipStatus HandleNullNonMatchingForwardOpenRequest(
  282. CipConnectionObject *connection_object,
  283. CipInstance *instance,
  284. CipMessageRouterRequest *message_router_request,
  285. CipMessageRouterResponse *message_router_response
  286. ) {
  287. OPENER_TRACE_INFO("Right now we cannot handle Null requests\n");
  288. return AssembleForwardOpenResponse(
  289. connection_object,
  290. message_router_response,
  291. kCipErrorConnectionFailure,
  292. kConnectionManagerExtendedStatusCodeNullForwardOpenNotSupported);
  293. }
  294. /** @brief Handles a Null Matching Forward Open request
  295. *
  296. * Either reconfigure a target device’s application, or
  297. * return General Status kCipErrorConnectionFailure and
  298. * Extended Status kConnectionManagerExtendedStatusCodeNullForwardOpenNotSupported
  299. */
  300. EipStatus HandleNullMatchingForwardOpenRequest(
  301. CipConnectionObject *connection_object,
  302. CipInstance *instance,
  303. CipMessageRouterRequest *message_router_request,
  304. CipMessageRouterResponse *message_router_response);
  305. EipStatus HandleNullMatchingForwardOpenRequest(
  306. CipConnectionObject *connection_object,
  307. CipInstance *instance,
  308. CipMessageRouterRequest *message_router_request,
  309. CipMessageRouterResponse *message_router_response
  310. ) {
  311. OPENER_TRACE_INFO("Right now we cannot handle Null requests\n");
  312. return AssembleForwardOpenResponse(
  313. connection_object,
  314. message_router_response,
  315. kCipErrorConnectionFailure,
  316. kConnectionManagerExtendedStatusCodeNullForwardOpenNotSupported);
  317. }
  318. /** @brief Handles a Non Null Matching Forward Open Request
  319. *
  320. * Non-Null, Matching request - Return General Status = kCipErrorConnectionFailure,
  321. * Extended Status = kConnectionManagerExtendedStatusCodeErrorConnectionInUseOrDuplicateForwardOpen
  322. */
  323. EipStatus HandleNonNullMatchingForwardOpenRequest(
  324. CipConnectionObject *connection_object,
  325. CipInstance *instance,
  326. CipMessageRouterRequest *message_router_request,
  327. CipMessageRouterResponse *message_router_response);
  328. EipStatus HandleNonNullMatchingForwardOpenRequest(
  329. CipConnectionObject *connection_object,
  330. CipInstance *instance,
  331. CipMessageRouterRequest *message_router_request,
  332. CipMessageRouterResponse *message_router_response
  333. ) {
  334. OPENER_TRACE_INFO("Right now we cannot handle reconfiguration requests\n");
  335. return AssembleForwardOpenResponse(
  336. connection_object,
  337. message_router_response,
  338. kCipErrorConnectionFailure,
  339. kConnectionManagerExtendedStatusCodeErrorConnectionInUseOrDuplicateForwardOpen);
  340. }
  341. /** @brief Handles a Non Null Non Matching Forward Open Request
  342. *
  343. * Non-Null, Non-Matching request - Establish a new connection
  344. */
  345. EipStatus HandleNonNullNonMatchingForwardOpenRequest(
  346. CipConnectionObject *connection_object,
  347. CipInstance *instance,
  348. CipMessageRouterRequest *message_router_request,
  349. CipMessageRouterResponse *message_router_response);
  350. EipStatus HandleNonNullNonMatchingForwardOpenRequest(
  351. CipConnectionObject *connection_object,
  352. CipInstance *instance,
  353. CipMessageRouterRequest *message_router_request,
  354. CipMessageRouterResponse *message_router_response
  355. ) {
  356. EipUint16 connection_status = kConnectionManagerExtendedStatusCodeSuccess;
  357. /*check if the trigger type value is invalid or ok */
  358. if(kConnectionObjectTransportClassTriggerProductionTriggerInvalid ==
  359. ConnectionObjectGetTransportClassTriggerProductionTrigger(&
  360. g_dummy_connection_object) )
  361. {
  362. return AssembleForwardOpenResponse(
  363. &g_dummy_connection_object,
  364. message_router_response,
  365. kCipErrorConnectionFailure,
  366. kConnectionManagerExtendedStatusCodeErrorTransportClassAndTriggerCombinationNotSupported);
  367. }
  368. EipUint32 temp = ParseConnectionPath(&g_dummy_connection_object,
  369. message_router_request,
  370. &connection_status);
  371. if (kEipStatusOk != temp) {
  372. return AssembleForwardOpenResponse(&g_dummy_connection_object,
  373. message_router_response, temp,
  374. connection_status);
  375. }
  376. /*parsing is now finished all data is available and check now establish the connection */
  377. ConnectionManagementHandling *connection_management_entry =
  378. GetConnectionManagementEntry( /* Gets correct open connection function for the targeted object */
  379. g_dummy_connection_object.configuration_path.class_id);
  380. if (NULL != connection_management_entry) {
  381. temp = connection_management_entry->open_connection_function(
  382. &g_dummy_connection_object, &connection_status);
  383. } else {
  384. temp = kEipStatusError;
  385. connection_status =
  386. kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
  387. }
  388. if (kEipStatusOk != temp) {
  389. OPENER_TRACE_INFO("connection manager: connect failed\n");
  390. /* in case of error the dummy objects holds all necessary information */
  391. return AssembleForwardOpenResponse(&g_dummy_connection_object,
  392. message_router_response, temp,
  393. connection_status);
  394. } else {
  395. OPENER_TRACE_INFO("connection manager: connect succeeded\n");
  396. /* in case of success the new connection is added at the head of the connection list */
  397. return AssembleForwardOpenResponse(connection_list.first->data,
  398. message_router_response,
  399. kCipErrorSuccess, 0);
  400. }
  401. }
  402. /** @brief Array of Forward Open handle function pointers
  403. *
  404. * File scope variable
  405. * The first dimension handles if the request was a non-null request (0) or a null request (1),
  406. * the second dimension handles if the request was a non-matchin (0) or matching request (1)
  407. */
  408. static const HandleForwardOpenRequestFunction
  409. handle_forward_open_request_functions[2][2] =
  410. { { HandleNonNullNonMatchingForwardOpenRequest,
  411. HandleNonNullMatchingForwardOpenRequest }, {
  412. HandleNullNonMatchingForwardOpenRequest,
  413. HandleNullMatchingForwardOpenRequest
  414. } };
  415. /** @brief Check if resources for new connection available, generate ForwardOpen Reply message.
  416. *
  417. * Forward Open four cases
  418. * Non-Null/Not matching - open a connection
  419. * Non-Null/Matching - error
  420. * Null/Not matching - ping a device/configure
  421. * Null/Matching - reconfigure
  422. *
  423. * Null connection - both O->T and T->O connection parameter field are null
  424. * Non-Null connection - one or both O->T and T->O connection parameter field are not null
  425. * Matching - Connection Triad matches an existing connection
  426. * (Connection Serial Number, Originator Vendor ID and Originator Serial Number)
  427. *
  428. * @param instance pointer to CIP object instance
  429. * @param message_router_request pointer to Message Router Request.
  430. * @param message_router_response pointer to Message Router Response.
  431. * @param originator_address address struct of the originator as received
  432. * @param encapsulation_session associated encapsulation session of the explicit message
  433. * @return >0 .. success, 0 .. no reply to send back
  434. * -1 .. error
  435. */
  436. EipStatus ForwardOpen(
  437. CipInstance *instance,
  438. CipMessageRouterRequest *message_router_request,
  439. CipMessageRouterResponse *message_router_response,
  440. struct sockaddr *originator_address,
  441. const int encapsulation_session
  442. ) {
  443. (void) instance; /*suppress compiler warning */
  444. bool is_null_request = false; /* 1 = Null Request, 0 = Non-Null Request */
  445. bool is_matching_request = false; /* 1 = Matching Request, 0 = Non-Matching Request */
  446. /*first check if we have already a connection with the given params */
  447. ConnectionObjectInitializeFromMessage(&(message_router_request->data),
  448. &g_dummy_connection_object);
  449. g_dummy_connection_object.associated_encapsulation_session =
  450. encapsulation_session;
  451. memcpy( &(g_dummy_connection_object.originator_address), originator_address,
  452. sizeof(g_dummy_connection_object.originator_address) );
  453. ConnectionObjectConnectionType o_to_t_connection_type =
  454. ConnectionObjectGetOToTConnectionType(&g_dummy_connection_object);
  455. ConnectionObjectConnectionType t_to_o_connection_type =
  456. ConnectionObjectGetTToOConnectionType(&g_dummy_connection_object);
  457. /* Check if both connection types are valid, otherwise send error response */
  458. if (kConnectionObjectConnectionTypeInvalid == o_to_t_connection_type) {
  459. return AssembleForwardOpenResponse(
  460. &g_dummy_connection_object, message_router_response,
  461. kCipErrorConnectionFailure,
  462. kConnectionManagerExtendedStatusCodeErrorInvalidOToTConnectionType);
  463. }
  464. if (kConnectionObjectConnectionTypeInvalid == t_to_o_connection_type) {
  465. return AssembleForwardOpenResponse(
  466. &g_dummy_connection_object, message_router_response,
  467. kCipErrorConnectionFailure,
  468. kConnectionManagerExtendedStatusCodeErrorInvalidTToOConnectionType);
  469. }
  470. /* Check if request is a Null request or a Non-Null request */
  471. if (kConnectionObjectConnectionTypeNull == o_to_t_connection_type
  472. && kConnectionObjectConnectionTypeNull == t_to_o_connection_type) {
  473. is_null_request = true;
  474. OPENER_TRACE_INFO("We have a Null request\n");
  475. } else {
  476. is_null_request = false;
  477. OPENER_TRACE_INFO("We have a Non-Null request\n");
  478. }
  479. /* Check if we have a matching or non matching request */
  480. if ( NULL != CheckForExistingConnection(&g_dummy_connection_object) ) {
  481. OPENER_TRACE_INFO("We have a Matching request\n");
  482. is_matching_request = true;
  483. } else {
  484. OPENER_TRACE_INFO("We have a Non-Matching request\n");
  485. is_matching_request = false;
  486. }
  487. HandleForwardOpenRequestFunction choosen_function =
  488. handle_forward_open_request_functions[is_null_request][is_matching_request];
  489. return choosen_function(&g_dummy_connection_object, instance,
  490. message_router_request, message_router_response);
  491. }
  492. EipStatus ForwardClose(
  493. CipInstance *instance,
  494. CipMessageRouterRequest *message_router_request,
  495. CipMessageRouterResponse *message_router_response,
  496. struct sockaddr *originator_address,
  497. const int encapsulation_session) {
  498. /*Suppress compiler warning*/
  499. (void) instance;
  500. /* check connection_serial_number && originator_vendor_id && originator_serial_number if connection is established */
  501. ConnectionManagerExtendedStatusCode connection_status =
  502. kConnectionManagerExtendedStatusCodeErrorConnectionTargetConnectionNotFound;
  503. /* set AddressInfo Items to invalid TypeID to prevent assembleLinearMsg to read them */
  504. g_common_packet_format_data_item.address_info_item[0].type_id = 0;
  505. g_common_packet_format_data_item.address_info_item[1].type_id = 0;
  506. message_router_request->data += 2; /* ignore Priority/Time_tick and Time-out_ticks */
  507. EipUint16 connection_serial_number = GetIntFromMessage(
  508. &message_router_request->data);
  509. EipUint16 originator_vendor_id = GetIntFromMessage(
  510. &message_router_request->data);
  511. EipUint32 originator_serial_number = GetDintFromMessage(
  512. &message_router_request->data);
  513. OPENER_TRACE_INFO("ForwardClose: ConnSerNo %d\n", connection_serial_number);
  514. DoublyLinkedListNode *node = connection_list.first;
  515. while (NULL != node) {
  516. /* this check should not be necessary as only established connections should be in the active connection list */
  517. CipConnectionObject *connection_object = node->data;
  518. if ( (kConnectionObjectStateEstablished ==
  519. ConnectionObjectGetState(connection_object) )
  520. || (kConnectionObjectStateTimedOut ==
  521. ConnectionObjectGetState(connection_object) ) ) {
  522. if ( (connection_object->connection_serial_number
  523. == connection_serial_number)
  524. && (connection_object->originator_vendor_id == originator_vendor_id)
  525. && (connection_object->originator_serial_number
  526. == originator_serial_number) ) {
  527. /* found the corresponding connection object -> close it */
  528. OPENER_ASSERT(NULL != connection_object->connection_close_function)
  529. if ( ( (struct sockaddr_in *) originator_address )->sin_addr.s_addr
  530. == connection_object->originator_address.sin_addr.s_addr ) {
  531. connection_object->connection_close_function(connection_object);
  532. connection_status = kConnectionManagerExtendedStatusCodeSuccess;
  533. } else {
  534. connection_status = kConnectionManagerExtendedStatusWrongCloser;
  535. }
  536. break;
  537. }
  538. }
  539. node = node->next;
  540. }
  541. if(
  542. kConnectionManagerExtendedStatusCodeErrorConnectionTargetConnectionNotFound
  543. ==
  544. connection_status) {
  545. OPENER_TRACE_INFO(
  546. "Connection not found! Requested connection triad: %u, %u, %u\n",
  547. connection_serial_number,
  548. originator_vendor_id,
  549. originator_serial_number);
  550. }
  551. return AssembleForwardCloseResponse(connection_serial_number,
  552. originator_vendor_id,
  553. originator_serial_number,
  554. message_router_request,
  555. message_router_response,
  556. connection_status);
  557. }
  558. /* TODO: Not implemented */
  559. EipStatus GetConnectionOwner(
  560. CipInstance *instance,
  561. CipMessageRouterRequest *message_router_request,
  562. CipMessageRouterResponse *message_router_response,
  563. struct sockaddr *originator_address,
  564. const int encapsulation_session) {
  565. /* suppress compiler warnings */
  566. (void) instance;
  567. (void) message_router_request;
  568. (void) message_router_response;
  569. return kEipStatusOk;
  570. }
  571. EipStatus ManageConnections(MilliSeconds elapsed_time) {
  572. //OPENER_TRACE_INFO("Entering ManageConnections\n");
  573. /*Inform application that it can execute */
  574. HandleApplication();
  575. ManageEncapsulationMessages(elapsed_time);
  576. DoublyLinkedListNode *node = connection_list.first;
  577. while (NULL != node) {
  578. //OPENER_TRACE_INFO("Entering Connection Object loop\n");
  579. CipConnectionObject *connection_object = node->data;
  580. if (kConnectionObjectStateEstablished ==
  581. ConnectionObjectGetState(connection_object) ) {
  582. if ( (NULL != connection_object->consuming_instance) || /* we have a consuming connection check inactivity watchdog timer */
  583. (kConnectionObjectTransportClassTriggerDirectionServer ==
  584. ConnectionObjectGetTransportClassTriggerDirection(connection_object) ) ) /* all server connections have to maintain an inactivity watchdog timer */
  585. {
  586. if (elapsed_time >= connection_object->inactivity_watchdog_timer) {
  587. /* we have a timed out connection perform watchdog time out action*/
  588. OPENER_TRACE_INFO(">>>>>>>>>>Connection ConnNr: %u timed out\n",
  589. connection_object->connection_serial_number);
  590. OPENER_ASSERT(NULL != connection_object->connection_timeout_function)
  591. connection_object->connection_timeout_function(connection_object);
  592. } else {
  593. connection_object->inactivity_watchdog_timer -= elapsed_time;
  594. connection_object->last_package_watchdog_timer -= elapsed_time;
  595. }
  596. }
  597. /* only if the connection has not timed out check if data is to be send */
  598. if (kConnectionObjectStateEstablished ==
  599. ConnectionObjectGetState(connection_object) ) {
  600. /* client connection */
  601. if ( (0 != ConnectionObjectGetExpectedPacketRate(connection_object) )
  602. && (kEipInvalidSocket
  603. != connection_object->socket[
  604. kUdpCommuncationDirectionProducing
  605. ]) ) /* only produce for the master connection */
  606. {
  607. if ( kConnectionObjectTransportClassTriggerProductionTriggerCyclic
  608. != ConnectionObjectGetTransportClassTriggerProductionTrigger(
  609. connection_object) ) {
  610. /* non cyclic connections have to decrement production inhibit timer */
  611. if (elapsed_time <= connection_object->production_inhibit_timer) {
  612. //The connection is allowed to send again
  613. } else {
  614. connection_object->production_inhibit_timer -= elapsed_time;
  615. }
  616. }
  617. if (connection_object->transmission_trigger_timer <= elapsed_time) { /* need to send package */
  618. OPENER_ASSERT(
  619. NULL != connection_object->connection_send_data_function)
  620. EipStatus eip_status = connection_object
  621. ->connection_send_data_function(
  622. connection_object);
  623. if (eip_status == kEipStatusError) {
  624. OPENER_TRACE_ERR(
  625. "sending of UDP data in manage Connection failed\n");
  626. }
  627. /* reload the timer value */
  628. connection_object->transmission_trigger_timer =
  629. ConnectionObjectGetRequestedPacketInterval(connection_object);
  630. if ( kConnectionObjectTransportClassTriggerProductionTriggerCyclic
  631. != ConnectionObjectGetTransportClassTriggerProductionTrigger(
  632. connection_object) ) {
  633. /* non cyclic connections have to reload the production inhibit timer */
  634. ConnectionObjectResetProductionInhibitTimer(connection_object);
  635. }
  636. } else {
  637. connection_object->transmission_trigger_timer -= elapsed_time;
  638. }
  639. }
  640. }
  641. }
  642. node = node->next;
  643. }
  644. return kEipStatusOk;
  645. }
  646. /** @brief Assembles the Forward Open Response
  647. *
  648. * @param connection_object pointer to connection Object
  649. * @param message_router_response pointer to message router response
  650. * @param general_status the general status of the response
  651. * @param extended_status extended status in the case of an error otherwise 0
  652. * @return status
  653. * kEipStatusOk .. no reply need to be sent back
  654. * kEipStatusOkSend .. need to send reply
  655. * kEipStatusError .. error
  656. */
  657. EipStatus AssembleForwardOpenResponse(
  658. CipConnectionObject *connection_object,
  659. CipMessageRouterResponse *message_router_response,
  660. EipUint8 general_status,
  661. EipUint16 extended_status
  662. ) {
  663. /* write reply information in CPF struct dependent of pa_status */
  664. CipCommonPacketFormatData *cip_common_packet_format_data =
  665. &g_common_packet_format_data_item;
  666. EipByte *message = message_router_response->data;
  667. cip_common_packet_format_data->item_count = 2;
  668. cip_common_packet_format_data->data_item.type_id =
  669. kCipItemIdUnconnectedDataItem;
  670. AddNullAddressItem(cip_common_packet_format_data);
  671. message_router_response->reply_service = (0x80 | kForwardOpen);
  672. message_router_response->general_status = general_status;
  673. if (kCipErrorSuccess == general_status) {
  674. OPENER_TRACE_INFO("assembleFWDOpenResponse: sending success response\n");
  675. message_router_response->data_length = 26; /* if there is no application specific data */
  676. message_router_response->size_of_additional_status = 0;
  677. if (cip_common_packet_format_data->address_info_item[0].type_id != 0) {
  678. cip_common_packet_format_data->item_count = 3;
  679. if (cip_common_packet_format_data->address_info_item[1].type_id != 0) {
  680. cip_common_packet_format_data->item_count = 4; /* there are two sockaddrinfo items to add */
  681. }
  682. }
  683. AddDintToMessage(connection_object->cip_consumed_connection_id, &message);
  684. AddDintToMessage(connection_object->cip_produced_connection_id, &message);
  685. } else {
  686. /* we have an connection creation error */
  687. OPENER_TRACE_INFO("AssembleForwardOpenResponse: sending error response\n");
  688. ConnectionObjectSetState(connection_object,
  689. kConnectionObjectStateNonExistent);
  690. message_router_response->data_length = 10;
  691. switch (general_status) {
  692. case kCipErrorNotEnoughData:
  693. case kCipErrorTooMuchData: {
  694. message_router_response->size_of_additional_status = 0;
  695. break;
  696. }
  697. default: {
  698. switch (extended_status) {
  699. case
  700. kConnectionManagerExtendedStatusCodeErrorInvalidOToTConnectionSize:
  701. {
  702. message_router_response->size_of_additional_status = 2;
  703. message_router_response->additional_status[0] = extended_status;
  704. message_router_response->additional_status[1] = connection_object
  705. ->
  706. correct_originator_to_target_size;
  707. break;
  708. }
  709. case
  710. kConnectionManagerExtendedStatusCodeErrorInvalidTToOConnectionSize:
  711. {
  712. message_router_response->size_of_additional_status = 2;
  713. message_router_response->additional_status[0] = extended_status;
  714. message_router_response->additional_status[1] = connection_object
  715. ->
  716. correct_target_to_originator_size;
  717. break;
  718. }
  719. default: {
  720. message_router_response->size_of_additional_status = 1;
  721. message_router_response->additional_status[0] = extended_status;
  722. break;
  723. }
  724. }
  725. break;
  726. }
  727. }
  728. }
  729. AddIntToMessage(connection_object->connection_serial_number, &message);
  730. AddIntToMessage(connection_object->originator_vendor_id, &message);
  731. AddDintToMessage(connection_object->originator_serial_number, &message);
  732. if (kCipErrorSuccess == general_status) {
  733. /* set the actual packet rate to requested packet rate */
  734. AddDintToMessage(connection_object->o_to_t_requested_packet_interval,
  735. &message);
  736. AddDintToMessage(connection_object->t_to_o_requested_packet_interval,
  737. &message);
  738. }
  739. *message = 0; /* remaining path size - for routing devices relevant */
  740. message++;
  741. *message = 0; /* reserved */
  742. message++;
  743. return kEipStatusOkSend; /* send reply */
  744. }
  745. /**
  746. * @brief Adds a Null Address Item to the common data packet format data
  747. * @param common_data_packet_format_data The CPF data packet where the Null Address Item shall be added
  748. */
  749. void AddNullAddressItem(
  750. CipCommonPacketFormatData *common_data_packet_format_data) {
  751. /* Precondition: Null Address Item only valid in unconnected messages */
  752. assert(
  753. common_data_packet_format_data->data_item.type_id
  754. == kCipItemIdUnconnectedDataItem);
  755. common_data_packet_format_data->address_item.type_id = kCipItemIdNullAddress;
  756. common_data_packet_format_data->address_item.length = 0;
  757. }
  758. /* INT8 assembleFWDCloseResponse(UINT16 pa_ConnectionSerialNr, UINT16 pa_OriginatorVendorID, UINT32 pa_OriginatorSerialNr, S_CIP_MR_Request *pa_MRRequest, S_CIP_MR_Response *pa_MRResponse, S_CIP_CPF_Data *pa_CPF_data, INT8 pa_status, INT8 *pa_msg)
  759. * create FWDClose response dependent on status.
  760. * pa_ConnectionSerialNr requested ConnectionSerialNr
  761. * pa_OriginatorVendorID requested OriginatorVendorID
  762. * pa_OriginatorSerialNr requested OriginalSerialNr
  763. * pa_MRRequest pointer to message router request
  764. * pa_MRResponse pointer to message router response
  765. * pa_CPF_data pointer to CPF Data Item
  766. * pa_status status of FWDClose
  767. * pa_msg pointer to memory where reply has to be stored
  768. * return status
  769. * 0 .. no reply need to ne sent back
  770. * 1 .. need to send reply
  771. * -1 .. error
  772. */
  773. EipStatus AssembleForwardCloseResponse(
  774. EipUint16 connection_serial_number,
  775. EipUint16 originatior_vendor_id,
  776. EipUint32 originator_serial_number,
  777. CipMessageRouterRequest *message_router_request,
  778. CipMessageRouterResponse *message_router_response,
  779. EipUint16 extended_error_code
  780. ) {
  781. /* write reply information in CPF struct dependent of pa_status */
  782. CipCommonPacketFormatData *common_data_packet_format_data =
  783. &g_common_packet_format_data_item;
  784. EipByte *message = message_router_response->data;
  785. common_data_packet_format_data->item_count = 2;
  786. common_data_packet_format_data->data_item.type_id =
  787. kCipItemIdUnconnectedDataItem;
  788. AddNullAddressItem(common_data_packet_format_data);
  789. AddIntToMessage(connection_serial_number, &message);
  790. AddIntToMessage(originatior_vendor_id, &message);
  791. AddDintToMessage(originator_serial_number, &message);
  792. message_router_response->reply_service = (0x80
  793. | message_router_request->service);
  794. message_router_response->data_length = 10; /* if there is no application specific data */
  795. if (kConnectionManagerExtendedStatusCodeSuccess == extended_error_code) {
  796. *message = 0; /* no application data */
  797. message_router_response->general_status = kCipErrorSuccess;
  798. message_router_response->size_of_additional_status = 0;
  799. } else {
  800. *message = *message_router_request->data; /* remaining path size */
  801. if (kConnectionManagerExtendedStatusWrongCloser == extended_error_code) {
  802. message_router_response->general_status = kCipErrorPrivilegeViolation;
  803. } else {
  804. message_router_response->general_status = kCipErrorConnectionFailure;
  805. message_router_response->additional_status[0] = extended_error_code;
  806. message_router_response->size_of_additional_status = 1;
  807. }
  808. }
  809. message++;
  810. *message = 0; /* reserved */
  811. message++;
  812. return kEipStatusOkSend;
  813. }
  814. CipConnectionObject *GetConnectedObject(const EipUint32 connection_id) {
  815. DoublyLinkedListNode *iterator = connection_list.first;
  816. while(NULL != iterator) {
  817. if(kConnectionObjectStateEstablished ==
  818. ConnectionObjectGetState(iterator->data) &&
  819. connection_id ==
  820. ConnectionObjectGetCipConsumedConnectionID(iterator->data) ) {
  821. return iterator->data;
  822. }
  823. iterator = iterator->next;
  824. }
  825. return NULL;
  826. }
  827. CipConnectionObject *GetConnectedOutputAssembly(
  828. const EipUint32 output_assembly_id) {
  829. DoublyLinkedListNode *iterator = connection_list.first;
  830. while(NULL != iterator) {
  831. if( kConnectionObjectInstanceTypeIOExclusiveOwner ==
  832. ConnectionObjectGetInstanceType(iterator->data) &&
  833. (kConnectionObjectStateEstablished ==
  834. ConnectionObjectGetState(iterator->data)
  835. || kConnectionObjectStateTimedOut ==
  836. ConnectionObjectGetState(iterator->data) ) &&
  837. output_assembly_id ==
  838. ( (CipConnectionObject *)iterator->data )->produced_path.instance_id ) {
  839. return iterator->data;
  840. }
  841. iterator = iterator->next;
  842. }
  843. return NULL;
  844. }
  845. CipConnectionObject *CheckForExistingConnection(
  846. const CipConnectionObject *const connection_object) {
  847. DoublyLinkedListNode *iterator = connection_list.first;
  848. while(NULL != iterator) {
  849. if(kConnectionObjectStateEstablished ==
  850. ConnectionObjectGetState(iterator->data) ) {
  851. if(EqualConnectionTriad(connection_object, iterator->data) ) {
  852. return iterator->data;
  853. }
  854. }
  855. iterator = iterator->next;
  856. }
  857. return NULL;
  858. }
  859. EipStatus CheckElectronicKeyData(
  860. EipUint8 key_format,
  861. void *key_data,
  862. EipUint16 *extended_status
  863. ) {
  864. /* Default return value */
  865. *extended_status = kConnectionManagerExtendedStatusCodeSuccess;
  866. /* Check key format */
  867. if (4 != key_format) {
  868. *extended_status =
  869. kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
  870. return kEipStatusError;
  871. }
  872. bool compatiblity_mode = ElectronicKeyFormat4GetMajorRevisionCompatibility(
  873. key_data);
  874. /* Check VendorID and ProductCode, must match, or 0 */
  875. if ( ( (ElectronicKeyFormat4GetVendorId(key_data) != vendor_id_) &&
  876. (ElectronicKeyFormat4GetVendorId(key_data) != 0) )
  877. || ( (ElectronicKeyFormat4GetProductCode(key_data) != product_code_)
  878. && (ElectronicKeyFormat4GetProductCode(key_data) != 0) ) ) {
  879. *extended_status =
  880. kConnectionManagerExtendedStatusCodeErrorVendorIdOrProductcodeError;
  881. return kEipStatusError;
  882. } else {
  883. /* VendorID and ProductCode are correct */
  884. /* Check DeviceType, must match or 0 */
  885. if ( (ElectronicKeyFormat4GetDeviceType(key_data) != device_type_)
  886. && (ElectronicKeyFormat4GetDeviceType(key_data) != 0) ) {
  887. *extended_status =
  888. kConnectionManagerExtendedStatusCodeErrorDeviceTypeError;
  889. return kEipStatusError;
  890. } else {
  891. /* VendorID, ProductCode and DeviceType are correct */
  892. if (false == compatiblity_mode) {
  893. /* Major = 0 is valid */
  894. if (0 == ElectronicKeyFormat4GetMajorRevision(key_data) ) {
  895. return kEipStatusOk;
  896. }
  897. /* Check Major / Minor Revision, Major must match, Minor match or 0 */
  898. if ( (ElectronicKeyFormat4GetMajorRevision(key_data) !=
  899. revision_.major_revision)
  900. || ( (ElectronicKeyFormat4GetMinorRevision(key_data) !=
  901. revision_.minor_revision)
  902. && (ElectronicKeyFormat4GetMinorRevision(key_data) != 0) ) ) {
  903. *extended_status =
  904. kConnectionManagerExtendedStatusCodeErrorRevisionMismatch;
  905. return kEipStatusError;
  906. }
  907. } else {
  908. /* Compatibility mode is set */
  909. /* Major must match, Minor != 0 and <= MinorRevision */
  910. if ( (ElectronicKeyFormat4GetMajorRevision(key_data) ==
  911. revision_.major_revision)
  912. && (ElectronicKeyFormat4GetMinorRevision(key_data) > 0)
  913. && (ElectronicKeyFormat4GetMinorRevision(key_data) <=
  914. revision_.minor_revision) ) {
  915. return kEipStatusOk;
  916. } else {
  917. *extended_status =
  918. kConnectionManagerExtendedStatusCodeErrorRevisionMismatch;
  919. return kEipStatusError;
  920. }
  921. } /* end if CompatiblityMode handling */
  922. }
  923. }
  924. return
  925. (*extended_status == kConnectionManagerExtendedStatusCodeSuccess) ?
  926. kEipStatusOk : kEipStatusError;
  927. }
  928. EipUint8 ParseConnectionPath(
  929. CipConnectionObject *connection_object,
  930. CipMessageRouterRequest *message_router_request,
  931. EipUint16 *extended_error
  932. ) {
  933. const EipUint8 *message = message_router_request->data;
  934. const size_t connection_path_size = GetSintFromMessage(&message); /* length in words */
  935. size_t remaining_path = connection_path_size;
  936. CipClass *class = NULL;
  937. CipDword class_id = 0x0;
  938. CipDword instance_id = 0x0;
  939. /* with 256 we mark that we haven't got a PIT segment */
  940. ConnectionObjectSetProductionInhibitTime(connection_object, 256);
  941. if ( (g_kForwardOpenHeaderLength + remaining_path * 2)
  942. < message_router_request->request_path_size ) {
  943. /* the received packet is larger than the data in the path */
  944. *extended_error = 0;
  945. return kCipErrorTooMuchData;
  946. }
  947. if ( (g_kForwardOpenHeaderLength + remaining_path * 2)
  948. > message_router_request->request_path_size ) {
  949. /*there is not enough data in received packet */
  950. *extended_error = 0;
  951. OPENER_TRACE_INFO("Message not long enough for path\n");
  952. return kCipErrorNotEnoughData;
  953. }
  954. if (remaining_path > 0) {
  955. /* first look if there is an electronic key */
  956. if ( kSegmentTypeLogicalSegment == GetPathSegmentType(message) ) {
  957. if ( kLogicalSegmentLogicalTypeSpecial
  958. == GetPathLogicalSegmentLogicalType(message) ) {
  959. if ( kLogicalSegmentSpecialTypeLogicalFormatElectronicKey
  960. == GetPathLogicalSegmentSpecialTypeLogicalType(message) ) {
  961. if ( kElectronicKeySegmentFormatKeyFormat4
  962. == GetPathLogicalSegmentElectronicKeyFormat(message) ) {
  963. /* Check if there is enough data for holding the electronic key segment */
  964. if (remaining_path < 5) {
  965. *extended_error = 0;
  966. OPENER_TRACE_INFO("Message not long enough for electronic key\n");
  967. return kCipErrorNotEnoughData;
  968. }
  969. /* Electronic key format 4 found */
  970. connection_object->electronic_key.key_format = 4;
  971. ElectronicKeyFormat4 *electronic_key = ElectronicKeyFormat4New();
  972. GetElectronicKeyFormat4FromMessage(&message, electronic_key);
  973. /* logical electronic key found */
  974. connection_object->electronic_key.key_data = electronic_key;
  975. remaining_path -= 5; /*length of the electronic key*/
  976. OPENER_TRACE_INFO(
  977. "key: ven ID %d, dev type %d, prod code %d, major %d, minor %d\n",
  978. ElectronicKeyFormat4GetVendorId(connection_object->electronic_key.
  979. key_data),
  980. ElectronicKeyFormat4GetDeviceType(connection_object->
  981. electronic_key.key_data),
  982. ElectronicKeyFormat4GetProductCode(connection_object->
  983. electronic_key.key_data),
  984. ElectronicKeyFormat4GetMajorRevision(connection_object->
  985. electronic_key.key_data),
  986. ElectronicKeyFormat4GetMinorRevision(connection_object->
  987. electronic_key.key_data) );
  988. if ( kEipStatusOk
  989. != CheckElectronicKeyData(
  990. connection_object->electronic_key.key_format,
  991. connection_object->electronic_key.key_data,
  992. extended_error) ) {
  993. ElectronicKeyFormat4Delete(&electronic_key);
  994. return kCipErrorConnectionFailure;
  995. }
  996. ElectronicKeyFormat4Delete(&electronic_key);
  997. }
  998. } else {
  999. OPENER_TRACE_INFO("no key\n");
  1000. }
  1001. }
  1002. }
  1003. //TODO: Refactor this afterwards
  1004. if ( kConnectionObjectTransportClassTriggerProductionTriggerCyclic
  1005. != ConnectionObjectGetTransportClassTriggerProductionTrigger(
  1006. connection_object) ) {
  1007. /*non cyclic connections may have a production inhibit */
  1008. if ( kSegmentTypeNetworkSegment == GetPathSegmentType(message) ) {
  1009. NetworkSegmentSubtype network_segment_subtype =
  1010. GetPathNetworkSegmentSubtype(message);
  1011. if (kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds
  1012. == network_segment_subtype) {
  1013. OPENER_TRACE_INFO("PIT segment available - value: %u\n",message[1]);
  1014. connection_object->production_inhibit_time = message[1];
  1015. message += 2;
  1016. remaining_path -= 1;
  1017. }
  1018. }
  1019. }
  1020. if (kSegmentTypeLogicalSegment == GetPathSegmentType(message) &&
  1021. kLogicalSegmentLogicalTypeClassId ==
  1022. GetPathLogicalSegmentLogicalType(message) ) {
  1023. class_id = CipEpathGetLogicalValue(&message);
  1024. class = GetCipClass(class_id);
  1025. if (NULL == class) {
  1026. OPENER_TRACE_ERR("classid %" PRIx32 " not found\n",
  1027. class_id);
  1028. if (class_id >= 0xC8) { /*reserved range of class ids */
  1029. *extended_error =
  1030. kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
  1031. } else {
  1032. *extended_error =
  1033. kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
  1034. }
  1035. return kCipErrorConnectionFailure;
  1036. }
  1037. OPENER_TRACE_INFO("classid %" PRIx32 " (%s)\n",
  1038. class_id,
  1039. class->class_name);
  1040. } else {
  1041. *extended_error =
  1042. kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
  1043. return kCipErrorConnectionFailure;
  1044. }
  1045. remaining_path -= 1; /* 1 16Bit word for the class part of the path */
  1046. /* Get instance ID */
  1047. if ( kSegmentTypeLogicalSegment == GetPathSegmentType(message) &&
  1048. kLogicalSegmentLogicalTypeInstanceId ==
  1049. GetPathLogicalSegmentLogicalType(message) ) { /* store the configuration ID for later checking in the application connection types */
  1050. instance_id = CipEpathGetLogicalValue(&message);
  1051. OPENER_TRACE_INFO("Configuration instance id %" PRId32 "\n",
  1052. instance_id);
  1053. if ( NULL == GetCipInstance(class, instance_id) ) {
  1054. /*according to the test tool we should respond with this extended error code */
  1055. *extended_error =
  1056. kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
  1057. return kCipErrorConnectionFailure;
  1058. }
  1059. /* 1 or 2 16Bit words for the configuration instance part of the path */
  1060. remaining_path -= (instance_id > 0xFF) ? 2 : 1; //TODO: 32 bit case missing
  1061. } else {
  1062. OPENER_TRACE_INFO("no config data\n");
  1063. }
  1064. if ( kConnectionObjectTransportClassTriggerTransportClass3 ==
  1065. ConnectionObjectGetTransportClassTriggerTransportClass(
  1066. connection_object) )
  1067. {
  1068. /*we have Class 3 connection*/
  1069. if (remaining_path > 0) {
  1070. OPENER_TRACE_WARN(
  1071. "Too much data in connection path for class 3 connection\n");
  1072. *extended_error =
  1073. kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
  1074. return kCipErrorConnectionFailure;
  1075. }
  1076. /* connection end point has to be the message router instance 1 */
  1077. if ( (class_id != kCipMessageRouterClassCode)
  1078. || (1 != instance_id) ) {
  1079. *extended_error =
  1080. kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
  1081. return kCipErrorConnectionFailure;
  1082. }
  1083. /* Configuration connection point is producing connection point */
  1084. CipConnectionPathEpath connection_epath = {
  1085. .class_id = class_id,
  1086. .instance_id = instance_id,
  1087. .attribute_id_or_connection_point = 0
  1088. };
  1089. memcpy(&(connection_object->configuration_path),
  1090. &connection_epath,
  1091. sizeof(connection_object->configuration_path) );
  1092. memcpy(&(connection_object->produced_path), &connection_epath,
  1093. sizeof(connection_object->produced_path) );
  1094. /* End class 3 connection handling */
  1095. } else { /* we have an IO connection */
  1096. CipConnectionPathEpath connection_epath = {
  1097. .class_id = class_id,
  1098. .instance_id = instance_id,
  1099. .attribute_id_or_connection_point = 0
  1100. };
  1101. memcpy(&(connection_object->configuration_path),
  1102. &connection_epath,
  1103. sizeof(connection_object->configuration_path) );
  1104. ConnectionObjectConnectionType originator_to_target_connection_type =
  1105. ConnectionObjectGetOToTConnectionType(
  1106. connection_object);
  1107. ConnectionObjectConnectionType target_to_originator_connection_type =
  1108. ConnectionObjectGetTToOConnectionType(
  1109. connection_object);
  1110. connection_object->consumed_connection_path_length = 0;
  1111. connection_object->consumed_connection_path = NULL;
  1112. //connection_object->connection_path.connection_point[1] = 0; /* set not available path to Invalid */
  1113. size_t number_of_encoded_paths = 0;
  1114. CipConnectionPathEpath *paths_to_encode[2] = { 0 };
  1115. if (kConnectionObjectConnectionTypeNull ==
  1116. originator_to_target_connection_type) {
  1117. if (kConnectionObjectConnectionTypeNull ==
  1118. target_to_originator_connection_type) { /* configuration only connection */
  1119. number_of_encoded_paths = 0;
  1120. OPENER_TRACE_WARN("assembly: type invalid\n");
  1121. } else { /* 1 path -> path is for production */
  1122. OPENER_TRACE_INFO("assembly: type produce\n");
  1123. number_of_encoded_paths = 1;
  1124. paths_to_encode[0] = &(connection_object->produced_path);
  1125. }
  1126. } else {
  1127. if (kConnectionObjectConnectionTypeNull ==
  1128. target_to_originator_connection_type) { /* 1 path -> path is for consumption */
  1129. OPENER_TRACE_INFO("assembly: type consume\n");
  1130. number_of_encoded_paths = 1;
  1131. paths_to_encode[0] = &(connection_object->consumed_path);
  1132. } else { /* 2 paths -> 1st for production 2nd for consumption */
  1133. OPENER_TRACE_INFO("assembly: type bidirectional\n");
  1134. paths_to_encode[0] = &(connection_object->consumed_path);
  1135. paths_to_encode[1] = &(connection_object->produced_path);
  1136. number_of_encoded_paths = 2;
  1137. }
  1138. }
  1139. for (size_t i = 0; i < number_of_encoded_paths; i++) /* process up to 2 encoded paths */
  1140. {
  1141. if ( kLogicalSegmentLogicalTypeInstanceId ==
  1142. GetPathLogicalSegmentLogicalType(message) ||
  1143. kLogicalSegmentLogicalTypeConnectionPoint ==
  1144. GetPathLogicalSegmentLogicalType(message) ) /* Connection Point interpreted as InstanceNr -> only in Assembly Objects */
  1145. { /* Attribute Id or Connection Point */
  1146. CipDword attribute_id = CipEpathGetLogicalValue(&message);
  1147. CipConnectionPathEpath connection_epath = {
  1148. .class_id = class_id,
  1149. .instance_id = attribute_id,
  1150. .attribute_id_or_connection_point = 0
  1151. };
  1152. memcpy(paths_to_encode[i], &connection_epath,
  1153. sizeof(connection_object->produced_path) );
  1154. OPENER_TRACE_INFO(
  1155. "connection point %" PRIu32 "\n",
  1156. attribute_id);
  1157. if ( NULL
  1158. == GetCipInstance(
  1159. class,
  1160. attribute_id) ) { /* Old code - Probably here the attribute ID marks the instance for the assembly object */
  1161. *extended_error =
  1162. kConnectionManagerExtendedStatusCodeInconsistentApplicationPathCombo;
  1163. return kCipErrorConnectionFailure;
  1164. }
  1165. /* 1 or 2 16Bit word for the connection point part of the path */
  1166. remaining_path -= (attribute_id > 0xFF) ? 2 : 1;
  1167. } else {
  1168. *extended_error =
  1169. kConnectionManagerExtendedStatusCodeErrorInvalidSegmentTypeInPath;
  1170. return kCipErrorConnectionFailure;
  1171. }
  1172. }
  1173. g_config_data_length = 0;
  1174. g_config_data_buffer = NULL;
  1175. while (remaining_path > 0) { /* remaining_path_size something left in the path should be configuration data */
  1176. SegmentType segment_type = GetPathSegmentType(message);
  1177. switch (segment_type) {
  1178. case kSegmentTypeDataSegment: {
  1179. DataSegmentSubtype data_segment_type = GetPathDataSegmentSubtype(
  1180. message);
  1181. switch (data_segment_type) {
  1182. case kDataSegmentSubtypeSimpleData:
  1183. g_config_data_length = message[1] * 2; /*data segments store length 16-bit word wise */
  1184. g_config_data_buffer = (EipUint8 *) message + 2;
  1185. remaining_path -= (g_config_data_length + 2) / 2;
  1186. message += (g_config_data_length + 2);
  1187. break;
  1188. default:
  1189. OPENER_TRACE_ERR("Not allowed in connection manager");
  1190. break;
  1191. }
  1192. }
  1193. break;
  1194. case kSegmentTypeNetworkSegment: {
  1195. NetworkSegmentSubtype subtype = GetPathNetworkSegmentSubtype(
  1196. message);
  1197. switch (subtype) {
  1198. case kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds:
  1199. if (
  1200. kConnectionObjectTransportClassTriggerProductionTriggerCyclic
  1201. !=
  1202. ConnectionObjectGetTransportClassTriggerProductionTrigger(
  1203. connection_object) ) {
  1204. /* only non cyclic connections may have a production inhibit */
  1205. connection_object->production_inhibit_time = message[1];
  1206. message += 2;
  1207. remaining_path -= 2;
  1208. } else {
  1209. *extended_error = connection_path_size - remaining_path; /*offset in 16Bit words where within the connection path the error happend*/
  1210. return kCipErrorPathSegmentError; /*status code for invalid segment type*/
  1211. }
  1212. break;
  1213. default:
  1214. OPENER_TRACE_ERR("Not allowed in connection manager");
  1215. break;
  1216. }
  1217. }
  1218. break;
  1219. default:
  1220. OPENER_TRACE_WARN(
  1221. "No data segment identifier found for the configuration data\n");
  1222. *extended_error = connection_path_size - remaining_path; /*offset in 16Bit words where within the connection path the error happend*/
  1223. return
  1224. kConnectionManagerGeneralStatusPathSegmentErrorInUnconnectedSend;
  1225. }
  1226. }
  1227. }
  1228. }
  1229. OPENER_TRACE_INFO("Resulting PIT value: %u\n",
  1230. connection_object->production_inhibit_time);
  1231. /*save back the current position in the stream allowing followers to parse anything thats still there*/
  1232. message_router_request->data = message;
  1233. return kEipStatusOk;
  1234. }
  1235. void CloseConnection(CipConnectionObject *RESTRICT connection_object) {
  1236. if ( kConnectionObjectTransportClassTriggerTransportClass3 !=
  1237. ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
  1238. {
  1239. /* only close the UDP connection for not class 3 connections */
  1240. CloseUdpSocket(
  1241. connection_object->socket[kUdpCommuncationDirectionConsuming]);
  1242. connection_object->socket[kUdpCommuncationDirectionConsuming] =
  1243. kEipInvalidSocket;
  1244. CloseUdpSocket(
  1245. connection_object->socket[kUdpCommuncationDirectionProducing]);
  1246. connection_object->socket[kUdpCommuncationDirectionProducing] =
  1247. kEipInvalidSocket;
  1248. }
  1249. RemoveFromActiveConnections(connection_object);
  1250. ConnectionObjectInitializeEmpty(connection_object);
  1251. }
  1252. void AddNewActiveConnection(const CipConnectionObject *const connection_object)
  1253. {
  1254. DoublyLinkedListInsertAtHead(&connection_list, connection_object);
  1255. ConnectionObjectSetState(connection_object,
  1256. kConnectionObjectStateEstablished);
  1257. }
  1258. void RemoveFromActiveConnections(CipConnectionObject *const connection_object) {
  1259. for(DoublyLinkedListNode *iterator = connection_list.first; iterator != NULL;
  1260. iterator = iterator->next) {
  1261. if(iterator->data == connection_object) {
  1262. DoublyLinkedListRemoveNode(&connection_list, &iterator);
  1263. return;
  1264. }
  1265. }
  1266. OPENER_TRACE_ERR("Connection not found in active connection list\n");
  1267. }
  1268. EipBool8 IsConnectedOutputAssembly(const EipUint32 instance_number) {
  1269. EipBool8 is_connected = false;
  1270. DoublyLinkedListNode *node = connection_list.first;
  1271. while (NULL != node) {
  1272. CipConnectionObject *connection_object = (CipConnectionObject *)node->data;
  1273. CipDword consumed_connection_point =
  1274. connection_object->consumed_path.instance_id;
  1275. if (instance_number == consumed_connection_point &&
  1276. true == ConnectionObjectIsTypeIOConnection(connection_object) ) {
  1277. is_connected = true;
  1278. break;
  1279. }
  1280. node = node->next;
  1281. }
  1282. return is_connected;
  1283. }
  1284. EipStatus AddConnectableObject(
  1285. const EipUint32 class_id,
  1286. OpenConnectionFunction open_connection_function
  1287. ) {
  1288. EipStatus status = kEipStatusError;
  1289. /*parsing is now finished all data is available and check now establish the connection */
  1290. for (size_t i = 0; i < g_kNumberOfConnectableObjects; ++i) {
  1291. if ( (0 == g_connection_management_list[i].class_id)
  1292. || (class_id == g_connection_management_list[i].class_id) ) {
  1293. g_connection_management_list[i].class_id = class_id;
  1294. g_connection_management_list[i].open_connection_function =
  1295. open_connection_function;
  1296. status = kEipStatusOk;
  1297. break;
  1298. }
  1299. }
  1300. return status;
  1301. }
  1302. ConnectionManagementHandling *
  1303. GetConnectionManagementEntry(const EipUint32 class_id) {
  1304. ConnectionManagementHandling *connection_management_entry = NULL;
  1305. for (size_t i = 0; i < g_kNumberOfConnectableObjects; ++i) {
  1306. if (class_id == g_connection_management_list[i].class_id) {
  1307. connection_management_entry = &(g_connection_management_list[i]);
  1308. break;
  1309. }
  1310. }
  1311. return connection_management_entry;
  1312. }
  1313. EipStatus TriggerConnections(
  1314. unsigned int output_assembly,
  1315. unsigned int input_assembly
  1316. ) {
  1317. EipStatus status = kEipStatusError;
  1318. DoublyLinkedListNode *node = connection_list.first;
  1319. while (NULL != node) {
  1320. CipConnectionObject *connection_object = node->data;
  1321. if ( (output_assembly == connection_object->consumed_path.instance_id)
  1322. && (input_assembly ==
  1323. connection_object->produced_path.instance_id) ) {
  1324. if (
  1325. kConnectionObjectTransportClassTriggerProductionTriggerApplicationObject
  1326. == ConnectionObjectGetTransportClassTriggerProductionTrigger(
  1327. connection_object) ) {
  1328. /* produce at the next allowed occurrence */
  1329. connection_object->transmission_trigger_timer = connection_object
  1330. ->
  1331. production_inhibit_time;
  1332. status = kEipStatusOk;
  1333. }
  1334. break;
  1335. }
  1336. }
  1337. return status;
  1338. }
  1339. void CheckForTimedOutConnectionsAndCloseTCPConnections(
  1340. const CipConnectionObject *const connection_object,
  1341. CloseSessionFunction CloseSessions) {
  1342. DoublyLinkedListNode *search_node = connection_list.first;
  1343. bool non_timed_out_connection_found = false;
  1344. while(NULL != search_node) {
  1345. CipConnectionObject *search_connection = search_node->data;
  1346. if(ConnectionObjectEqualOriginator(connection_object, search_connection)
  1347. && connection_object != search_connection
  1348. && kConnectionObjectStateTimedOut !=
  1349. ConnectionObjectGetState(search_connection) ) {
  1350. non_timed_out_connection_found = true;
  1351. break;
  1352. }
  1353. search_node = search_node->next;
  1354. }
  1355. if(false == non_timed_out_connection_found) {
  1356. CloseSessions(connection_object);
  1357. }
  1358. }
  1359. void InitializeConnectionManagerData() {
  1360. memset( g_connection_management_list, 0,
  1361. g_kNumberOfConnectableObjects *
  1362. sizeof(ConnectionManagementHandling) );
  1363. InitializeClass3ConnectionData();
  1364. InitializeIoConnectionData();
  1365. }