ua_client.c 24 KB

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