ua_client.c 35 KB

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