ua_client.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2015-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2015-2016 (c) Sten Grüner
  7. * Copyright 2015-2016 (c) Chris Iatrou
  8. * Copyright 2015 (c) hfaham
  9. * Copyright 2015-2017 (c) Florian Palm
  10. * Copyright 2017-2018 (c) Thomas Stalder, Blue Time Concept SA
  11. * Copyright 2015 (c) Holger Jeromin
  12. * Copyright 2015 (c) Oleksiy Vasylyev
  13. * Copyright 2016 (c) TorbenD
  14. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  15. * Copyright 2016 (c) Lykurg
  16. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  17. * Copyright 2018 (c) Kalycito Infotech Private Limited
  18. */
  19. #include "ua_client_internal.h"
  20. #include "ua_connection_internal.h"
  21. #include "ua_types_encoding_binary.h"
  22. #include "ua_types_generated_encoding_binary.h"
  23. #include "ua_util.h"
  24. #include "ua_securitypolicies.h"
  25. #include "ua_pki_certificate.h"
  26. #define STATUS_CODE_BAD_POINTER 0x01
  27. /********************/
  28. /* Client Lifecycle */
  29. /********************/
  30. static void
  31. UA_Client_init(UA_Client* client, UA_ClientConfig config) {
  32. memset(client, 0, sizeof(UA_Client));
  33. /* TODO: Select policy according to the endpoint */
  34. UA_SecurityPolicy_None(&client->securityPolicy, NULL, UA_BYTESTRING_NULL, config.logger);
  35. UA_SecureChannel_init(&client->channel);
  36. client->config = config;
  37. if(client->config.stateCallback)
  38. client->config.stateCallback(client, client->state);
  39. /* Catch error during async connection */
  40. client->connectStatus = UA_STATUSCODE_GOOD;
  41. UA_Timer_init(&client->timer);
  42. UA_WorkQueue_init(&client->workQueue);
  43. }
  44. UA_Client *
  45. UA_Client_new(UA_ClientConfig config) {
  46. UA_Client *client = (UA_Client*)UA_malloc(sizeof(UA_Client));
  47. if(!client)
  48. return NULL;
  49. UA_Client_init(client, config);
  50. return client;
  51. }
  52. #ifdef UA_ENABLE_ENCRYPTION
  53. /* Initializes a secure client with the required configuration, certificate
  54. * privatekey, trustlist and revocation list.
  55. *
  56. * @param client client to store configuration
  57. * @param config new secure configuration for client
  58. * @param certificate client certificate
  59. * @param privateKey client's private key
  60. * @param remoteCertificate server certificate form the endpoints
  61. * @param trustList list of trustable certificate
  62. * @param trustListSize count of trustList
  63. * @param revocationList list of revoked digital certificate
  64. * @param revocationListSize count of revocationList
  65. * @param securityPolicyFunction securityPolicy function
  66. * @return Returns a client configuration for secure channel */
  67. static UA_StatusCode
  68. UA_Client_secure_init(UA_Client* client, UA_ClientConfig config,
  69. const UA_ByteString certificate,
  70. const UA_ByteString privateKey,
  71. const UA_ByteString *remoteCertificate,
  72. const UA_ByteString *trustList, size_t trustListSize,
  73. const UA_ByteString *revocationList,
  74. size_t revocationListSize,
  75. UA_SecurityPolicy_Func securityPolicyFunction) {
  76. if(client == NULL || remoteCertificate == NULL)
  77. return STATUS_CODE_BAD_POINTER;
  78. memset(client, 0, sizeof(UA_Client));
  79. /* Allocate memory for certificate verification */
  80. client->securityPolicy.certificateVerification =
  81. (UA_CertificateVerification *)
  82. UA_malloc(sizeof(UA_CertificateVerification));
  83. UA_StatusCode retval =
  84. UA_CertificateVerification_Trustlist(client->securityPolicy.certificateVerification,
  85. trustList, trustListSize,
  86. revocationList, revocationListSize);
  87. if(retval != UA_STATUSCODE_GOOD) {
  88. UA_LOG_ERROR(client->channel.securityPolicy->logger, UA_LOGCATEGORY_SECURECHANNEL,
  89. "Trust list parsing failed with error %s", UA_StatusCode_name(retval));
  90. return retval;
  91. }
  92. /* Initiate client security policy */
  93. retval = (*securityPolicyFunction)(&client->securityPolicy,
  94. client->securityPolicy.certificateVerification,
  95. certificate, privateKey, config.logger);
  96. if(retval != UA_STATUSCODE_GOOD) {
  97. UA_LOG_ERROR(client->channel.securityPolicy->logger, UA_LOGCATEGORY_CLIENT,
  98. "Failed to setup the SecurityPolicy with error %s", UA_StatusCode_name(retval));
  99. return retval;
  100. }
  101. client->config = config;
  102. if(client->config.stateCallback)
  103. client->config.stateCallback(client, client->state);
  104. /* Catch error during async connection */
  105. client->connectStatus = UA_STATUSCODE_GOOD;
  106. UA_Timer_init(&client->timer);
  107. UA_WorkQueue_init(&client->workQueue);
  108. /* Initialize the SecureChannel */
  109. UA_SecureChannel_init(&client->channel);
  110. client->channel.securityMode = UA_MESSAGESECURITYMODE_SIGNANDENCRYPT;
  111. retval = UA_SecureChannel_setSecurityPolicy(&client->channel, &client->securityPolicy,
  112. remoteCertificate);
  113. return retval;
  114. }
  115. /* Creates a new secure client.
  116. *
  117. * @param config new secure configuration for client
  118. * @param certificate client certificate
  119. * @param privateKey client's private key
  120. * @param remoteCertificate server certificate form the endpoints
  121. * @param trustList list of trustable certificate
  122. * @param trustListSize count of trustList
  123. * @param revocationList list of revoked digital certificate
  124. * @param revocationListSize count of revocationList
  125. * @param securityPolicyFunction securityPolicy function
  126. * @return Returns a client with secure configuration */
  127. UA_Client *
  128. UA_Client_secure_new(UA_ClientConfig config, UA_ByteString certificate,
  129. UA_ByteString privateKey, const UA_ByteString *remoteCertificate,
  130. const UA_ByteString *trustList, size_t trustListSize,
  131. const UA_ByteString *revocationList, size_t revocationListSize,
  132. UA_SecurityPolicy_Func securityPolicyFunction) {
  133. if(remoteCertificate == NULL)
  134. return NULL;
  135. UA_Client *client = (UA_Client *)UA_malloc(sizeof(UA_Client));
  136. if(!client)
  137. return NULL;
  138. UA_StatusCode retval = UA_Client_secure_init(client, config, certificate, privateKey,
  139. remoteCertificate, trustList, trustListSize,
  140. revocationList, revocationListSize,
  141. securityPolicyFunction);
  142. if(retval != UA_STATUSCODE_GOOD) {
  143. UA_free(client);
  144. return NULL;
  145. }
  146. return client;
  147. }
  148. #endif
  149. static void
  150. UA_Client_deleteMembers(UA_Client* client) {
  151. UA_Client_disconnect(client);
  152. client->securityPolicy.deleteMembers(&client->securityPolicy);
  153. /* Commented as UA_SecureChannel_deleteMembers already done
  154. * in UA_Client_disconnect function */
  155. //UA_SecureChannel_deleteMembersCleanup(&client->channel);
  156. if (client->connection.free)
  157. client->connection.free(&client->connection);
  158. UA_Connection_deleteMembers(&client->connection);
  159. if(client->endpointUrl.data)
  160. UA_String_deleteMembers(&client->endpointUrl);
  161. UA_UserTokenPolicy_deleteMembers(&client->token);
  162. UA_NodeId_deleteMembers(&client->authenticationToken);
  163. if(client->username.data)
  164. UA_String_deleteMembers(&client->username);
  165. if(client->password.data)
  166. UA_String_deleteMembers(&client->password);
  167. /* Delete the async service calls */
  168. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  169. /* Delete the subscriptions */
  170. #ifdef UA_ENABLE_SUBSCRIPTIONS
  171. UA_Client_Subscriptions_clean(client);
  172. #endif
  173. /* Delete the timed work */
  174. UA_Timer_deleteMembers(&client->timer);
  175. /* Clean up the work queue */
  176. UA_WorkQueue_cleanup(&client->workQueue);
  177. }
  178. void
  179. UA_Client_reset(UA_Client* client) {
  180. UA_Client_deleteMembers(client);
  181. UA_Client_init(client, client->config);
  182. }
  183. void
  184. UA_Client_delete(UA_Client* client) {
  185. /* certificate verification is initialized for secure client
  186. * which is deallocated */
  187. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  188. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  189. if (client->securityPolicy.certificateVerification->deleteMembers)
  190. client->securityPolicy.certificateVerification->deleteMembers(client->securityPolicy.certificateVerification);
  191. UA_free(client->securityPolicy.certificateVerification);
  192. }
  193. UA_Client_deleteMembers(client);
  194. UA_free(client);
  195. }
  196. UA_ClientState
  197. UA_Client_getState(UA_Client *client) {
  198. return client->state;
  199. }
  200. UA_ClientConfig *
  201. UA_Client_getConfig(UA_Client *client) {
  202. if(!client)
  203. return NULL;
  204. return &client->config;
  205. }
  206. /****************/
  207. /* Raw Services */
  208. /****************/
  209. /* For synchronous service calls. Execute async responses with a callback. When
  210. * the response with the correct requestId turns up, return it via the
  211. * SyncResponseDescription pointer. */
  212. typedef struct {
  213. UA_Client *client;
  214. UA_Boolean received;
  215. UA_UInt32 requestId;
  216. void *response;
  217. const UA_DataType *responseType;
  218. } SyncResponseDescription;
  219. /* For both synchronous and asynchronous service calls */
  220. static UA_StatusCode
  221. sendSymmetricServiceRequest(UA_Client *client, const void *request,
  222. const UA_DataType *requestType, UA_UInt32 *requestId) {
  223. /* Make sure we have a valid session */
  224. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  225. /* FIXME: this is just a dirty workaround. We need to rework some of the sync and async processing
  226. * FIXME: in the client. Currently a lot of stuff is semi broken and in dire need of cleaning up.*/
  227. /*UA_StatusCode retval = openSecureChannel(client, true);
  228. if(retval != UA_STATUSCODE_GOOD)
  229. return retval;*/
  230. /* Adjusting the request header. The const attribute is violated, but we
  231. * only touch the following members: */
  232. UA_RequestHeader *rr = (UA_RequestHeader*)(uintptr_t)request;
  233. rr->authenticationToken = client->authenticationToken; /* cleaned up at the end */
  234. rr->timestamp = UA_DateTime_now();
  235. rr->requestHandle = ++client->requestHandle;
  236. /* Send the request */
  237. UA_UInt32 rqId = ++client->requestId;
  238. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  239. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  240. if (client->channel.nextSecurityToken.tokenId != 0) // Change to the new security token if the secure channel has been renewed.
  241. UA_SecureChannel_revolveTokens(&client->channel);
  242. retval = UA_SecureChannel_sendSymmetricMessage(&client->channel, rqId, UA_MESSAGETYPE_MSG,
  243. rr, requestType);
  244. UA_NodeId_init(&rr->authenticationToken); /* Do not return the token to the user */
  245. if(retval != UA_STATUSCODE_GOOD)
  246. return retval;
  247. *requestId = rqId;
  248. return UA_STATUSCODE_GOOD;
  249. }
  250. static const UA_NodeId
  251. serviceFaultId = {0, UA_NODEIDTYPE_NUMERIC, {UA_NS0ID_SERVICEFAULT_ENCODING_DEFAULTBINARY}};
  252. /* Look for the async callback in the linked list, execute and delete it */
  253. static UA_StatusCode
  254. processAsyncResponse(UA_Client *client, UA_UInt32 requestId, const UA_NodeId *responseTypeId,
  255. const UA_ByteString *responseMessage, size_t *offset) {
  256. /* Find the callback */
  257. AsyncServiceCall *ac;
  258. LIST_FOREACH(ac, &client->asyncServiceCalls, pointers) {
  259. if(ac->requestId == requestId)
  260. break;
  261. }
  262. if(!ac)
  263. return UA_STATUSCODE_BADREQUESTHEADERINVALID;
  264. /* Allocate the response */
  265. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  266. void *response = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  267. /* Verify the type of the response */
  268. const UA_DataType *responseType = ac->responseType;
  269. const UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, ac->responseType->binaryEncodingId);
  270. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  271. if(!UA_NodeId_equal(responseTypeId, &expectedNodeId)) {
  272. UA_init(response, ac->responseType);
  273. if(UA_NodeId_equal(responseTypeId, &serviceFaultId)) {
  274. /* Decode as a ServiceFault, i.e. only the response header */
  275. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  276. "Received a ServiceFault response");
  277. responseType = &UA_TYPES[UA_TYPES_SERVICEFAULT];
  278. } else {
  279. /* Close the connection */
  280. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  281. "Reply contains the wrong service response");
  282. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  283. goto process;
  284. }
  285. }
  286. /* Decode the response */
  287. retval = UA_decodeBinary(responseMessage, offset, response, responseType, NULL);
  288. process:
  289. if(retval != UA_STATUSCODE_GOOD) {
  290. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  291. "Could not decode the response with id %u due to %s",
  292. requestId, UA_StatusCode_name(retval));
  293. ((UA_ResponseHeader*)response)->serviceResult = retval;
  294. }
  295. /* Call the callback */
  296. if(ac->callback)
  297. ac->callback(client, ac->userdata, requestId, response);
  298. UA_deleteMembers(response, ac->responseType);
  299. /* Remove the callback */
  300. LIST_REMOVE(ac, pointers);
  301. UA_free(ac);
  302. return retval;
  303. }
  304. /* Processes the received service response. Either with an async callback or by
  305. * decoding the message and returning it "upwards" in the
  306. * SyncResponseDescription. */
  307. static void
  308. processServiceResponse(void *application, UA_SecureChannel *channel,
  309. UA_MessageType messageType, UA_UInt32 requestId,
  310. const UA_ByteString *message) {
  311. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  312. /* Must be OPN or MSG */
  313. if(messageType != UA_MESSAGETYPE_OPN &&
  314. messageType != UA_MESSAGETYPE_MSG) {
  315. UA_LOG_TRACE_CHANNEL(rd->client->config.logger, channel,
  316. "Invalid message type");
  317. return;
  318. }
  319. /* Forward declaration for the goto */
  320. UA_NodeId expectedNodeId = UA_NODEID_NULL;
  321. /* Decode the data type identifier of the response */
  322. size_t offset = 0;
  323. UA_NodeId responseId;
  324. UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset, &responseId);
  325. if(retval != UA_STATUSCODE_GOOD)
  326. goto finish;
  327. /* Got an asynchronous response. Don't expected a synchronous response
  328. * (responseType NULL) or the id does not match. */
  329. if(!rd->responseType || requestId != rd->requestId) {
  330. retval = processAsyncResponse(rd->client, requestId, &responseId, message, &offset);
  331. goto finish;
  332. }
  333. /* Got the synchronous response */
  334. rd->received = true;
  335. /* Check that the response type matches */
  336. expectedNodeId = UA_NODEID_NUMERIC(0, rd->responseType->binaryEncodingId);
  337. if(!UA_NodeId_equal(&responseId, &expectedNodeId)) {
  338. if(UA_NodeId_equal(&responseId, &serviceFaultId)) {
  339. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  340. "Received a ServiceFault response");
  341. UA_init(rd->response, rd->responseType);
  342. retval = UA_decodeBinary(message, &offset, rd->response,
  343. &UA_TYPES[UA_TYPES_SERVICEFAULT], NULL);
  344. } else {
  345. /* Close the connection */
  346. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  347. "Reply contains the wrong service response");
  348. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  349. }
  350. goto finish;
  351. }
  352. #ifdef UA_ENABLE_TYPENAMES
  353. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  354. "Decode a message of type %s", rd->responseType->typeName);
  355. #else
  356. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  357. "Decode a message of type %u", responseId.identifier.numeric);
  358. #endif
  359. /* Decode the response */
  360. retval = UA_decodeBinary(message, &offset, rd->response, rd->responseType,
  361. rd->client->config.customDataTypes);
  362. finish:
  363. UA_NodeId_deleteMembers(&responseId);
  364. if(retval != UA_STATUSCODE_GOOD) {
  365. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  366. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  367. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  368. "Error receiving the response with status code %s",
  369. UA_StatusCode_name(retval));
  370. if(rd->response) {
  371. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  372. respHeader->serviceResult = retval;
  373. }
  374. }
  375. }
  376. /* Forward complete chunks directly to the securechannel */
  377. static UA_StatusCode
  378. client_processChunk(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  379. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  380. UA_StatusCode retval = UA_SecureChannel_decryptAddChunk(&rd->client->channel, chunk, true);
  381. if(retval != UA_STATUSCODE_GOOD)
  382. return retval;
  383. return UA_SecureChannel_persistIncompleteMessages(&rd->client->channel);
  384. }
  385. /* Receive and process messages until a synchronous message arrives or the
  386. * timout finishes */
  387. UA_StatusCode
  388. receiveServiceResponse(UA_Client *client, void *response, const UA_DataType *responseType,
  389. UA_DateTime maxDate, UA_UInt32 *synchronousRequestId) {
  390. /* Prepare the response and the structure we give into processServiceResponse */
  391. SyncResponseDescription rd = { client, false, 0, response, responseType };
  392. /* Return upon receiving the synchronized response. All other responses are
  393. * processed with a callback "in the background". */
  394. if(synchronousRequestId)
  395. rd.requestId = *synchronousRequestId;
  396. UA_StatusCode retval;
  397. do {
  398. UA_DateTime now = UA_DateTime_nowMonotonic();
  399. /* >= avoid timeout to be set to 0 */
  400. if(now >= maxDate)
  401. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  402. /* round always to upper value to avoid timeout to be set to 0
  403. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  404. UA_UInt32 timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  405. retval = UA_Connection_receiveChunksBlocking(&client->connection, &rd, client_processChunk, timeout);
  406. UA_SecureChannel_processCompleteMessages(&client->channel, &rd, processServiceResponse);
  407. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  408. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  409. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  410. UA_Client_disconnect(client);
  411. break;
  412. }
  413. } while(!rd.received);
  414. return retval;
  415. }
  416. void
  417. __UA_Client_Service(UA_Client *client, const void *request,
  418. const UA_DataType *requestType, void *response,
  419. const UA_DataType *responseType) {
  420. UA_init(response, responseType);
  421. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  422. /* Send the request */
  423. UA_UInt32 requestId;
  424. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &requestId);
  425. if(retval != UA_STATUSCODE_GOOD) {
  426. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  427. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  428. else
  429. respHeader->serviceResult = retval;
  430. UA_Client_disconnect(client);
  431. return;
  432. }
  433. /* Retrieve the response */
  434. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  435. (client->config.timeout * UA_DATETIME_MSEC);
  436. retval = receiveServiceResponse(client, response, responseType, maxDate, &requestId);
  437. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  438. /* In synchronous service, if we have don't have a reply we need to close the connection */
  439. UA_Client_disconnect(client);
  440. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  441. }
  442. if(retval != UA_STATUSCODE_GOOD)
  443. respHeader->serviceResult = retval;
  444. }
  445. UA_StatusCode
  446. receiveServiceResponseAsync(UA_Client *client, void *response,
  447. const UA_DataType *responseType) {
  448. SyncResponseDescription rd = { client, false, 0, response, responseType };
  449. UA_StatusCode retval = UA_Connection_receiveChunksNonBlocking(
  450. &client->connection, &rd, client_processChunk);
  451. UA_SecureChannel_processCompleteMessages(&client->channel, &rd, processServiceResponse);
  452. /*let client run when non critical timeout*/
  453. if(retval != UA_STATUSCODE_GOOD
  454. && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  455. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  456. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  457. }
  458. UA_Client_disconnect(client);
  459. }
  460. return retval;
  461. }
  462. UA_StatusCode
  463. receivePacketAsync(UA_Client *client) {
  464. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  465. if (UA_Client_getState(client) == UA_CLIENTSTATE_DISCONNECTED ||
  466. UA_Client_getState(client) == UA_CLIENTSTATE_WAITING_FOR_ACK) {
  467. retval = UA_Connection_receiveChunksNonBlocking(&client->connection, client, processACKResponseAsync);
  468. }
  469. else if(UA_Client_getState(client) == UA_CLIENTSTATE_CONNECTED) {
  470. retval = UA_Connection_receiveChunksNonBlocking(&client->connection, client, processOPNResponseAsync);
  471. }
  472. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  473. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  474. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  475. UA_Client_disconnect(client);
  476. }
  477. return retval;
  478. }
  479. void
  480. UA_Client_AsyncService_cancel(UA_Client *client, AsyncServiceCall *ac,
  481. UA_StatusCode statusCode) {
  482. /* Create an empty response with the statuscode */
  483. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  484. void *resp = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  485. UA_init(resp, ac->responseType);
  486. ((UA_ResponseHeader*)resp)->serviceResult = statusCode;
  487. if(ac->callback)
  488. ac->callback(client, ac->userdata, ac->requestId, resp);
  489. /* Clean up the response. Users might move data into it. For whatever reasons. */
  490. UA_deleteMembers(resp, ac->responseType);
  491. }
  492. void UA_Client_AsyncService_removeAll(UA_Client *client, UA_StatusCode statusCode) {
  493. AsyncServiceCall *ac, *ac_tmp;
  494. LIST_FOREACH_SAFE(ac, &client->asyncServiceCalls, pointers, ac_tmp) {
  495. LIST_REMOVE(ac, pointers);
  496. UA_Client_AsyncService_cancel(client, ac, statusCode);
  497. UA_free(ac);
  498. }
  499. }
  500. UA_StatusCode
  501. __UA_Client_AsyncServiceEx(UA_Client *client, const void *request,
  502. const UA_DataType *requestType,
  503. UA_ClientAsyncServiceCallback callback,
  504. const UA_DataType *responseType,
  505. void *userdata, UA_UInt32 *requestId,
  506. UA_UInt32 timeout) {
  507. /* Prepare the entry for the linked list */
  508. AsyncServiceCall *ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  509. if(!ac)
  510. return UA_STATUSCODE_BADOUTOFMEMORY;
  511. ac->callback = callback;
  512. ac->responseType = responseType;
  513. ac->userdata = userdata;
  514. ac->timeout = timeout;
  515. /* Call the service and set the requestId */
  516. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &ac->requestId);
  517. if(retval != UA_STATUSCODE_GOOD) {
  518. UA_free(ac);
  519. return retval;
  520. }
  521. ac->start = UA_DateTime_nowMonotonic();
  522. /* Store the entry for async processing */
  523. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  524. if(requestId)
  525. *requestId = ac->requestId;
  526. return UA_STATUSCODE_GOOD;
  527. }
  528. UA_StatusCode
  529. __UA_Client_AsyncService(UA_Client *client, const void *request,
  530. const UA_DataType *requestType,
  531. UA_ClientAsyncServiceCallback callback,
  532. const UA_DataType *responseType,
  533. void *userdata, UA_UInt32 *requestId) {
  534. return __UA_Client_AsyncServiceEx(client, request, requestType, callback,
  535. responseType, userdata, requestId,
  536. client->config.timeout);
  537. }
  538. UA_StatusCode
  539. UA_Client_sendAsyncRequest(UA_Client *client, const void *request,
  540. const UA_DataType *requestType,
  541. UA_ClientAsyncServiceCallback callback,
  542. const UA_DataType *responseType, void *userdata,
  543. UA_UInt32 *requestId) {
  544. if (UA_Client_getState(client) < UA_CLIENTSTATE_SECURECHANNEL) {
  545. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  546. "Cient must be connected to send high-level requests");
  547. return UA_STATUSCODE_GOOD;
  548. }
  549. return __UA_Client_AsyncService(client, request, requestType, callback,
  550. responseType, userdata, requestId);
  551. }
  552. UA_StatusCode
  553. UA_Client_addRepeatedCallback(UA_Client *client, UA_ClientCallback callback,
  554. void *data, UA_UInt32 interval,
  555. UA_UInt64 *callbackId) {
  556. return UA_Timer_addRepeatedCallback(&client->timer,
  557. (UA_ApplicationCallback) callback, client, data,
  558. interval, callbackId);
  559. }
  560. UA_StatusCode
  561. UA_Client_removeRepeatedCallback(UA_Client *client, UA_UInt64 callbackId) {
  562. return UA_Timer_removeRepeatedCallback(&client->timer, callbackId);
  563. }