ua_client.c 26 KB

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