ua_client.c 38 KB

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