ua_client.c 38 KB

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