ua_client.c 34 KB

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