ua_client.c 27 KB

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