ua_client.c 14 KB

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