ua_client.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. /* Forward declaration for the goto */
  161. UA_NodeId expectedNodeId;
  162. const UA_NodeId serviceFaultNodeId =
  163. UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_SERVICEFAULT].binaryEncodingId);
  164. /* Decode the data type identifier of the response */
  165. size_t offset = 0;
  166. UA_NodeId responseId;
  167. UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset, &responseId);
  168. if(retval != UA_STATUSCODE_GOOD)
  169. goto finish;
  170. /* Got an asynchronous response. Don't expected a synchronous response
  171. * (responseType NULL) or the id does not match. */
  172. if(!rd->responseType || requestId != rd->requestId) {
  173. retval = processAsyncResponse(rd->client, requestId, &responseId, message, &offset);
  174. goto finish;
  175. }
  176. /* Got the synchronous response */
  177. rd->received = true;
  178. /* Check that the response type matches */
  179. expectedNodeId = UA_NODEID_NUMERIC(0, rd->responseType->binaryEncodingId);
  180. if(UA_NodeId_equal(&responseId, &expectedNodeId)) {
  181. /* Decode the response */
  182. retval = UA_decodeBinary(message, &offset, rd->response, rd->responseType,
  183. rd->client->config.customDataTypesSize,
  184. rd->client->config.customDataTypes);
  185. } else {
  186. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  187. "Reply contains the wrong service response");
  188. if(UA_NodeId_equal(&responseId, &serviceFaultNodeId)) {
  189. /* Decode only the message header with the servicefault */
  190. retval = UA_decodeBinary(message, &offset, rd->response,
  191. &UA_TYPES[UA_TYPES_SERVICEFAULT], 0, NULL);
  192. } else {
  193. /* Close the connection */
  194. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  195. }
  196. }
  197. finish:
  198. if(retval == UA_STATUSCODE_GOOD) {
  199. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  200. "Received a response of type %i", responseId.identifier.numeric);
  201. } else {
  202. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  203. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  204. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  205. "Error receiving the response with status code %s",
  206. UA_StatusCode_name(retval));
  207. if(rd->response) {
  208. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  209. respHeader->serviceResult = retval;
  210. }
  211. }
  212. UA_NodeId_deleteMembers(&responseId);
  213. return retval;
  214. }
  215. /* Forward complete chunks directly to the securechannel */
  216. static UA_StatusCode
  217. client_processChunk(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  218. SyncResponseDescription *rd = (SyncResponseDescription*)application;
  219. return UA_SecureChannel_processChunk(&rd->client->channel, chunk,
  220. processServiceResponse,
  221. rd);
  222. }
  223. /* Receive and process messages until a synchronous message arrives or the
  224. * timout finishes */
  225. UA_StatusCode
  226. receiveServiceResponse(UA_Client *client, void *response, const UA_DataType *responseType,
  227. UA_DateTime maxDate, UA_UInt32 *synchronousRequestId) {
  228. /* Prepare the response and the structure we give into processServiceResponse */
  229. SyncResponseDescription rd = { client, false, 0, response, responseType };
  230. /* Return upon receiving the synchronized response. All other responses are
  231. * processed with a callback "in the background". */
  232. if(synchronousRequestId)
  233. rd.requestId = *synchronousRequestId;
  234. UA_StatusCode retval;
  235. do {
  236. UA_DateTime now = UA_DateTime_nowMonotonic();
  237. if(now > maxDate)
  238. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  239. UA_UInt32 timeout = (UA_UInt32)((maxDate - now) / UA_MSEC_TO_DATETIME);
  240. retval = UA_Connection_receiveChunksBlocking(&client->connection, &rd,
  241. client_processChunk, timeout);
  242. if(retval != UA_STATUSCODE_GOOD && retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT) {
  243. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  244. client->state = UA_CLIENTSTATE_DISCONNECTED;
  245. else
  246. UA_Client_disconnect(client);
  247. break;
  248. }
  249. } while(!rd.received);
  250. return retval;
  251. }
  252. void
  253. __UA_Client_Service(UA_Client *client, const void *request,
  254. const UA_DataType *requestType, void *response,
  255. const UA_DataType *responseType) {
  256. UA_init(response, responseType);
  257. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  258. /* Send the request */
  259. UA_UInt32 requestId;
  260. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &requestId);
  261. if(retval != UA_STATUSCODE_GOOD) {
  262. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  263. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  264. else
  265. respHeader->serviceResult = retval;
  266. UA_Client_disconnect(client);
  267. return;
  268. }
  269. /* Retrieve the response */
  270. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  271. (client->config.timeout * UA_MSEC_TO_DATETIME);
  272. retval = receiveServiceResponse(client, response, responseType, maxDate, &requestId);
  273. if(retval != UA_STATUSCODE_GOOD)
  274. respHeader->serviceResult = retval;
  275. }
  276. UA_StatusCode
  277. __UA_Client_AsyncService(UA_Client *client, const void *request,
  278. const UA_DataType *requestType,
  279. UA_ClientAsyncServiceCallback callback,
  280. const UA_DataType *responseType,
  281. void *userdata, UA_UInt32 *requestId) {
  282. /* Prepare the entry for the linked list */
  283. AsyncServiceCall *ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  284. if(!ac)
  285. return UA_STATUSCODE_BADOUTOFMEMORY;
  286. ac->callback = callback;
  287. ac->responseType = responseType;
  288. ac->userdata = userdata;
  289. /* Call the service and set the requestId */
  290. UA_StatusCode retval = sendSymmetricServiceRequest(client, request, requestType, &ac->requestId);
  291. if(retval != UA_STATUSCODE_GOOD) {
  292. UA_free(ac);
  293. return retval;
  294. }
  295. /* Store the entry for async processing */
  296. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  297. if(requestId)
  298. *requestId = ac->requestId;
  299. return UA_STATUSCODE_GOOD;
  300. }
  301. UA_StatusCode
  302. UA_Client_runAsync(UA_Client *client, UA_UInt16 timeout) {
  303. /* TODO: Call repeated jobs that are scheduled */
  304. UA_DateTime maxDate = UA_DateTime_nowMonotonic() +
  305. (timeout * UA_MSEC_TO_DATETIME);
  306. UA_StatusCode retval = receiveServiceResponse(client, NULL, NULL, maxDate, NULL);
  307. if(retval == UA_STATUSCODE_GOODNONCRITICALTIMEOUT)
  308. retval = UA_STATUSCODE_GOOD;
  309. return retval;
  310. }