ua_client.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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.h"
  20. #include "ua_client_internal.h"
  21. #include "ua_connection_internal.h"
  22. #include "ua_types_encoding_binary.h"
  23. #include "ua_types_generated_encoding_binary.h"
  24. #include "ua_util.h"
  25. #include "ua_securitypolicies.h"
  26. #include "ua_pki_certificate.h"
  27. #define STATUS_CODE_BAD_POINTER 0x01
  28. /********************/
  29. /* Client Lifecycle */
  30. /********************/
  31. static void
  32. UA_Client_init(UA_Client* client, UA_ClientConfig config) {
  33. memset(client, 0, sizeof(UA_Client));
  34. /* TODO: Select policy according to the endpoint */
  35. UA_SecurityPolicy_None(&client->securityPolicy, NULL, UA_BYTESTRING_NULL, config.logger);
  36. UA_SecureChannel_init(&client->channel);
  37. client->config = config;
  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,
  289. responseType, 0, NULL);
  290. process:
  291. if(retval != UA_STATUSCODE_GOOD) {
  292. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  293. "Could not decode the response with id %u due to %s",
  294. requestId, UA_StatusCode_name(retval));
  295. ((UA_ResponseHeader*)response)->serviceResult = retval;
  296. }
  297. /* Call the 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], 0, 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.customDataTypesSize,
  363. rd->client->config.customDataTypes);
  364. finish:
  365. UA_NodeId_deleteMembers(&responseId);
  366. if(retval != UA_STATUSCODE_GOOD) {
  367. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  368. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  369. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  370. "Error receiving the response with status code %s",
  371. UA_StatusCode_name(retval));
  372. if(rd->response) {
  373. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  374. respHeader->serviceResult = retval;
  375. }
  376. }
  377. }
  378. /* Forward complete chunks directly to the securechannel */
  379. static UA_StatusCode
  380. client_processChunk(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  381. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  382. UA_StatusCode retval = UA_SecureChannel_decryptAddChunk(&rd->client->channel, chunk, UA_TRUE);
  383. if(retval != UA_STATUSCODE_GOOD)
  384. return retval;
  385. return UA_SecureChannel_persistIncompleteMessages(&rd->client->channel);
  386. }
  387. /* Receive and process messages until a synchronous message arrives or the
  388. * timout finishes */
  389. UA_StatusCode
  390. receiveServiceResponse(UA_Client *client, void *response, const UA_DataType *responseType,
  391. UA_DateTime maxDate, UA_UInt32 *synchronousRequestId) {
  392. /* Prepare the response and the structure we give into processServiceResponse */
  393. SyncResponseDescription rd = { client, false, 0, response, responseType };
  394. /* Return upon receiving the synchronized response. All other responses are
  395. * processed with a callback "in the background". */
  396. if(synchronousRequestId)
  397. rd.requestId = *synchronousRequestId;
  398. UA_StatusCode retval;
  399. do {
  400. UA_DateTime now = UA_DateTime_nowMonotonic();
  401. /* >= avoid timeout to be set to 0 */
  402. if(now >= maxDate)
  403. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  404. /* round always to upper value to avoid timeout to be set to 0
  405. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  406. UA_UInt32 timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  407. retval = UA_Connection_receiveChunksBlocking(&client->connection, &rd, client_processChunk, timeout);
  408. UA_SecureChannel_processCompleteMessages(&client->channel, &rd, processServiceResponse);
  409. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  410. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  411. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  412. UA_Client_disconnect(client);
  413. break;
  414. }
  415. } while(!rd.received);
  416. return retval;
  417. }
  418. void
  419. __UA_Client_Service(UA_Client *client, const void *request,
  420. const UA_DataType *requestType, void *response,
  421. const UA_DataType *responseType) {
  422. UA_init(response, responseType);
  423. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  424. /* Send the request */
  425. UA_UInt32 requestId;
  426. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &requestId);
  427. if(retval != UA_STATUSCODE_GOOD) {
  428. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  429. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  430. else
  431. respHeader->serviceResult = retval;
  432. UA_Client_disconnect(client);
  433. return;
  434. }
  435. /* Retrieve the response */
  436. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  437. (client->config.timeout * UA_DATETIME_MSEC);
  438. retval = receiveServiceResponse(client, response, responseType, maxDate, &requestId);
  439. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  440. /* In synchronous service, if we have don't have a reply we need to close the connection */
  441. UA_Client_disconnect(client);
  442. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  443. }
  444. if(retval != UA_STATUSCODE_GOOD)
  445. respHeader->serviceResult = retval;
  446. }
  447. UA_StatusCode
  448. receiveServiceResponseAsync(UA_Client *client, void *response,
  449. const UA_DataType *responseType) {
  450. SyncResponseDescription rd = { client, false, 0, response, responseType };
  451. UA_StatusCode retval = UA_Connection_receiveChunksNonBlocking(
  452. &client->connection, &rd, client_processChunk);
  453. UA_SecureChannel_processCompleteMessages(&client->channel, &rd, processServiceResponse);
  454. /*let client run when non critical timeout*/
  455. if(retval != UA_STATUSCODE_GOOD
  456. && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  457. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  458. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  459. }
  460. UA_Client_disconnect(client);
  461. }
  462. return retval;
  463. }
  464. UA_StatusCode
  465. receivePacketAsync(UA_Client *client) {
  466. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  467. if (UA_Client_getState(client) == UA_CLIENTSTATE_DISCONNECTED ||
  468. UA_Client_getState(client) == UA_CLIENTSTATE_WAITING_FOR_ACK) {
  469. retval = UA_Connection_receiveChunksNonBlocking(
  470. &client->connection, client, client->ackResponseCallback);
  471. }
  472. else if(UA_Client_getState(client) == UA_CLIENTSTATE_CONNECTED) {
  473. retval = UA_Connection_receiveChunksNonBlocking(
  474. &client->connection, client,
  475. client->openSecureChannelResponseCallback);
  476. }
  477. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  478. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  479. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  480. UA_Client_disconnect(client);
  481. }
  482. return retval;
  483. }
  484. void
  485. UA_Client_AsyncService_cancel(UA_Client *client, AsyncServiceCall *ac,
  486. UA_StatusCode statusCode) {
  487. /* Create an empty response with the statuscode */
  488. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  489. void *resp = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  490. UA_init(resp, ac->responseType);
  491. ((UA_ResponseHeader*)resp)->serviceResult = statusCode;
  492. ac->callback(client, ac->userdata, ac->requestId, resp);
  493. /* Clean up the response. Users might move data into it. For whatever reasons. */
  494. UA_deleteMembers(resp, ac->responseType);
  495. }
  496. void UA_Client_AsyncService_removeAll(UA_Client *client, UA_StatusCode statusCode) {
  497. AsyncServiceCall *ac, *ac_tmp;
  498. LIST_FOREACH_SAFE(ac, &client->asyncServiceCalls, pointers, ac_tmp) {
  499. LIST_REMOVE(ac, pointers);
  500. UA_Client_AsyncService_cancel(client, ac, statusCode);
  501. UA_free(ac);
  502. }
  503. }
  504. UA_StatusCode
  505. __UA_Client_AsyncServiceEx(UA_Client *client, const void *request,
  506. const UA_DataType *requestType,
  507. UA_ClientAsyncServiceCallback callback,
  508. const UA_DataType *responseType,
  509. void *userdata, UA_UInt32 *requestId,
  510. UA_UInt32 timeout) {
  511. /* Prepare the entry for the linked list */
  512. AsyncServiceCall *ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  513. if(!ac)
  514. return UA_STATUSCODE_BADOUTOFMEMORY;
  515. ac->callback = callback;
  516. ac->responseType = responseType;
  517. ac->userdata = userdata;
  518. ac->timeout = timeout;
  519. /* Call the service and set the requestId */
  520. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &ac->requestId);
  521. if(retval != UA_STATUSCODE_GOOD) {
  522. UA_free(ac);
  523. return retval;
  524. }
  525. ac->start = UA_DateTime_nowMonotonic();
  526. /* Store the entry for async processing */
  527. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  528. if(requestId)
  529. *requestId = ac->requestId;
  530. return UA_STATUSCODE_GOOD;
  531. }
  532. UA_StatusCode
  533. __UA_Client_AsyncService(UA_Client *client, const void *request,
  534. const UA_DataType *requestType,
  535. UA_ClientAsyncServiceCallback callback,
  536. const UA_DataType *responseType,
  537. void *userdata, UA_UInt32 *requestId) {
  538. return __UA_Client_AsyncServiceEx(client, request, requestType, callback,
  539. responseType, userdata, requestId,
  540. client->config.timeout);
  541. }
  542. UA_StatusCode
  543. UA_Client_sendAsyncRequest(UA_Client *client, const void *request,
  544. const UA_DataType *requestType,
  545. UA_ClientAsyncServiceCallback callback,
  546. const UA_DataType *responseType, void *userdata,
  547. UA_UInt32 *requestId) {
  548. if (UA_Client_getState(client) < UA_CLIENTSTATE_SECURECHANNEL) {
  549. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  550. "Cient must be connected to send high-level requests");
  551. return UA_STATUSCODE_GOOD;
  552. }
  553. return __UA_Client_AsyncService(client, request, requestType, callback,
  554. responseType, userdata, requestId);
  555. }
  556. UA_StatusCode
  557. UA_Client_addRepeatedCallback(UA_Client *client, UA_ClientCallback callback,
  558. void *data, UA_UInt32 interval,
  559. UA_UInt64 *callbackId) {
  560. return UA_Timer_addRepeatedCallback(&client->timer,
  561. (UA_ApplicationCallback) callback, client, data,
  562. interval, callbackId);
  563. }
  564. UA_StatusCode
  565. UA_Client_removeRepeatedCallback(UA_Client *client, UA_UInt64 callbackId) {
  566. return UA_Timer_removeRepeatedCallback(&client->timer, callbackId);
  567. }