ua_client.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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_securitypolicy_none.h"
  26. #include "ua_securitypolicy_basic128rsa15.h"
  27. #include "ua_pki_certificate.h"
  28. #define STATUS_CODE_BAD_POINTER 0x01
  29. /********************/
  30. /* Client Lifecycle */
  31. /********************/
  32. static void
  33. UA_Client_init(UA_Client* client, UA_ClientConfig config) {
  34. memset(client, 0, sizeof(UA_Client));
  35. /* TODO: Select policy according to the endpoint */
  36. UA_SecurityPolicy_None(&client->securityPolicy, NULL, UA_BYTESTRING_NULL, config.logger);
  37. client->channel.securityPolicy = &client->securityPolicy;
  38. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  39. client->config = config;
  40. if(client->config.stateCallback)
  41. client->config.stateCallback(client, client->state);
  42. }
  43. UA_Client *
  44. UA_Client_new(UA_ClientConfig config) {
  45. UA_Client *client = (UA_Client*)UA_malloc(sizeof(UA_Client));
  46. if(!client)
  47. return NULL;
  48. UA_Client_init(client, config);
  49. return client;
  50. }
  51. #ifdef UA_ENABLE_ENCRYPTION
  52. /* Initializes a secure client with the required configuration, certificate
  53. * privatekey, trustlist and revocation list.
  54. *
  55. * @param client client to store configuration
  56. * @param config new secure configuration for client
  57. * @param certificate client certificate
  58. * @param privateKey client's private key
  59. * @param remoteCertificate server certificate form the endpoints
  60. * @param trustList list of trustable certificate
  61. * @param trustListSize count of trustList
  62. * @param revocationList list of revoked digital certificate
  63. * @param revocationListSize count of revocationList
  64. * @param securityPolicyFunction securityPolicy function
  65. * @return Returns a client configuration for secure channel */
  66. static UA_StatusCode
  67. UA_Client_secure_init(UA_Client* client, UA_ClientConfig config,
  68. const UA_ByteString certificate,
  69. const UA_ByteString privateKey,
  70. const UA_ByteString *remoteCertificate,
  71. const UA_ByteString *trustList, size_t trustListSize,
  72. const UA_ByteString *revocationList,
  73. size_t revocationListSize,
  74. UA_SecurityPolicy_Func securityPolicyFunction) {
  75. if(client == NULL || remoteCertificate == NULL)
  76. return STATUS_CODE_BAD_POINTER;
  77. memset(client, 0, sizeof(UA_Client));
  78. /* Allocate memory for certificate verification */
  79. client->securityPolicy.certificateVerification =
  80. (UA_CertificateVerification *)
  81. UA_malloc(sizeof(UA_CertificateVerification));
  82. UA_StatusCode retval =
  83. UA_CertificateVerification_Trustlist(client->securityPolicy.certificateVerification,
  84. trustList, trustListSize,
  85. revocationList, revocationListSize);
  86. if(retval != UA_STATUSCODE_GOOD)
  87. return retval;
  88. /* Initiate client security policy */
  89. (*securityPolicyFunction)(&client->securityPolicy,
  90. client->securityPolicy.certificateVerification,
  91. certificate, privateKey, config.logger);
  92. client->channel.securityPolicy = &client->securityPolicy;
  93. client->channel.securityMode = UA_MESSAGESECURITYMODE_SIGNANDENCRYPT;
  94. client->config = config;
  95. if(client->config.stateCallback)
  96. client->config.stateCallback(client, client->state);
  97. if(client->channel.securityPolicy->certificateVerification != NULL) {
  98. retval = client->channel.securityPolicy->certificateVerification->
  99. verifyCertificate(client->channel.securityPolicy->certificateVerification->context,
  100. remoteCertificate);
  101. } else {
  102. UA_LOG_WARNING(client->channel.securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  103. "No PKI plugin set. Accepting all certificates");
  104. }
  105. const UA_SecurityPolicy *securityPolicy = (UA_SecurityPolicy *) &client->securityPolicy;
  106. retval = client->securityPolicy.channelModule.newContext(securityPolicy, remoteCertificate,
  107. &client->channel.channelContext);
  108. if(retval != UA_STATUSCODE_GOOD)
  109. return retval;
  110. retval = UA_ByteString_copy(remoteCertificate, &client->channel.remoteCertificate);
  111. if(retval != UA_STATUSCODE_GOOD)
  112. return retval;
  113. UA_ByteString remoteCertificateThumbprint = {20, client->channel.remoteCertificateThumbprint};
  114. /* Invoke remote certificate thumbprint */
  115. retval = client->securityPolicy.asymmetricModule.
  116. makeCertificateThumbprint(securityPolicy, &client->channel.remoteCertificate,
  117. &remoteCertificateThumbprint);
  118. return retval;
  119. }
  120. /* Creates a new secure client.
  121. *
  122. * @param config new secure configuration for client
  123. * @param certificate client certificate
  124. * @param privateKey client's private key
  125. * @param remoteCertificate server certificate form the endpoints
  126. * @param trustList list of trustable certificate
  127. * @param trustListSize count of trustList
  128. * @param revocationList list of revoked digital certificate
  129. * @param revocationListSize count of revocationList
  130. * @param securityPolicyFunction securityPolicy function
  131. * @return Returns a client with secure configuration */
  132. UA_Client *
  133. UA_Client_secure_new(UA_ClientConfig config, UA_ByteString certificate,
  134. UA_ByteString privateKey, const UA_ByteString *remoteCertificate,
  135. const UA_ByteString *trustList, size_t trustListSize,
  136. const UA_ByteString *revocationList, size_t revocationListSize,
  137. UA_SecurityPolicy_Func securityPolicyFunction) {
  138. if(remoteCertificate == NULL)
  139. return NULL;
  140. UA_Client *client = (UA_Client *)UA_malloc(sizeof(UA_Client));
  141. if(!client)
  142. return NULL;
  143. UA_StatusCode retval = UA_Client_secure_init(client, config, certificate, privateKey,
  144. remoteCertificate, trustList, trustListSize,
  145. revocationList, revocationListSize,
  146. securityPolicyFunction);
  147. if(retval != UA_STATUSCODE_GOOD){
  148. return NULL;
  149. }
  150. return client;
  151. }
  152. #endif
  153. static void
  154. UA_Client_deleteMembers(UA_Client* client) {
  155. UA_Client_disconnect(client);
  156. client->securityPolicy.deleteMembers(&client->securityPolicy);
  157. /* Commented as UA_SecureChannel_deleteMembers already done
  158. * in UA_Client_disconnect function */
  159. //UA_SecureChannel_deleteMembersCleanup(&client->channel);
  160. UA_Connection_deleteMembers(&client->connection);
  161. if(client->endpointUrl.data)
  162. UA_String_deleteMembers(&client->endpointUrl);
  163. UA_UserTokenPolicy_deleteMembers(&client->token);
  164. UA_NodeId_deleteMembers(&client->authenticationToken);
  165. if(client->username.data)
  166. UA_String_deleteMembers(&client->username);
  167. if(client->password.data)
  168. UA_String_deleteMembers(&client->password);
  169. /* Delete the async service calls */
  170. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  171. /* Delete the subscriptions */
  172. #ifdef UA_ENABLE_SUBSCRIPTIONS
  173. UA_Client_Subscriptions_clean(client);
  174. #endif
  175. }
  176. void
  177. UA_Client_reset(UA_Client* client) {
  178. UA_Client_deleteMembers(client);
  179. UA_Client_init(client, client->config);
  180. }
  181. void
  182. UA_Client_delete(UA_Client* client) {
  183. /* certificate verification is initialized for secure client
  184. * which is deallocated */
  185. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  186. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  187. if (client->securityPolicy.certificateVerification->deleteMembers)
  188. client->securityPolicy.certificateVerification->deleteMembers(client->securityPolicy.certificateVerification);
  189. UA_free(client->securityPolicy.certificateVerification);
  190. }
  191. UA_Client_deleteMembers(client);
  192. UA_free(client);
  193. }
  194. UA_ClientState
  195. UA_Client_getState(UA_Client *client) {
  196. return client->state;
  197. }
  198. void *
  199. UA_Client_getContext(UA_Client *client) {
  200. if(!client)
  201. return NULL;
  202. return client->config.clientContext;
  203. }
  204. /****************/
  205. /* Raw Services */
  206. /****************/
  207. /* For synchronous service calls. Execute async responses with a callback. When
  208. * the response with the correct requestId turns up, return it via the
  209. * SyncResponseDescription pointer. */
  210. typedef struct {
  211. UA_Client *client;
  212. UA_Boolean received;
  213. UA_UInt32 requestId;
  214. void *response;
  215. const UA_DataType *responseType;
  216. } SyncResponseDescription;
  217. /* For both synchronous and asynchronous service calls */
  218. static UA_StatusCode
  219. sendSymmetricServiceRequest(UA_Client *client, const void *request,
  220. const UA_DataType *requestType, UA_UInt32 *requestId) {
  221. /* Make sure we have a valid session */
  222. UA_StatusCode retval = UA_Client_manuallyRenewSecureChannel(client);
  223. if(retval != UA_STATUSCODE_GOOD)
  224. return retval;
  225. /* Adjusting the request header. The const attribute is violated, but we
  226. * only touch the following members: */
  227. UA_RequestHeader *rr = (UA_RequestHeader*)(uintptr_t)request;
  228. rr->authenticationToken = client->authenticationToken; /* cleaned up at the end */
  229. rr->timestamp = UA_DateTime_now();
  230. rr->requestHandle = ++client->requestHandle;
  231. /* Send the request */
  232. UA_UInt32 rqId = ++client->requestId;
  233. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  234. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  235. retval = UA_SecureChannel_sendSymmetricMessage(&client->channel, rqId, UA_MESSAGETYPE_MSG,
  236. rr, requestType);
  237. UA_NodeId_init(&rr->authenticationToken); /* Do not return the token to the user */
  238. if(retval != UA_STATUSCODE_GOOD)
  239. return retval;
  240. *requestId = rqId;
  241. return UA_STATUSCODE_GOOD;
  242. }
  243. static const UA_NodeId
  244. serviceFaultId = {0, UA_NODEIDTYPE_NUMERIC, {UA_NS0ID_SERVICEFAULT_ENCODING_DEFAULTBINARY}};
  245. /* Look for the async callback in the linked list, execute and delete it */
  246. static UA_StatusCode
  247. processAsyncResponse(UA_Client *client, UA_UInt32 requestId, const UA_NodeId *responseTypeId,
  248. const UA_ByteString *responseMessage, size_t *offset) {
  249. /* Find the callback */
  250. AsyncServiceCall *ac;
  251. LIST_FOREACH(ac, &client->asyncServiceCalls, pointers) {
  252. if(ac->requestId == requestId)
  253. break;
  254. }
  255. if(!ac)
  256. return UA_STATUSCODE_BADREQUESTHEADERINVALID;
  257. /* Allocate the response */
  258. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  259. void *response = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  260. /* Verify the type of the response */
  261. const UA_DataType *responseType = ac->responseType;
  262. const UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, ac->responseType->binaryEncodingId);
  263. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  264. if(!UA_NodeId_equal(responseTypeId, &expectedNodeId)) {
  265. UA_init(response, ac->responseType);
  266. if(UA_NodeId_equal(responseTypeId, &serviceFaultId)) {
  267. /* Decode as a ServiceFault, i.e. only the response header */
  268. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  269. "Received a ServiceFault response");
  270. responseType = &UA_TYPES[UA_TYPES_SERVICEFAULT];
  271. } else {
  272. /* Close the connection */
  273. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  274. "Reply contains the wrong service response");
  275. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  276. goto process;
  277. }
  278. }
  279. /* Decode the response */
  280. retval = UA_decodeBinary(responseMessage, offset, response,
  281. responseType, 0, NULL);
  282. process:
  283. if(retval != UA_STATUSCODE_GOOD) {
  284. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  285. "Could not decode the response with id %u due to %s",
  286. requestId, UA_StatusCode_name(retval));
  287. ((UA_ResponseHeader*)response)->serviceResult = retval;
  288. }
  289. /* Call the callback */
  290. ac->callback(client, ac->userdata, requestId, response, ac->responseType);
  291. UA_deleteMembers(response, ac->responseType);
  292. /* Remove the callback */
  293. LIST_REMOVE(ac, pointers);
  294. UA_free(ac);
  295. return retval;
  296. }
  297. /* Processes the received service response. Either with an async callback or by
  298. * decoding the message and returning it "upwards" in the
  299. * SyncResponseDescription. */
  300. static UA_StatusCode
  301. processServiceResponse(void *application, UA_SecureChannel *channel,
  302. UA_MessageType messageType, UA_UInt32 requestId,
  303. const UA_ByteString *message) {
  304. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  305. /* Must be OPN or MSG */
  306. if(messageType != UA_MESSAGETYPE_OPN &&
  307. messageType != UA_MESSAGETYPE_MSG) {
  308. UA_LOG_TRACE_CHANNEL(rd->client->config.logger, channel,
  309. "Invalid message type");
  310. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  311. }
  312. /* Has the SecureChannel timed out?
  313. * TODO: Solve this for client and server together */
  314. if(rd->client->state >= UA_CLIENTSTATE_SECURECHANNEL &&
  315. (channel->securityToken.createdAt +
  316. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  317. < UA_DateTime_nowMonotonic())
  318. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  319. /* Decode the data type identifier of the response */
  320. size_t offset = 0;
  321. UA_NodeId responseId;
  322. UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset, &responseId);
  323. if(retval != UA_STATUSCODE_GOOD)
  324. goto finish;
  325. /* Got an asynchronous response. Don't expected a synchronous response
  326. * (responseType NULL) or the id does not match. */
  327. if(!rd->responseType || requestId != rd->requestId) {
  328. retval = processAsyncResponse(rd->client, requestId, &responseId, message, &offset);
  329. goto finish;
  330. }
  331. /* Got the synchronous response */
  332. rd->received = true;
  333. /* Forward declaration for the goto */
  334. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, rd->responseType->binaryEncodingId);
  335. /* Check that the response type matches */
  336. if(!UA_NodeId_equal(&responseId, &expectedNodeId)) {
  337. if(UA_NodeId_equal(&responseId, &serviceFaultId)) {
  338. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  339. "Received a ServiceFault response");
  340. UA_init(rd->response, rd->responseType);
  341. retval = UA_decodeBinary(message, &offset, rd->response,
  342. &UA_TYPES[UA_TYPES_SERVICEFAULT], 0, NULL);
  343. } else {
  344. /* Close the connection */
  345. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  346. "Reply contains the wrong service response");
  347. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  348. }
  349. goto finish;
  350. }
  351. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  352. "Decode a message of type %u", responseId.identifier.numeric);
  353. /* Decode the response */
  354. retval = UA_decodeBinary(message, &offset, rd->response, rd->responseType,
  355. rd->client->config.customDataTypesSize,
  356. rd->client->config.customDataTypes);
  357. finish:
  358. UA_NodeId_deleteMembers(&responseId);
  359. if(retval != UA_STATUSCODE_GOOD) {
  360. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  361. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  362. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  363. "Error receiving the response with status code %s",
  364. UA_StatusCode_name(retval));
  365. if(rd->response) {
  366. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  367. respHeader->serviceResult = retval;
  368. }
  369. }
  370. return retval;
  371. }
  372. /* Forward complete chunks directly to the securechannel */
  373. static UA_StatusCode
  374. client_processChunk(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  375. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  376. return UA_SecureChannel_processChunk(&rd->client->channel, chunk,
  377. processServiceResponse,
  378. rd);
  379. }
  380. /* Receive and process messages until a synchronous message arrives or the
  381. * timout finishes */
  382. UA_StatusCode
  383. receiveServiceResponse(UA_Client *client, void *response, const UA_DataType *responseType,
  384. UA_DateTime maxDate, UA_UInt32 *synchronousRequestId) {
  385. /* Prepare the response and the structure we give into processServiceResponse */
  386. SyncResponseDescription rd = { client, false, 0, response, responseType };
  387. /* Return upon receiving the synchronized response. All other responses are
  388. * processed with a callback "in the background". */
  389. if(synchronousRequestId)
  390. rd.requestId = *synchronousRequestId;
  391. UA_StatusCode retval;
  392. do {
  393. UA_DateTime now = UA_DateTime_nowMonotonic();
  394. /* >= avoid timeout to be set to 0 */
  395. if(now >= maxDate)
  396. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  397. /* round always to upper value to avoid timeout to be set to 0
  398. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  399. UA_UInt32 timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  400. retval = UA_Connection_receiveChunksBlocking(&client->connection, &rd, client_processChunk, timeout);
  401. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  402. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  403. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  404. UA_Client_close(client);
  405. break;
  406. }
  407. } while(!rd.received);
  408. return retval;
  409. }
  410. void
  411. __UA_Client_Service(UA_Client *client, const void *request,
  412. const UA_DataType *requestType, void *response,
  413. const UA_DataType *responseType) {
  414. UA_init(response, responseType);
  415. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  416. /* Send the request */
  417. UA_UInt32 requestId;
  418. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &requestId);
  419. if(retval != UA_STATUSCODE_GOOD) {
  420. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  421. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  422. else
  423. respHeader->serviceResult = retval;
  424. UA_Client_close(client);
  425. return;
  426. }
  427. /* Retrieve the response */
  428. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  429. (client->config.timeout * UA_DATETIME_MSEC);
  430. retval = receiveServiceResponse(client, response, responseType, maxDate, &requestId);
  431. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  432. /* In synchronous service, if we have don't have a reply we need to close the connection */
  433. UA_Client_close(client);
  434. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  435. }
  436. if(retval != UA_STATUSCODE_GOOD)
  437. respHeader->serviceResult = retval;
  438. }
  439. void
  440. UA_Client_AsyncService_cancel(UA_Client *client, AsyncServiceCall *ac,
  441. UA_StatusCode statusCode) {
  442. /* Create an empty response with the statuscode */
  443. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  444. void *resp = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  445. UA_init(resp, ac->responseType);
  446. ((UA_ResponseHeader*)resp)->serviceResult = statusCode;
  447. ac->callback(client, ac->userdata, ac->requestId, resp, ac->responseType);
  448. /* Clean up the response. Users might move data into it. For whatever reasons. */
  449. UA_deleteMembers(resp, ac->responseType);
  450. }
  451. void UA_Client_AsyncService_removeAll(UA_Client *client, UA_StatusCode statusCode) {
  452. AsyncServiceCall *ac, *ac_tmp;
  453. LIST_FOREACH_SAFE(ac, &client->asyncServiceCalls, pointers, ac_tmp) {
  454. LIST_REMOVE(ac, pointers);
  455. UA_Client_AsyncService_cancel(client, ac, statusCode);
  456. UA_free(ac);
  457. }
  458. }
  459. UA_StatusCode
  460. __UA_Client_AsyncService(UA_Client *client, const void *request,
  461. const UA_DataType *requestType,
  462. UA_ClientAsyncServiceCallback callback,
  463. const UA_DataType *responseType,
  464. void *userdata, UA_UInt32 *requestId) {
  465. /* Prepare the entry for the linked list */
  466. AsyncServiceCall *ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  467. if(!ac)
  468. return UA_STATUSCODE_BADOUTOFMEMORY;
  469. ac->callback = callback;
  470. ac->responseType = responseType;
  471. ac->userdata = userdata;
  472. /* Call the service and set the requestId */
  473. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &ac->requestId);
  474. if(retval != UA_STATUSCODE_GOOD) {
  475. UA_free(ac);
  476. return retval;
  477. }
  478. /* Store the entry for async processing */
  479. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  480. if(requestId)
  481. *requestId = ac->requestId;
  482. return UA_STATUSCODE_GOOD;
  483. }
  484. UA_StatusCode
  485. UA_Client_runAsync(UA_Client *client, UA_UInt16 timeout) {
  486. /* TODO: Call repeated jobs that are scheduled */
  487. #ifdef UA_ENABLE_SUBSCRIPTIONS
  488. UA_StatusCode retvalPublish = UA_Client_Subscriptions_backgroundPublish(client);
  489. if (retvalPublish != UA_STATUSCODE_GOOD)
  490. return retvalPublish;
  491. #endif
  492. UA_StatusCode retval = UA_Client_manuallyRenewSecureChannel(client);
  493. if (retval != UA_STATUSCODE_GOOD)
  494. return retval;
  495. UA_DateTime maxDate = UA_DateTime_nowMonotonic() + (timeout * UA_DATETIME_MSEC);
  496. retval = receiveServiceResponse(client, NULL, NULL, maxDate, NULL);
  497. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT)
  498. retval = UA_STATUSCODE_GOOD;
  499. #ifdef UA_ENABLE_SUBSCRIPTIONS
  500. /* The inactivity check must be done after receiveServiceResponse */
  501. UA_Client_Subscriptions_backgroundPublishInactivityCheck(client);
  502. #endif
  503. return retval;
  504. }