ua_client.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. */
  18. #include "ua_client.h"
  19. #include "ua_client_internal.h"
  20. #include "ua_connection_internal.h"
  21. #include "ua_types_encoding_binary.h"
  22. #include "ua_types_generated_encoding_binary.h"
  23. #include "ua_util.h"
  24. #include "ua_securitypolicy_none.h"
  25. /********************/
  26. /* Client Lifecycle */
  27. /********************/
  28. static void
  29. UA_Client_init(UA_Client* client, UA_ClientConfig config) {
  30. memset(client, 0, sizeof(UA_Client));
  31. /* TODO: Select policy according to the endpoint */
  32. UA_SecurityPolicy_None(&client->securityPolicy, NULL, UA_BYTESTRING_NULL, config.logger);
  33. client->channel.securityPolicy = &client->securityPolicy;
  34. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  35. client->config = config;
  36. if(client->config.stateCallback)
  37. client->config.stateCallback(client, client->state);
  38. }
  39. UA_Client *
  40. UA_Client_new(UA_ClientConfig config) {
  41. UA_Client *client = (UA_Client*)UA_malloc(sizeof(UA_Client));
  42. if(!client)
  43. return NULL;
  44. UA_Client_init(client, config);
  45. return client;
  46. }
  47. static void
  48. UA_Client_deleteMembers(UA_Client* client) {
  49. UA_Client_disconnect(client);
  50. client->securityPolicy.deleteMembers(&client->securityPolicy);
  51. UA_SecureChannel_deleteMembersCleanup(&client->channel);
  52. UA_Connection_deleteMembers(&client->connection);
  53. if(client->endpointUrl.data)
  54. UA_String_deleteMembers(&client->endpointUrl);
  55. UA_UserTokenPolicy_deleteMembers(&client->token);
  56. UA_NodeId_deleteMembers(&client->authenticationToken);
  57. if(client->username.data)
  58. UA_String_deleteMembers(&client->username);
  59. if(client->password.data)
  60. UA_String_deleteMembers(&client->password);
  61. /* Delete the async service calls */
  62. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  63. /* Delete the subscriptions */
  64. #ifdef UA_ENABLE_SUBSCRIPTIONS
  65. UA_Client_Subscriptions_clean(client);
  66. #endif
  67. }
  68. void
  69. UA_Client_reset(UA_Client* client) {
  70. UA_Client_deleteMembers(client);
  71. UA_Client_init(client, client->config);
  72. }
  73. void
  74. UA_Client_delete(UA_Client* client) {
  75. UA_Client_deleteMembers(client);
  76. UA_free(client);
  77. }
  78. UA_ClientState
  79. UA_Client_getState(UA_Client *client) {
  80. return client->state;
  81. }
  82. void *
  83. UA_Client_getContext(UA_Client *client) {
  84. if(!client)
  85. return NULL;
  86. return client->config.clientContext;
  87. }
  88. /****************/
  89. /* Raw Services */
  90. /****************/
  91. /* For synchronous service calls. Execute async responses with a callback. When
  92. * the response with the correct requestId turns up, return it via the
  93. * SyncResponseDescription pointer. */
  94. typedef struct {
  95. UA_Client *client;
  96. UA_Boolean received;
  97. UA_UInt32 requestId;
  98. void *response;
  99. const UA_DataType *responseType;
  100. } SyncResponseDescription;
  101. /* For both synchronous and asynchronous service calls */
  102. static UA_StatusCode
  103. sendSymmetricServiceRequest(UA_Client *client, const void *request,
  104. const UA_DataType *requestType, UA_UInt32 *requestId) {
  105. /* Make sure we have a valid session */
  106. UA_StatusCode retval = UA_Client_manuallyRenewSecureChannel(client);
  107. if(retval != UA_STATUSCODE_GOOD)
  108. return retval;
  109. /* Adjusting the request header. The const attribute is violated, but we
  110. * only touch the following members: */
  111. UA_RequestHeader *rr = (UA_RequestHeader*)(uintptr_t)request;
  112. rr->authenticationToken = client->authenticationToken; /* cleaned up at the end */
  113. rr->timestamp = UA_DateTime_now();
  114. rr->requestHandle = ++client->requestHandle;
  115. /* Send the request */
  116. UA_UInt32 rqId = ++client->requestId;
  117. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  118. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  119. retval = UA_SecureChannel_sendSymmetricMessage(&client->channel, rqId, UA_MESSAGETYPE_MSG,
  120. rr, requestType);
  121. UA_NodeId_init(&rr->authenticationToken); /* Do not return the token to the user */
  122. if(retval != UA_STATUSCODE_GOOD)
  123. return retval;
  124. *requestId = rqId;
  125. return UA_STATUSCODE_GOOD;
  126. }
  127. static const UA_NodeId
  128. serviceFaultId = {0, UA_NODEIDTYPE_NUMERIC, {UA_NS0ID_SERVICEFAULT_ENCODING_DEFAULTBINARY}};
  129. /* Look for the async callback in the linked list, execute and delete it */
  130. static UA_StatusCode
  131. processAsyncResponse(UA_Client *client, UA_UInt32 requestId, const UA_NodeId *responseTypeId,
  132. const UA_ByteString *responseMessage, size_t *offset) {
  133. /* Find the callback */
  134. AsyncServiceCall *ac;
  135. LIST_FOREACH(ac, &client->asyncServiceCalls, pointers) {
  136. if(ac->requestId == requestId)
  137. break;
  138. }
  139. if(!ac)
  140. return UA_STATUSCODE_BADREQUESTHEADERINVALID;
  141. /* Allocate the response */
  142. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  143. void *response = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  144. /* Verify the type of the response */
  145. const UA_DataType *responseType = ac->responseType;
  146. const UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, ac->responseType->binaryEncodingId);
  147. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  148. if(!UA_NodeId_equal(responseTypeId, &expectedNodeId)) {
  149. UA_init(response, ac->responseType);
  150. if(UA_NodeId_equal(responseTypeId, &serviceFaultId)) {
  151. /* Decode as a ServiceFault, i.e. only the response header */
  152. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  153. "Received a ServiceFault response");
  154. responseType = &UA_TYPES[UA_TYPES_SERVICEFAULT];
  155. } else {
  156. /* Close the connection */
  157. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  158. "Reply contains the wrong service response");
  159. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  160. goto process;
  161. }
  162. }
  163. /* Decode the response */
  164. retval = UA_decodeBinary(responseMessage, offset, response,
  165. responseType, 0, NULL);
  166. process:
  167. if(retval != UA_STATUSCODE_GOOD) {
  168. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  169. "Could not decode the response with id %u due to %s",
  170. requestId, UA_StatusCode_name(retval));
  171. ((UA_ResponseHeader*)response)->serviceResult = retval;
  172. }
  173. /* Call the callback */
  174. ac->callback(client, ac->userdata, requestId, response, ac->responseType);
  175. UA_deleteMembers(response, ac->responseType);
  176. /* Remove the callback */
  177. LIST_REMOVE(ac, pointers);
  178. UA_free(ac);
  179. return retval;
  180. }
  181. /* Processes the received service response. Either with an async callback or by
  182. * decoding the message and returning it "upwards" in the
  183. * SyncResponseDescription. */
  184. static UA_StatusCode
  185. processServiceResponse(void *application, UA_SecureChannel *channel,
  186. UA_MessageType messageType, UA_UInt32 requestId,
  187. const UA_ByteString *message) {
  188. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  189. /* Must be OPN or MSG */
  190. if(messageType != UA_MESSAGETYPE_OPN &&
  191. messageType != UA_MESSAGETYPE_MSG) {
  192. UA_LOG_TRACE_CHANNEL(rd->client->config.logger, channel,
  193. "Invalid message type");
  194. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  195. }
  196. /* Has the SecureChannel timed out?
  197. * TODO: Solve this for client and server together */
  198. if(rd->client->state >= UA_CLIENTSTATE_SECURECHANNEL &&
  199. (channel->securityToken.createdAt +
  200. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  201. < UA_DateTime_nowMonotonic())
  202. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  203. /* Decode the data type identifier of the response */
  204. size_t offset = 0;
  205. UA_NodeId responseId;
  206. UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset, &responseId);
  207. if(retval != UA_STATUSCODE_GOOD)
  208. goto finish;
  209. /* Got an asynchronous response. Don't expected a synchronous response
  210. * (responseType NULL) or the id does not match. */
  211. if(!rd->responseType || requestId != rd->requestId) {
  212. retval = processAsyncResponse(rd->client, requestId, &responseId, message, &offset);
  213. goto finish;
  214. }
  215. /* Got the synchronous response */
  216. rd->received = true;
  217. /* Forward declaration for the goto */
  218. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, rd->responseType->binaryEncodingId);
  219. /* Check that the response type matches */
  220. if(!UA_NodeId_equal(&responseId, &expectedNodeId)) {
  221. if(UA_NodeId_equal(&responseId, &serviceFaultId)) {
  222. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  223. "Received a ServiceFault response");
  224. UA_init(rd->response, rd->responseType);
  225. retval = UA_decodeBinary(message, &offset, rd->response,
  226. &UA_TYPES[UA_TYPES_SERVICEFAULT], 0, NULL);
  227. } else {
  228. /* Close the connection */
  229. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  230. "Reply contains the wrong service response");
  231. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  232. }
  233. goto finish;
  234. }
  235. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  236. "Decode a message of type %u", responseId.identifier.numeric);
  237. /* Decode the response */
  238. retval = UA_decodeBinary(message, &offset, rd->response, rd->responseType,
  239. rd->client->config.customDataTypesSize,
  240. rd->client->config.customDataTypes);
  241. finish:
  242. UA_NodeId_deleteMembers(&responseId);
  243. if(retval != UA_STATUSCODE_GOOD) {
  244. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  245. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  246. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  247. "Error receiving the response with status code %s",
  248. UA_StatusCode_name(retval));
  249. if(rd->response) {
  250. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  251. respHeader->serviceResult = retval;
  252. }
  253. }
  254. return retval;
  255. }
  256. /* Forward complete chunks directly to the securechannel */
  257. static UA_StatusCode
  258. client_processChunk(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  259. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  260. return UA_SecureChannel_processChunk(&rd->client->channel, chunk,
  261. processServiceResponse,
  262. rd);
  263. }
  264. /* Receive and process messages until a synchronous message arrives or the
  265. * timout finishes */
  266. UA_StatusCode
  267. receiveServiceResponse(UA_Client *client, void *response, const UA_DataType *responseType,
  268. UA_DateTime maxDate, UA_UInt32 *synchronousRequestId) {
  269. /* Prepare the response and the structure we give into processServiceResponse */
  270. SyncResponseDescription rd = { client, false, 0, response, responseType };
  271. /* Return upon receiving the synchronized response. All other responses are
  272. * processed with a callback "in the background". */
  273. if(synchronousRequestId)
  274. rd.requestId = *synchronousRequestId;
  275. UA_StatusCode retval;
  276. do {
  277. UA_DateTime now = UA_DateTime_nowMonotonic();
  278. /* >= avoid timeout to be set to 0 */
  279. if(now >= maxDate)
  280. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  281. /* round always to upper value to avoid timeout to be set to 0
  282. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  283. UA_UInt32 timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  284. retval = UA_Connection_receiveChunksBlocking(&client->connection, &rd, client_processChunk, timeout);
  285. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  286. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  287. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  288. UA_Client_close(client);
  289. break;
  290. }
  291. } while(!rd.received);
  292. return retval;
  293. }
  294. void
  295. __UA_Client_Service(UA_Client *client, const void *request,
  296. const UA_DataType *requestType, void *response,
  297. const UA_DataType *responseType) {
  298. UA_init(response, responseType);
  299. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  300. /* Send the request */
  301. UA_UInt32 requestId;
  302. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &requestId);
  303. if(retval != UA_STATUSCODE_GOOD) {
  304. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  305. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  306. else
  307. respHeader->serviceResult = retval;
  308. UA_Client_close(client);
  309. return;
  310. }
  311. /* Retrieve the response */
  312. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  313. (client->config.timeout * UA_DATETIME_MSEC);
  314. retval = receiveServiceResponse(client, response, responseType, maxDate, &requestId);
  315. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  316. /* In synchronous service, if we have don't have a reply we need to close the connection */
  317. UA_Client_close(client);
  318. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  319. }
  320. if(retval != UA_STATUSCODE_GOOD)
  321. respHeader->serviceResult = retval;
  322. }
  323. void
  324. UA_Client_AsyncService_cancel(UA_Client *client, AsyncServiceCall *ac,
  325. UA_StatusCode statusCode) {
  326. /* Create an empty response with the statuscode */
  327. UA_STACKARRAY(UA_Byte, responseBuf, ac->responseType->memSize);
  328. void *resp = (void*)(uintptr_t)&responseBuf[0]; /* workaround aliasing rules */
  329. UA_init(resp, ac->responseType);
  330. ((UA_ResponseHeader*)resp)->serviceResult = statusCode;
  331. ac->callback(client, ac->userdata, ac->requestId, resp, ac->responseType);
  332. /* Clean up the response. Users might move data into it. For whatever reasons. */
  333. UA_deleteMembers(resp, ac->responseType);
  334. }
  335. void UA_Client_AsyncService_removeAll(UA_Client *client, UA_StatusCode statusCode) {
  336. AsyncServiceCall *ac, *ac_tmp;
  337. LIST_FOREACH_SAFE(ac, &client->asyncServiceCalls, pointers, ac_tmp) {
  338. LIST_REMOVE(ac, pointers);
  339. UA_Client_AsyncService_cancel(client, ac, statusCode);
  340. UA_free(ac);
  341. }
  342. }
  343. UA_StatusCode
  344. __UA_Client_AsyncService(UA_Client *client, const void *request,
  345. const UA_DataType *requestType,
  346. UA_ClientAsyncServiceCallback callback,
  347. const UA_DataType *responseType,
  348. void *userdata, UA_UInt32 *requestId) {
  349. /* Prepare the entry for the linked list */
  350. AsyncServiceCall *ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  351. if(!ac)
  352. return UA_STATUSCODE_BADOUTOFMEMORY;
  353. ac->callback = callback;
  354. ac->responseType = responseType;
  355. ac->userdata = userdata;
  356. /* Call the service and set the requestId */
  357. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &ac->requestId);
  358. if(retval != UA_STATUSCODE_GOOD) {
  359. UA_free(ac);
  360. return retval;
  361. }
  362. /* Store the entry for async processing */
  363. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  364. if(requestId)
  365. *requestId = ac->requestId;
  366. return UA_STATUSCODE_GOOD;
  367. }
  368. UA_StatusCode
  369. UA_Client_runAsync(UA_Client *client, UA_UInt16 timeout) {
  370. /* TODO: Call repeated jobs that are scheduled */
  371. #ifdef UA_ENABLE_SUBSCRIPTIONS
  372. UA_StatusCode retvalPublish = UA_Client_Subscriptions_backgroundPublish(client);
  373. if (retvalPublish != UA_STATUSCODE_GOOD)
  374. return retvalPublish;
  375. #endif
  376. UA_StatusCode retval = UA_Client_manuallyRenewSecureChannel(client);
  377. if (retval != UA_STATUSCODE_GOOD)
  378. return retval;
  379. UA_DateTime maxDate = UA_DateTime_nowMonotonic() + (timeout * UA_DATETIME_MSEC);
  380. retval = receiveServiceResponse(client, NULL, NULL, maxDate, NULL);
  381. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT)
  382. retval = UA_STATUSCODE_GOOD;
  383. #ifdef UA_ENABLE_SUBSCRIPTIONS
  384. /* The inactivity check must be done after receiveServiceResponse */
  385. UA_Client_Subscriptions_backgroundPublishInactivityCheck(client);
  386. #endif
  387. return retval;
  388. }