ua_client.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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_transport_generated.h"
  10. #include "ua_transport_generated_handling.h"
  11. #include "ua_transport_generated_encoding_binary.h"
  12. #include "ua_util.h"
  13. #include "ua_nodeids.h"
  14. /*********************/
  15. /* Create and Delete */
  16. /*********************/
  17. static void UA_Client_init(UA_Client* client, UA_ClientConfig config) {
  18. memset(client, 0, sizeof(UA_Client));
  19. client->channel.connection = &client->connection;
  20. client->config = config;
  21. }
  22. UA_Client * UA_Client_new(UA_ClientConfig config) {
  23. UA_Client *client = (UA_Client*)UA_calloc(1, sizeof(UA_Client));
  24. if(!client)
  25. return NULL;
  26. UA_Client_init(client, config);
  27. return client;
  28. }
  29. static void UA_Client_deleteMembers(UA_Client* client) {
  30. UA_Client_disconnect(client);
  31. UA_SecureChannel_deleteMembersCleanup(&client->channel);
  32. UA_Connection_deleteMembers(&client->connection);
  33. if(client->endpointUrl.data)
  34. UA_String_deleteMembers(&client->endpointUrl);
  35. UA_UserTokenPolicy_deleteMembers(&client->token);
  36. UA_NodeId_deleteMembers(&client->authenticationToken);
  37. if(client->username.data)
  38. UA_String_deleteMembers(&client->username);
  39. if(client->password.data)
  40. UA_String_deleteMembers(&client->password);
  41. #ifdef UA_ENABLE_SUBSCRIPTIONS
  42. UA_Client_NotificationsAckNumber *n, *tmp;
  43. LIST_FOREACH_SAFE(n, &client->pendingNotificationsAcks, listEntry, tmp) {
  44. LIST_REMOVE(n, listEntry);
  45. UA_free(n);
  46. }
  47. UA_Client_Subscription *sub, *tmps;
  48. LIST_FOREACH_SAFE(sub, &client->subscriptions, listEntry, tmps)
  49. UA_Client_Subscriptions_forceDelete(client, sub); /* force local removal */
  50. #endif
  51. }
  52. void UA_Client_reset(UA_Client* client){
  53. UA_Client_deleteMembers(client);
  54. UA_Client_init(client, client->config);
  55. }
  56. void UA_Client_delete(UA_Client* client){
  57. UA_Client_deleteMembers(client);
  58. UA_free(client);
  59. }
  60. UA_ClientState UA_Client_getState(UA_Client *client) {
  61. if(!client)
  62. return UA_CLIENTSTATE_ERRORED;
  63. return client->state;
  64. }
  65. /*************************/
  66. /* Manage the Connection */
  67. /*************************/
  68. #define UA_MINMESSAGESIZE 8192
  69. static UA_StatusCode
  70. HelAckHandshake(UA_Client *client) {
  71. /* Get a buffer */
  72. UA_ByteString message;
  73. UA_Connection *conn = &client->connection;
  74. UA_StatusCode retval = conn->getSendBuffer(conn, UA_MINMESSAGESIZE, &message);
  75. if(retval != UA_STATUSCODE_GOOD)
  76. return retval;
  77. /* Prepare the HEL message and encode at offset 8 */
  78. UA_TcpHelloMessage hello;
  79. UA_String_copy(&client->endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  80. hello.maxChunkCount = conn->localConf.maxChunkCount;
  81. hello.maxMessageSize = conn->localConf.maxMessageSize;
  82. hello.protocolVersion = conn->localConf.protocolVersion;
  83. hello.receiveBufferSize = conn->localConf.recvBufferSize;
  84. hello.sendBufferSize = conn->localConf.sendBufferSize;
  85. size_t offset = 8;
  86. retval = UA_TcpHelloMessage_encodeBinary(&hello, &message, &offset);
  87. UA_TcpHelloMessage_deleteMembers(&hello);
  88. /* Encode the message header at offset 0 */
  89. UA_TcpMessageHeader messageHeader;
  90. messageHeader.messageTypeAndChunkType = UA_CHUNKTYPE_FINAL + UA_MESSAGETYPE_HEL;
  91. messageHeader.messageSize = (UA_UInt32)offset;
  92. offset = 0;
  93. retval |= UA_TcpMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  94. if(retval != UA_STATUSCODE_GOOD) {
  95. conn->releaseSendBuffer(conn, &message);
  96. return retval;
  97. }
  98. /* Send the HEL message */
  99. message.length = messageHeader.messageSize;
  100. retval = conn->send(conn, &message);
  101. if(retval != UA_STATUSCODE_GOOD) {
  102. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_NETWORK,
  103. "Sending HEL failed");
  104. return retval;
  105. }
  106. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_NETWORK,
  107. "Sent HEL message");
  108. /* Loop until we have a complete chunk */
  109. UA_ByteString reply = UA_BYTESTRING_NULL;
  110. UA_Boolean realloced = false;
  111. retval = UA_Connection_receiveChunksBlocking(conn, &reply, &realloced,
  112. client->config.timeout);
  113. if(retval != UA_STATUSCODE_GOOD) {
  114. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_NETWORK,
  115. "Receiving ACK message failed");
  116. return retval;
  117. }
  118. /* Decode the message */
  119. offset = 0;
  120. UA_TcpAcknowledgeMessage ackMessage;
  121. retval = UA_TcpMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  122. retval |= UA_TcpAcknowledgeMessage_decodeBinary(&reply, &offset, &ackMessage);
  123. /* Free the message buffer */
  124. if(!realloced)
  125. conn->releaseRecvBuffer(conn, &reply);
  126. else
  127. UA_ByteString_deleteMembers(&reply);
  128. /* Store remote connection settings and adjust local configuration to not
  129. exceed the limits */
  130. if(retval == UA_STATUSCODE_GOOD) {
  131. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  132. conn->remoteConf.maxChunkCount = ackMessage.maxChunkCount; /* may be zero -> unlimited */
  133. conn->remoteConf.maxMessageSize = ackMessage.maxMessageSize; /* may be zero -> unlimited */
  134. conn->remoteConf.protocolVersion = ackMessage.protocolVersion;
  135. conn->remoteConf.sendBufferSize = ackMessage.sendBufferSize;
  136. conn->remoteConf.recvBufferSize = ackMessage.receiveBufferSize;
  137. if(conn->remoteConf.recvBufferSize < conn->localConf.sendBufferSize)
  138. conn->localConf.sendBufferSize = conn->remoteConf.recvBufferSize;
  139. if(conn->remoteConf.sendBufferSize < conn->localConf.recvBufferSize)
  140. conn->localConf.recvBufferSize = conn->remoteConf.sendBufferSize;
  141. conn->state = UA_CONNECTION_ESTABLISHED;
  142. } else {
  143. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_NETWORK, "Decoding ACK message failed");
  144. }
  145. UA_TcpAcknowledgeMessage_deleteMembers(&ackMessage);
  146. return retval;
  147. }
  148. static UA_StatusCode
  149. SecureChannelHandshake(UA_Client *client, UA_Boolean renew) {
  150. /* Check if sc is still valid */
  151. if(renew && client->nextChannelRenewal - UA_DateTime_nowMonotonic() > 0)
  152. return UA_STATUSCODE_GOOD;
  153. UA_Connection *conn = &client->connection;
  154. if(conn->state != UA_CONNECTION_ESTABLISHED)
  155. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  156. UA_ByteString message;
  157. UA_StatusCode retval = conn->getSendBuffer(conn, conn->remoteConf.recvBufferSize, &message);
  158. if(retval != UA_STATUSCODE_GOOD)
  159. return retval;
  160. /* Jump over the messageHeader that will be encoded last */
  161. size_t offset = 12;
  162. /* Encode the Asymmetric Security Header */
  163. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  164. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  165. asymHeader.securityPolicyUri = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  166. retval = UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &message, &offset);
  167. /* Encode the sequence header */
  168. UA_SequenceHeader seqHeader;
  169. seqHeader.sequenceNumber = ++client->channel.sendSequenceNumber;
  170. seqHeader.requestId = ++client->requestId;
  171. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  172. /* Encode the NodeId of the OpenSecureChannel Service */
  173. UA_NodeId requestType =
  174. UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST].binaryEncodingId);
  175. retval |= UA_NodeId_encodeBinary(&requestType, &message, &offset);
  176. /* Encode the OpenSecureChannelRequest */
  177. UA_OpenSecureChannelRequest opnSecRq;
  178. UA_OpenSecureChannelRequest_init(&opnSecRq);
  179. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  180. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  181. if(renew) {
  182. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  183. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  184. "Requesting to renew the SecureChannel");
  185. } else {
  186. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  187. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  188. "Requesting to open a SecureChannel");
  189. }
  190. opnSecRq.securityMode = UA_MESSAGESECURITYMODE_NONE;
  191. opnSecRq.clientNonce = client->channel.clientNonce;
  192. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  193. retval |= UA_OpenSecureChannelRequest_encodeBinary(&opnSecRq, &message, &offset);
  194. /* Encode the message header at the beginning */
  195. UA_SecureConversationMessageHeader messageHeader;
  196. messageHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  197. messageHeader.messageHeader.messageSize = (UA_UInt32)offset;
  198. if(renew)
  199. messageHeader.secureChannelId = client->channel.securityToken.channelId;
  200. else
  201. messageHeader.secureChannelId = 0;
  202. offset = 0;
  203. retval |= UA_SecureConversationMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  204. /* Clean up and return if encoding the message failed */
  205. if(retval != UA_STATUSCODE_GOOD) {
  206. client->connection.releaseSendBuffer(&client->connection, &message);
  207. return retval;
  208. }
  209. /* Send the message */
  210. message.length = messageHeader.messageHeader.messageSize;
  211. retval = conn->send(conn, &message);
  212. if(retval != UA_STATUSCODE_GOOD)
  213. return retval;
  214. /* Receive the response */
  215. UA_ByteString reply = UA_BYTESTRING_NULL;
  216. UA_Boolean realloced = false;
  217. retval = UA_Connection_receiveChunksBlocking(conn, &reply, &realloced,
  218. client->config.timeout);
  219. if(retval != UA_STATUSCODE_GOOD) {
  220. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  221. "Receiving OpenSecureChannelResponse failed");
  222. return retval;
  223. }
  224. /* Decode the header */
  225. offset = 0;
  226. retval = UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  227. retval |= UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &asymHeader);
  228. retval |= UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  229. retval |= UA_NodeId_decodeBinary(&reply, &offset, &requestType);
  230. UA_NodeId expectedRequest =
  231. UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE].binaryEncodingId);
  232. if(retval != UA_STATUSCODE_GOOD || !UA_NodeId_equal(&requestType, &expectedRequest)) {
  233. UA_ByteString_deleteMembers(&reply);
  234. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  235. UA_NodeId_deleteMembers(&requestType);
  236. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  237. "Reply answers the wrong request. Expected OpenSecureChannelResponse.");
  238. return UA_STATUSCODE_BADINTERNALERROR;
  239. }
  240. /* Save the sequence number from server */
  241. client->channel.receiveSequenceNumber = seqHeader.sequenceNumber;
  242. /* Decode the response */
  243. UA_OpenSecureChannelResponse response;
  244. retval = UA_OpenSecureChannelResponse_decodeBinary(&reply, &offset, &response);
  245. /* Free the message */
  246. if(!realloced)
  247. conn->releaseRecvBuffer(conn, &reply);
  248. else
  249. UA_ByteString_deleteMembers(&reply);
  250. /* Results in either the StatusCode of decoding or the service */
  251. retval |= response.responseHeader.serviceResult;
  252. if(retval == UA_STATUSCODE_GOOD) {
  253. /* Response.securityToken.revisedLifetime is UInt32 we need to cast it
  254. * to DateTime=Int64 we take 75% of lifetime to start renewing as
  255. * described in standard */
  256. client->nextChannelRenewal = UA_DateTime_nowMonotonic() +
  257. (UA_DateTime)(response.securityToken.revisedLifetime * (UA_Double)UA_MSEC_TO_DATETIME * 0.75);
  258. /* Replace the old nonce */
  259. UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
  260. UA_ChannelSecurityToken_copy(&response.securityToken, &client->channel.securityToken);
  261. UA_ByteString_deleteMembers(&client->channel.serverNonce);
  262. UA_ByteString_copy(&response.serverNonce, &client->channel.serverNonce);
  263. if(renew)
  264. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  265. "SecureChannel renewed");
  266. else
  267. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  268. "SecureChannel opened");
  269. } else {
  270. if(renew)
  271. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  272. "SecureChannel could not be renewed "
  273. "with error code %s", UA_StatusCode_name(retval));
  274. else
  275. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  276. "SecureChannel could not be opened "
  277. "with error code %s", UA_StatusCode_name(retval));
  278. }
  279. /* Clean up */
  280. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  281. UA_OpenSecureChannelResponse_deleteMembers(&response);
  282. return retval;
  283. }
  284. static UA_StatusCode
  285. ActivateSession(UA_Client *client) {
  286. UA_ActivateSessionRequest request;
  287. UA_ActivateSessionRequest_init(&request);
  288. request.requestHeader.requestHandle = ++client->requestHandle;
  289. request.requestHeader.timestamp = UA_DateTime_now();
  290. request.requestHeader.timeoutHint = 600000;
  291. //manual ExtensionObject encoding of the identityToken
  292. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE) {
  293. UA_AnonymousIdentityToken* identityToken = UA_AnonymousIdentityToken_new();
  294. UA_AnonymousIdentityToken_init(identityToken);
  295. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  296. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  297. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  298. request.userIdentityToken.content.decoded.data = identityToken;
  299. } else {
  300. UA_UserNameIdentityToken* identityToken = UA_UserNameIdentityToken_new();
  301. UA_UserNameIdentityToken_init(identityToken);
  302. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  303. UA_String_copy(&client->username, &identityToken->userName);
  304. UA_String_copy(&client->password, &identityToken->password);
  305. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  306. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  307. request.userIdentityToken.content.decoded.data = identityToken;
  308. }
  309. UA_ActivateSessionResponse response;
  310. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  311. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  312. if(response.responseHeader.serviceResult) {
  313. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  314. "ActivateSession failed with error code %s",
  315. UA_StatusCode_name(response.responseHeader.serviceResult));
  316. }
  317. UA_StatusCode retval = response.responseHeader.serviceResult;
  318. UA_ActivateSessionRequest_deleteMembers(&request);
  319. UA_ActivateSessionResponse_deleteMembers(&response);
  320. return retval;
  321. }
  322. /* Gets a list of endpoints. Memory is allocated for endpointDescription array */
  323. static UA_StatusCode
  324. GetEndpoints(UA_Client *client, size_t* endpointDescriptionsSize,
  325. UA_EndpointDescription** endpointDescriptions) {
  326. UA_GetEndpointsRequest request;
  327. UA_GetEndpointsRequest_init(&request);
  328. request.requestHeader.timestamp = UA_DateTime_now();
  329. request.requestHeader.timeoutHint = 10000;
  330. // assume the endpointurl outlives the service call
  331. request.endpointUrl = client->endpointUrl;
  332. UA_GetEndpointsResponse response;
  333. UA_GetEndpointsResponse_init(&response);
  334. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  335. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  336. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  337. UA_StatusCode retval = response.responseHeader.serviceResult;
  338. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  339. "GetEndpointRequest failed with error code %s",
  340. UA_StatusCode_name(retval));
  341. UA_GetEndpointsResponse_deleteMembers(&response);
  342. return retval;
  343. }
  344. *endpointDescriptions = response.endpoints;
  345. *endpointDescriptionsSize = response.endpointsSize;
  346. response.endpoints = NULL;
  347. response.endpointsSize = 0;
  348. UA_GetEndpointsResponse_deleteMembers(&response);
  349. return UA_STATUSCODE_GOOD;
  350. }
  351. static UA_StatusCode
  352. EndpointsHandshake(UA_Client *client) {
  353. UA_EndpointDescription* endpointArray = NULL;
  354. size_t endpointArraySize = 0;
  355. UA_StatusCode retval = GetEndpoints(client, &endpointArraySize, &endpointArray);
  356. if(retval != UA_STATUSCODE_GOOD)
  357. return retval;
  358. UA_Boolean endpointFound = false;
  359. UA_Boolean tokenFound = false;
  360. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  361. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  362. "Transport/uatcp-uasc-uabinary");
  363. //TODO: compare endpoint information with client->endpointUri
  364. for(size_t i = 0; i < endpointArraySize; ++i) {
  365. UA_EndpointDescription* endpoint = &endpointArray[i];
  366. /* look out for binary transport endpoints */
  367. /* Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  368. if(endpoint->transportProfileUri.length != 0 &&
  369. !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  370. continue;
  371. /* look out for an endpoint without security */
  372. if(!UA_String_equal(&endpoint->securityPolicyUri, &securityNone))
  373. continue;
  374. /* endpoint with no security found */
  375. endpointFound = true;
  376. /* look for a user token policy with an anonymous token */
  377. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  378. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  379. /* Usertokens also have a security policy... */
  380. if(userToken->securityPolicyUri.length > 0 &&
  381. !UA_String_equal(&userToken->securityPolicyUri, &securityNone))
  382. continue;
  383. /* UA_CLIENTAUTHENTICATION_NONE == UA_USERTOKENTYPE_ANONYMOUS
  384. * UA_CLIENTAUTHENTICATION_USERNAME == UA_USERTOKENTYPE_USERNAME
  385. * TODO: Check equivalence for other types when adding the support */
  386. if((int)client->authenticationMethod != (int)userToken->tokenType)
  387. continue;
  388. /* Endpoint with matching usertokenpolicy found */
  389. tokenFound = true;
  390. UA_UserTokenPolicy_copy(userToken, &client->token);
  391. break;
  392. }
  393. }
  394. UA_Array_delete(endpointArray, endpointArraySize,
  395. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  396. if(!endpointFound) {
  397. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  398. "No suitable endpoint found");
  399. retval = UA_STATUSCODE_BADINTERNALERROR;
  400. } else if(!tokenFound) {
  401. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  402. "No suitable UserTokenPolicy found for the possible endpoints");
  403. retval = UA_STATUSCODE_BADINTERNALERROR;
  404. }
  405. return retval;
  406. }
  407. static UA_StatusCode
  408. SessionHandshake(UA_Client *client) {
  409. UA_CreateSessionRequest request;
  410. UA_CreateSessionRequest_init(&request);
  411. request.requestHeader.timestamp = UA_DateTime_now();
  412. request.requestHeader.timeoutHint = 10000;
  413. UA_ByteString_copy(&client->channel.clientNonce, &request.clientNonce);
  414. request.requestedSessionTimeout = 1200000;
  415. request.maxResponseMessageSize = UA_INT32_MAX;
  416. UA_String_copy(&client->endpointUrl, &request.endpointUrl);
  417. UA_CreateSessionResponse response;
  418. UA_CreateSessionResponse_init(&response);
  419. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  420. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  421. UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  422. UA_StatusCode retval = response.responseHeader.serviceResult;
  423. UA_CreateSessionRequest_deleteMembers(&request);
  424. UA_CreateSessionResponse_deleteMembers(&response);
  425. return retval;
  426. }
  427. static UA_StatusCode
  428. CloseSession(UA_Client *client) {
  429. UA_CloseSessionRequest request;
  430. UA_CloseSessionRequest_init(&request);
  431. request.requestHeader.timestamp = UA_DateTime_now();
  432. request.requestHeader.timeoutHint = 10000;
  433. request.deleteSubscriptions = true;
  434. UA_CloseSessionResponse response;
  435. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  436. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  437. UA_StatusCode retval = response.responseHeader.serviceResult;
  438. UA_CloseSessionRequest_deleteMembers(&request);
  439. UA_CloseSessionResponse_deleteMembers(&response);
  440. return retval;
  441. }
  442. static UA_StatusCode
  443. CloseSecureChannel(UA_Client *client) {
  444. UA_SecureChannel *channel = &client->channel;
  445. UA_CloseSecureChannelRequest request;
  446. UA_CloseSecureChannelRequest_init(&request);
  447. request.requestHeader.requestHandle = ++client->requestHandle;
  448. request.requestHeader.timestamp = UA_DateTime_now();
  449. request.requestHeader.timeoutHint = 10000;
  450. UA_NodeId_copy(&client->authenticationToken,
  451. &request.requestHeader.authenticationToken);
  452. UA_SecureConversationMessageHeader msgHeader;
  453. msgHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_CLO + UA_CHUNKTYPE_FINAL;
  454. msgHeader.secureChannelId = channel->securityToken.channelId;
  455. UA_SymmetricAlgorithmSecurityHeader symHeader;
  456. symHeader.tokenId = channel->securityToken.tokenId;
  457. UA_SequenceHeader seqHeader;
  458. seqHeader.sequenceNumber = ++channel->sendSequenceNumber;
  459. seqHeader.requestId = ++client->requestId;
  460. UA_NodeId typeId =
  461. UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST].binaryEncodingId);
  462. UA_ByteString message;
  463. UA_Connection *conn = &client->connection;
  464. UA_StatusCode retval = conn->getSendBuffer(conn, conn->remoteConf.recvBufferSize, &message);
  465. if(retval != UA_STATUSCODE_GOOD){
  466. UA_CloseSecureChannelRequest_deleteMembers(&request);
  467. return retval;
  468. }
  469. size_t offset = 12;
  470. retval |= UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symHeader, &message, &offset);
  471. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  472. retval |= UA_NodeId_encodeBinary(&typeId, &message, &offset);
  473. retval |= UA_encodeBinary(&request, &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST],
  474. NULL, NULL, &message, &offset);
  475. msgHeader.messageHeader.messageSize = (UA_UInt32)offset;
  476. offset = 0;
  477. retval |= UA_SecureConversationMessageHeader_encodeBinary(&msgHeader, &message, &offset);
  478. if(retval == UA_STATUSCODE_GOOD) {
  479. message.length = msgHeader.messageHeader.messageSize;
  480. retval = conn->send(conn, &message);
  481. } else {
  482. conn->releaseSendBuffer(conn, &message);
  483. }
  484. conn->close(conn);
  485. UA_CloseSecureChannelRequest_deleteMembers(&request);
  486. return retval;
  487. }
  488. UA_StatusCode
  489. UA_Client_getEndpoints(UA_Client *client, const char *serverUrl,
  490. size_t* endpointDescriptionsSize,
  491. UA_EndpointDescription** endpointDescriptions) {
  492. if(client->state == UA_CLIENTSTATE_CONNECTED)
  493. return UA_STATUSCODE_GOOD;
  494. if(client->state == UA_CLIENTSTATE_ERRORED)
  495. UA_Client_reset(client);
  496. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  497. client->connection =
  498. client->config.connectionFunc(UA_ConnectionConfig_standard, serverUrl,
  499. client->config.logger);
  500. if(client->connection.state != UA_CONNECTION_OPENING) {
  501. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  502. goto cleanup;
  503. }
  504. client->endpointUrl = UA_STRING_ALLOC(serverUrl);
  505. if(!client->endpointUrl.data) {
  506. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  507. goto cleanup;
  508. }
  509. client->connection.localConf = client->config.localConnectionConfig;
  510. retval = HelAckHandshake(client);
  511. if(retval == UA_STATUSCODE_GOOD)
  512. retval = SecureChannelHandshake(client, false);
  513. if(retval == UA_STATUSCODE_GOOD)
  514. retval = GetEndpoints(client, endpointDescriptionsSize, endpointDescriptions);
  515. /* always cleanup */
  516. cleanup:
  517. UA_Client_disconnect(client);
  518. UA_Client_reset(client);
  519. return retval;
  520. }
  521. UA_StatusCode
  522. UA_Client_connect_username(UA_Client *client, const char *endpointUrl,
  523. const char *username, const char *password){
  524. client->authenticationMethod=UA_CLIENTAUTHENTICATION_USERNAME;
  525. client->username = UA_STRING_ALLOC(username);
  526. client->password = UA_STRING_ALLOC(password);
  527. return UA_Client_connect(client, endpointUrl);
  528. }
  529. UA_StatusCode
  530. UA_Client_connect(UA_Client *client, const char *endpointUrl) {
  531. if(client->state == UA_CLIENTSTATE_CONNECTED)
  532. return UA_STATUSCODE_GOOD;
  533. if(client->state == UA_CLIENTSTATE_ERRORED) {
  534. UA_Client_reset(client);
  535. }
  536. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  537. client->connection =
  538. client->config.connectionFunc(UA_ConnectionConfig_standard,
  539. endpointUrl, client->config.logger);
  540. if(client->connection.state != UA_CONNECTION_OPENING) {
  541. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  542. goto cleanup;
  543. }
  544. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  545. if(!client->endpointUrl.data) {
  546. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  547. goto cleanup;
  548. }
  549. client->connection.localConf = client->config.localConnectionConfig;
  550. retval = HelAckHandshake(client);
  551. if(retval == UA_STATUSCODE_GOOD)
  552. retval = SecureChannelHandshake(client, false);
  553. if(retval == UA_STATUSCODE_GOOD)
  554. retval = EndpointsHandshake(client);
  555. if(retval == UA_STATUSCODE_GOOD)
  556. retval = SessionHandshake(client);
  557. if(retval == UA_STATUSCODE_GOOD)
  558. retval = ActivateSession(client);
  559. if(retval == UA_STATUSCODE_GOOD) {
  560. client->connection.state = UA_CONNECTION_ESTABLISHED;
  561. client->state = UA_CLIENTSTATE_CONNECTED;
  562. } else {
  563. goto cleanup;
  564. }
  565. return retval;
  566. cleanup:
  567. UA_Client_reset(client);
  568. return retval;
  569. }
  570. UA_StatusCode UA_Client_disconnect(UA_Client *client) {
  571. if(client->state == UA_CLIENTSTATE_READY)
  572. return UA_STATUSCODE_BADNOTCONNECTED;
  573. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  574. /* Is a session established? */
  575. if(client->connection.state == UA_CONNECTION_ESTABLISHED &&
  576. !UA_NodeId_equal(&client->authenticationToken, &UA_NODEID_NULL))
  577. retval = CloseSession(client);
  578. /* Is a secure channel established? */
  579. if(client->connection.state == UA_CONNECTION_ESTABLISHED)
  580. retval |= CloseSecureChannel(client);
  581. return retval;
  582. }
  583. UA_StatusCode UA_Client_manuallyRenewSecureChannel(UA_Client *client) {
  584. UA_StatusCode retval = SecureChannelHandshake(client, true);
  585. if(retval == UA_STATUSCODE_GOOD)
  586. client->state = UA_CLIENTSTATE_CONNECTED;
  587. return retval;
  588. }
  589. /****************/
  590. /* Raw Services */
  591. /****************/
  592. struct ResponseDescription {
  593. UA_Client *client;
  594. UA_Boolean processed;
  595. UA_UInt32 requestId;
  596. void *response;
  597. const UA_DataType *responseType;
  598. };
  599. static void
  600. processServiceResponse(struct ResponseDescription *rd, UA_SecureChannel *channel,
  601. UA_MessageType messageType, UA_UInt32 requestId,
  602. UA_ByteString *message) {
  603. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  604. const UA_NodeId expectedNodeId =
  605. UA_NODEID_NUMERIC(0, rd->responseType->binaryEncodingId);
  606. const UA_NodeId serviceFaultNodeId =
  607. UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_SERVICEFAULT].binaryEncodingId);
  608. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)rd->response;
  609. rd->processed = true;
  610. if(messageType == UA_MESSAGETYPE_ERR) {
  611. UA_TcpErrorMessage *msg = (UA_TcpErrorMessage*)message;
  612. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  613. "Server replied with an error message: %s %.*s",
  614. UA_StatusCode_name(msg->error), msg->reason.length, msg->reason.data);
  615. retval = msg->error;
  616. goto finish;
  617. } else if(messageType != UA_MESSAGETYPE_MSG) {
  618. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  619. "Server replied with the wrong message type");
  620. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  621. goto finish;
  622. }
  623. /* Check that the request id matches */
  624. /* Todo: we need to demux async responses since a publish responses may come
  625. at any time */
  626. if(requestId != rd->requestId) {
  627. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  628. "Reply answers the wrong requestId. "
  629. "Async services are not yet implemented.");
  630. retval = UA_STATUSCODE_BADINTERNALERROR;
  631. goto finish;
  632. }
  633. /* Check that the response type matches */
  634. size_t offset = 0;
  635. UA_NodeId responseId;
  636. retval = UA_NodeId_decodeBinary(message, &offset, &responseId);
  637. if(retval != UA_STATUSCODE_GOOD)
  638. goto finish;
  639. if(!UA_NodeId_equal(&responseId, &expectedNodeId)) {
  640. if(UA_NodeId_equal(&responseId, &serviceFaultNodeId)) {
  641. /* Take the statuscode from the servicefault */
  642. retval = UA_decodeBinary(message, &offset, rd->response,
  643. &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  644. } else {
  645. UA_LOG_ERROR(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  646. "Reply answers the wrong request. Expected ns=%i,i=%i."
  647. "But retrieved ns=%i,i=%i", expectedNodeId.namespaceIndex,
  648. expectedNodeId.identifier.numeric, responseId.namespaceIndex,
  649. responseId.identifier.numeric);
  650. UA_NodeId_deleteMembers(&responseId);
  651. retval = UA_STATUSCODE_BADINTERNALERROR;
  652. }
  653. goto finish;
  654. }
  655. /* Decode the response */
  656. retval = UA_decodeBinary(message, &offset, rd->response, rd->responseType);
  657. finish:
  658. if(retval == UA_STATUSCODE_GOOD) {
  659. UA_LOG_DEBUG(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  660. "Received a response of type %i", responseId.identifier.numeric);
  661. } else {
  662. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  663. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  664. UA_LOG_INFO(rd->client->config.logger, UA_LOGCATEGORY_CLIENT,
  665. "Error receiving the response");
  666. respHeader->serviceResult = retval;
  667. }
  668. }
  669. void
  670. __UA_Client_Service(UA_Client *client, const void *request, const UA_DataType *requestType,
  671. void *response, const UA_DataType *responseType) {
  672. UA_init(response, responseType);
  673. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  674. /* Make sure we have a valid session */
  675. UA_StatusCode retval = UA_Client_manuallyRenewSecureChannel(client);
  676. if(retval != UA_STATUSCODE_GOOD) {
  677. respHeader->serviceResult = retval;
  678. client->state = UA_CLIENTSTATE_ERRORED;
  679. return;
  680. }
  681. /* Adjusting the request header. The const attribute is violated, but we
  682. * only touch the following members: */
  683. UA_RequestHeader *rr = (UA_RequestHeader*)(uintptr_t)request;
  684. rr->authenticationToken = client->authenticationToken; /* cleaned up at the end */
  685. rr->timestamp = UA_DateTime_now();
  686. rr->requestHandle = ++client->requestHandle;
  687. /* Send the request */
  688. UA_UInt32 requestId = ++client->requestId;
  689. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  690. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  691. retval = UA_SecureChannel_sendBinaryMessage(&client->channel, requestId, rr, requestType);
  692. if(retval != UA_STATUSCODE_GOOD) {
  693. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  694. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  695. else
  696. respHeader->serviceResult = retval;
  697. client->state = UA_CLIENTSTATE_FAULTED;
  698. UA_NodeId_init(&rr->authenticationToken);
  699. return;
  700. }
  701. /* Prepare the response and the structure we give into processServiceResponse */
  702. UA_init(response, responseType);
  703. struct ResponseDescription rd = {client, false, requestId, response, responseType};
  704. /* Retrieve the response */
  705. UA_DateTime maxDate = UA_DateTime_nowMonotonic() + (client->config.timeout * UA_MSEC_TO_DATETIME);
  706. do {
  707. /* Retrieve complete chunks */
  708. UA_ByteString reply = UA_BYTESTRING_NULL;
  709. UA_Boolean realloced = false;
  710. UA_DateTime now = UA_DateTime_nowMonotonic();
  711. if(now < maxDate) {
  712. UA_UInt32 timeout = (UA_UInt32)((maxDate - now) / UA_MSEC_TO_DATETIME);
  713. retval = UA_Connection_receiveChunksBlocking(&client->connection, &reply, &realloced, timeout);
  714. } else {
  715. retval = UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  716. }
  717. if(retval != UA_STATUSCODE_GOOD) {
  718. respHeader->serviceResult = retval;
  719. break;
  720. }
  721. /* ProcessChunks and call processServiceResponse for complete messages */
  722. UA_SecureChannel_processChunks(&client->channel, &reply,
  723. (UA_ProcessMessageCallback*)processServiceResponse, &rd);
  724. /* Free the received buffer */
  725. if(!realloced)
  726. client->connection.releaseRecvBuffer(&client->connection, &reply);
  727. else
  728. UA_ByteString_deleteMembers(&reply);
  729. } while(!rd.processed);
  730. /* Clean up the authentication token */
  731. UA_NodeId_init(&rr->authenticationToken);
  732. }