ua_client.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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) Julius Pfrommer, Fraunhofer IOSB
  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 (c) Thomas Stalder
  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, 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. AsyncServiceCall *ac, *ac_tmp;
  63. LIST_FOREACH_SAFE(ac, &client->asyncServiceCalls, pointers, ac_tmp) {
  64. LIST_REMOVE(ac, pointers);
  65. UA_free(ac);
  66. }
  67. /* Delete the subscriptions */
  68. #ifdef UA_ENABLE_SUBSCRIPTIONS
  69. UA_Client_Subscriptions_clean(client);
  70. #endif
  71. }
  72. void
  73. UA_Client_reset(UA_Client* client) {
  74. UA_Client_deleteMembers(client);
  75. UA_Client_init(client, client->config);
  76. }
  77. void
  78. UA_Client_delete(UA_Client* client) {
  79. UA_Client_deleteMembers(client);
  80. UA_free(client);
  81. }
  82. UA_ClientState
  83. UA_Client_getState(UA_Client *client) {
  84. return client->state;
  85. }
  86. void *
  87. UA_Client_getContext(UA_Client *client) {
  88. if(!client)
  89. return NULL;
  90. return client->config.clientContext;
  91. }
  92. /****************/
  93. /* Raw Services */
  94. /****************/
  95. /* For synchronous service calls. Execute async responses with a callback. When
  96. * the response with the correct requestId turns up, return it via the
  97. * SyncResponseDescription pointer. */
  98. typedef struct {
  99. UA_Client *client;
  100. UA_Boolean received;
  101. UA_UInt32 requestId;
  102. void *response;
  103. const UA_DataType *responseType;
  104. } SyncResponseDescription;
  105. /* For both synchronous and asynchronous service calls */
  106. static UA_StatusCode
  107. sendSymmetricServiceRequest(UA_Client *client, const void *request,
  108. const UA_DataType *requestType, UA_UInt32 *requestId) {
  109. /* Make sure we have a valid session */
  110. UA_StatusCode retval = UA_Client_manuallyRenewSecureChannel(client);
  111. if(retval != UA_STATUSCODE_GOOD)
  112. return retval;
  113. /* Adjusting the request header. The const attribute is violated, but we
  114. * only touch the following members: */
  115. UA_RequestHeader *rr = (UA_RequestHeader*)(uintptr_t)request;
  116. rr->authenticationToken = client->authenticationToken; /* cleaned up at the end */
  117. rr->timestamp = UA_DateTime_now();
  118. rr->requestHandle = ++client->requestHandle;
  119. /* Send the request */
  120. UA_UInt32 rqId = ++client->requestId;
  121. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  122. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  123. retval = UA_SecureChannel_sendSymmetricMessage(&client->channel, rqId, UA_MESSAGETYPE_MSG,
  124. rr, requestType);
  125. UA_NodeId_init(&rr->authenticationToken); /* Do not return the token to the user */
  126. if(retval != UA_STATUSCODE_GOOD)
  127. return retval;
  128. *requestId = rqId;
  129. return UA_STATUSCODE_GOOD;
  130. }
  131. /* Look for the async callback in the linked list, execute and delete it */
  132. static UA_StatusCode
  133. processAsyncResponse(UA_Client *client, UA_UInt32 requestId, UA_NodeId *responseTypeId,
  134. const UA_ByteString *responseMessage, size_t *offset) {
  135. /* Find the callback */
  136. AsyncServiceCall *ac;
  137. LIST_FOREACH(ac, &client->asyncServiceCalls, pointers) {
  138. if(ac->requestId == requestId)
  139. break;
  140. }
  141. if(!ac)
  142. return UA_STATUSCODE_BADREQUESTHEADERINVALID;
  143. /* Decode the response */
  144. void *response = UA_alloca(ac->responseType->memSize);
  145. UA_StatusCode retval = UA_decodeBinary(responseMessage, offset, response,
  146. ac->responseType, 0, NULL);
  147. /* Call the callback */
  148. if(retval == UA_STATUSCODE_GOOD) {
  149. ac->callback(client, ac->userdata, requestId, response);
  150. UA_deleteMembers(response, ac->responseType);
  151. } else {
  152. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT,
  153. "Could not decodee the response with Id %u", requestId);
  154. }
  155. /* Remove the callback */
  156. LIST_REMOVE(ac, pointers);
  157. UA_free(ac);
  158. return retval;
  159. }
  160. /* Processes the received service response. Either with an async callback or by
  161. * decoding the message and returning it "upwards" in the
  162. * SyncResponseDescription. */
  163. static UA_StatusCode
  164. processServiceResponse(void *application, UA_SecureChannel *channel,
  165. UA_MessageType messageType, UA_UInt32 requestId,
  166. const UA_ByteString *message) {
  167. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  168. /* Must be OPN or MSG */
  169. if(messageType != UA_MESSAGETYPE_OPN &&
  170. messageType != UA_MESSAGETYPE_MSG) {
  171. UA_LOG_TRACE_CHANNEL(rd->client->config.logger, channel,
  172. "Invalid message type");
  173. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  174. }
  175. /* Has the SecureChannel timed out?
  176. * TODO: Solve this for client and server together */
  177. if(rd->client->state >= UA_CLIENTSTATE_SECURECHANNEL &&
  178. (channel->securityToken.createdAt +
  179. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  180. < UA_DateTime_nowMonotonic())
  181. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  182. /* Forward declaration for the goto */
  183. UA_NodeId expectedNodeId;
  184. const UA_NodeId serviceFaultNodeId =
  185. UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_SERVICEFAULT].binaryEncodingId);
  186. /* Decode the data type identifier of the response */
  187. size_t offset = 0;
  188. UA_NodeId responseId;
  189. UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset, &responseId);
  190. if(retval != UA_STATUSCODE_GOOD)
  191. goto finish;
  192. /* Got an asynchronous response. Don't expected a synchronous response
  193. * (responseType NULL) or the id does not match. */
  194. if(!rd->responseType || requestId != rd->requestId) {
  195. retval = processAsyncResponse(rd->client, requestId, &responseId, message, &offset);
  196. goto finish;
  197. }
  198. /* Got the synchronous response */
  199. rd->received = true;
  200. /* Check that the response type matches */
  201. expectedNodeId = UA_NODEID_NUMERIC(0, rd->responseType->binaryEncodingId);
  202. if(UA_NodeId_equal(&responseId, &expectedNodeId)) {
  203. /* Decode the response */
  204. retval = UA_decodeBinary(message, &offset, rd->response, rd->responseType,
  205. rd->client->config.customDataTypesSize,
  206. rd->client->config.customDataTypes);
  207. } else {
  208. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  209. "Reply contains the wrong service response");
  210. if(UA_NodeId_equal(&responseId, &serviceFaultNodeId)) {
  211. /* Decode only the message header with the servicefault */
  212. retval = UA_decodeBinary(message, &offset, rd->response,
  213. &UA_TYPES[UA_TYPES_SERVICEFAULT], 0, NULL);
  214. } else {
  215. /* Close the connection */
  216. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  217. }
  218. }
  219. finish:
  220. if(retval == UA_STATUSCODE_GOOD) {
  221. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  222. "Received a response of type %i", responseId.identifier.numeric);
  223. } else {
  224. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  225. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  226. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  227. "Error receiving the response with status code %s",
  228. UA_StatusCode_name(retval));
  229. if(rd->response) {
  230. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  231. respHeader->serviceResult = retval;
  232. }
  233. }
  234. UA_NodeId_deleteMembers(&responseId);
  235. return retval;
  236. }
  237. /* Forward complete chunks directly to the securechannel */
  238. static UA_StatusCode
  239. client_processChunk(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  240. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  241. return UA_SecureChannel_processChunk(&rd->client->channel, chunk,
  242. processServiceResponse,
  243. rd);
  244. }
  245. /* Receive and process messages until a synchronous message arrives or the
  246. * timout finishes */
  247. UA_StatusCode
  248. receiveServiceResponse(UA_Client *client, void *response, const UA_DataType *responseType,
  249. UA_DateTime maxDate, UA_UInt32 *synchronousRequestId) {
  250. /* Prepare the response and the structure we give into processServiceResponse */
  251. SyncResponseDescription rd = { client, false, 0, response, responseType };
  252. /* Return upon receiving the synchronized response. All other responses are
  253. * processed with a callback "in the background". */
  254. if(synchronousRequestId)
  255. rd.requestId = *synchronousRequestId;
  256. UA_StatusCode retval;
  257. do {
  258. UA_DateTime now = UA_DateTime_nowMonotonic();
  259. /* >= avoid timeout to be set to 0 */
  260. if(now >= maxDate)
  261. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  262. /* round always to upper value to avoid timeout to be set to 0
  263. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  264. UA_UInt32 timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  265. retval = UA_Connection_receiveChunksBlocking(&client->connection, &rd, client_processChunk, timeout);
  266. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  267. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  268. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  269. UA_Client_close(client);
  270. break;
  271. }
  272. } while(!rd.received);
  273. return retval;
  274. }
  275. void
  276. __UA_Client_Service(UA_Client *client, const void *request,
  277. const UA_DataType *requestType, void *response,
  278. const UA_DataType *responseType) {
  279. UA_init(response, responseType);
  280. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  281. /* Send the request */
  282. UA_UInt32 requestId;
  283. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &requestId);
  284. if(retval != UA_STATUSCODE_GOOD) {
  285. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  286. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  287. else
  288. respHeader->serviceResult = retval;
  289. UA_Client_close(client);
  290. return;
  291. }
  292. /* Retrieve the response */
  293. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  294. (client->config.timeout * UA_DATETIME_MSEC);
  295. retval = receiveServiceResponse(client, response, responseType, maxDate, &requestId);
  296. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  297. /* In synchronous service, if we have don't have a reply we need to close the connection */
  298. UA_Client_close(client);
  299. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  300. }
  301. if(retval != UA_STATUSCODE_GOOD)
  302. respHeader->serviceResult = retval;
  303. }
  304. UA_StatusCode
  305. __UA_Client_AsyncService(UA_Client *client, const void *request,
  306. const UA_DataType *requestType,
  307. UA_ClientAsyncServiceCallback callback,
  308. const UA_DataType *responseType,
  309. void *userdata, UA_UInt32 *requestId) {
  310. /* Prepare the entry for the linked list */
  311. AsyncServiceCall *ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  312. if(!ac)
  313. return UA_STATUSCODE_BADOUTOFMEMORY;
  314. ac->callback = callback;
  315. ac->responseType = responseType;
  316. ac->userdata = userdata;
  317. /* Call the service and set the requestId */
  318. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &ac->requestId);
  319. if(retval != UA_STATUSCODE_GOOD) {
  320. UA_free(ac);
  321. return retval;
  322. }
  323. /* Store the entry for async processing */
  324. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  325. if(requestId)
  326. *requestId = ac->requestId;
  327. return UA_STATUSCODE_GOOD;
  328. }
  329. UA_StatusCode
  330. UA_Client_runAsync(UA_Client *client, UA_UInt16 timeout) {
  331. /* TODO: Call repeated jobs that are scheduled */
  332. UA_DateTime maxDate = UA_DateTime_nowMonotonic() + (timeout * UA_DATETIME_MSEC);
  333. UA_StatusCode retval = receiveServiceResponse(client, NULL, NULL, maxDate, NULL);
  334. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT)
  335. retval = UA_STATUSCODE_GOOD;
  336. return retval;
  337. }