ua_client.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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_types_generated.h"
  6. #include "ua_nodeids.h"
  7. #include "ua_types_encoding_binary.h"
  8. #include "ua_transport_generated.h"
  9. #include "ua_types_generated_encoding_binary.h"
  10. #include "ua_transport_generated_encoding_binary.h"
  11. const UA_EXPORT UA_ClientConfig UA_ClientConfig_standard =
  12. { .timeout = 5000 /* ms receive timout */, .secureChannelLifeTime = 600000,
  13. {.protocolVersion = 0, .sendBufferSize = 65536, .recvBufferSize = 65536,
  14. .maxMessageSize = 65536, .maxChunkCount = 1}};
  15. /*********************/
  16. /* Create and Delete */
  17. /*********************/
  18. static void UA_Client_init(UA_Client* client, UA_ClientConfig config,
  19. UA_Logger logger) {
  20. client->state = UA_CLIENTSTATE_READY;
  21. UA_Connection_init(&client->connection);
  22. UA_SecureChannel_init(&client->channel);
  23. client->channel.connection = &client->connection;
  24. UA_String_init(&client->endpointUrl);
  25. client->requestId = 0;
  26. UA_NodeId_init(&client->authenticationToken);
  27. client->requestHandle = 0;
  28. client->logger = logger;
  29. client->config = config;
  30. client->scRenewAt = 0;
  31. #ifdef UA_ENABLE_SUBSCRIPTIONS
  32. client->monitoredItemHandles = 0;
  33. LIST_INIT(&client->pendingNotificationsAcks);
  34. LIST_INIT(&client->subscriptions);
  35. #endif
  36. }
  37. UA_Client * UA_Client_new(UA_ClientConfig config, UA_Logger logger) {
  38. UA_Client *client = UA_calloc(1, sizeof(UA_Client));
  39. if(!client)
  40. return NULL;
  41. UA_Client_init(client, config, logger);
  42. return client;
  43. }
  44. static void UA_Client_deleteMembers(UA_Client* client) {
  45. UA_Client_disconnect(client);
  46. UA_Connection_deleteMembers(&client->connection);
  47. UA_SecureChannel_deleteMembersCleanup(&client->channel);
  48. if(client->endpointUrl.data)
  49. UA_String_deleteMembers(&client->endpointUrl);
  50. UA_UserTokenPolicy_deleteMembers(&client->token);
  51. #ifdef UA_ENABLE_SUBSCRIPTIONS
  52. UA_Client_NotificationsAckNumber *n, *tmp;
  53. LIST_FOREACH_SAFE(n, &client->pendingNotificationsAcks, listEntry, tmp) {
  54. LIST_REMOVE(n, listEntry);
  55. free(n);
  56. }
  57. UA_Client_Subscription *sub, *tmps;
  58. LIST_FOREACH_SAFE(sub, &client->subscriptions, listEntry, tmps) {
  59. LIST_REMOVE(sub, listEntry);
  60. UA_Client_MonitoredItem *mon, *tmpmon;
  61. LIST_FOREACH_SAFE(mon, &sub->MonitoredItems, listEntry, tmpmon) {
  62. UA_Client_Subscriptions_removeMonitoredItem(client, sub->SubscriptionID,
  63. mon->MonitoredItemId);
  64. }
  65. free(sub);
  66. }
  67. #endif
  68. }
  69. void UA_Client_reset(UA_Client* client){
  70. UA_Client_deleteMembers(client);
  71. UA_Client_init(client, client->config, client->logger);
  72. }
  73. void UA_Client_delete(UA_Client* client){
  74. if(client->state != UA_CLIENTSTATE_READY)
  75. UA_Client_deleteMembers(client);
  76. UA_free(client);
  77. }
  78. /*************************/
  79. /* Manage the Connection */
  80. /*************************/
  81. static UA_StatusCode HelAckHandshake(UA_Client *c) {
  82. UA_TcpMessageHeader messageHeader;
  83. messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_HELF;
  84. UA_TcpHelloMessage hello;
  85. UA_String_copy(&c->endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  86. UA_Connection *conn = &c->connection;
  87. hello.maxChunkCount = conn->localConf.maxChunkCount;
  88. hello.maxMessageSize = conn->localConf.maxMessageSize;
  89. hello.protocolVersion = conn->localConf.protocolVersion;
  90. hello.receiveBufferSize = conn->localConf.recvBufferSize;
  91. hello.sendBufferSize = conn->localConf.sendBufferSize;
  92. UA_ByteString message;
  93. UA_StatusCode retval;
  94. retval = c->connection.getSendBuffer(&c->connection, c->connection.remoteConf.recvBufferSize, &message);
  95. if(retval != UA_STATUSCODE_GOOD)
  96. return retval;
  97. size_t offset = 8;
  98. retval |= UA_TcpHelloMessage_encodeBinary(&hello, &message, &offset);
  99. messageHeader.messageSize = (UA_UInt32)offset;
  100. offset = 0;
  101. retval |= UA_TcpMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  102. UA_TcpHelloMessage_deleteMembers(&hello);
  103. if(retval != UA_STATUSCODE_GOOD) {
  104. c->connection.releaseSendBuffer(&c->connection, &message);
  105. return retval;
  106. }
  107. message.length = messageHeader.messageSize;
  108. retval = c->connection.send(&c->connection, &message);
  109. if(retval != UA_STATUSCODE_GOOD) {
  110. UA_LOG_INFO(c->logger, UA_LOGCATEGORY_NETWORK, "Sending HEL failed");
  111. return retval;
  112. }
  113. UA_LOG_DEBUG(c->logger, UA_LOGCATEGORY_NETWORK, "Sent HEL message");
  114. UA_ByteString reply;
  115. UA_ByteString_init(&reply);
  116. UA_Boolean realloced = UA_FALSE;
  117. do {
  118. retval = c->connection.recv(&c->connection, &reply, c->config.timeout);
  119. retval |= UA_Connection_completeMessages(&c->connection, &reply, &realloced);
  120. if(retval != UA_STATUSCODE_GOOD) {
  121. UA_LOG_INFO(c->logger, UA_LOGCATEGORY_NETWORK, "Receiving ACK message failed");
  122. return retval;
  123. }
  124. } while(reply.length == 0);
  125. offset = 0;
  126. UA_TcpMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  127. UA_TcpAcknowledgeMessage ackMessage;
  128. retval = UA_TcpAcknowledgeMessage_decodeBinary(&reply, &offset, &ackMessage);
  129. if(!realloced)
  130. c->connection.releaseRecvBuffer(&c->connection, &reply);
  131. else
  132. UA_ByteString_deleteMembers(&reply);
  133. if(retval != UA_STATUSCODE_GOOD) {
  134. UA_LOG_INFO(c->logger, UA_LOGCATEGORY_NETWORK, "Decoding ACK message failed");
  135. return retval;
  136. }
  137. UA_LOG_DEBUG(c->logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  138. conn->remoteConf.maxChunkCount = ackMessage.maxChunkCount;
  139. conn->remoteConf.maxMessageSize = ackMessage.maxMessageSize;
  140. conn->remoteConf.protocolVersion = ackMessage.protocolVersion;
  141. conn->remoteConf.recvBufferSize = ackMessage.receiveBufferSize;
  142. conn->remoteConf.sendBufferSize = ackMessage.sendBufferSize;
  143. conn->state = UA_CONNECTION_ESTABLISHED;
  144. return UA_STATUSCODE_GOOD;
  145. }
  146. static UA_StatusCode SecureChannelHandshake(UA_Client *client, UA_Boolean renew) {
  147. /* Check if sc is still valid */
  148. if(renew && client->scRenewAt - UA_DateTime_now() > 0)
  149. return UA_STATUSCODE_GOOD;
  150. UA_Connection *c = &client->connection;
  151. if(c->state != UA_CONNECTION_ESTABLISHED)
  152. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  153. UA_SecureConversationMessageHeader messageHeader;
  154. messageHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_OPNF;
  155. if(renew)
  156. messageHeader.secureChannelId = client->channel.securityToken.channelId;
  157. else
  158. messageHeader.secureChannelId = 0;
  159. UA_SequenceHeader seqHeader;
  160. seqHeader.sequenceNumber = ++client->channel.sequenceNumber;
  161. seqHeader.requestId = ++client->requestId;
  162. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  163. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  164. asymHeader.securityPolicyUri = UA_STRING_ALLOC("http://opcfoundation.org/UA/SecurityPolicy#None");
  165. /* id of opensecurechannelrequest */
  166. UA_NodeId requestType = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  167. UA_OpenSecureChannelRequest opnSecRq;
  168. UA_OpenSecureChannelRequest_init(&opnSecRq);
  169. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  170. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  171. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  172. if(renew) {
  173. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  174. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to renew the SecureChannel");
  175. } else {
  176. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  177. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to open a SecureChannel");
  178. }
  179. UA_ByteString_copy(&client->channel.clientNonce, &opnSecRq.clientNonce);
  180. opnSecRq.securityMode = UA_MESSAGESECURITYMODE_NONE;
  181. UA_ByteString message;
  182. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  183. if(retval != UA_STATUSCODE_GOOD) {
  184. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  185. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  186. return retval;
  187. }
  188. size_t offset = 12;
  189. retval = UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &message, &offset);
  190. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  191. retval |= UA_NodeId_encodeBinary(&requestType, &message, &offset);
  192. retval |= UA_OpenSecureChannelRequest_encodeBinary(&opnSecRq, &message, &offset);
  193. messageHeader.messageHeader.messageSize = (UA_UInt32)offset;
  194. offset = 0;
  195. retval |= UA_SecureConversationMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  196. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  197. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  198. if(retval != UA_STATUSCODE_GOOD) {
  199. client->connection.releaseSendBuffer(&client->connection, &message);
  200. return retval;
  201. }
  202. message.length = messageHeader.messageHeader.messageSize;
  203. retval = client->connection.send(&client->connection, &message);
  204. if(retval != UA_STATUSCODE_GOOD)
  205. return retval;
  206. UA_ByteString reply;
  207. UA_ByteString_init(&reply);
  208. UA_Boolean realloced = UA_FALSE;
  209. do {
  210. retval = c->recv(c, &reply, client->config.timeout);
  211. retval |= UA_Connection_completeMessages(c, &reply, &realloced);
  212. if(retval != UA_STATUSCODE_GOOD) {
  213. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL,
  214. "Receiving OpenSecureChannelResponse failed");
  215. return retval;
  216. }
  217. } while(reply.length == 0);
  218. offset = 0;
  219. UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  220. UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &asymHeader);
  221. UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  222. UA_NodeId_decodeBinary(&reply, &offset, &requestType);
  223. UA_NodeId expectedRequest = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE +
  224. UA_ENCODINGOFFSET_BINARY);
  225. if(!UA_NodeId_equal(&requestType, &expectedRequest)) {
  226. UA_ByteString_deleteMembers(&reply);
  227. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  228. UA_NodeId_deleteMembers(&requestType);
  229. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  230. "Reply answers the wrong request. Expected OpenSecureChannelResponse.");
  231. return UA_STATUSCODE_BADINTERNALERROR;
  232. }
  233. UA_OpenSecureChannelResponse response;
  234. UA_OpenSecureChannelResponse_init(&response);
  235. retval = UA_OpenSecureChannelResponse_decodeBinary(&reply, &offset, &response);
  236. if(!realloced)
  237. c->releaseRecvBuffer(c, &reply);
  238. else
  239. UA_ByteString_deleteMembers(&reply);
  240. if(retval != UA_STATUSCODE_GOOD) {
  241. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Decoding OpenSecureChannelResponse failed");
  242. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  243. UA_OpenSecureChannelResponse_init(&response);
  244. response.responseHeader.serviceResult = retval;
  245. return retval;
  246. }
  247. //response.securityToken.revisedLifetime is UInt32 we need to cast it to DateTime=Int64
  248. //we take 75% of lifetime to start renewing as described in standard
  249. client->scRenewAt = UA_DateTime_now() +
  250. (UA_DateTime)(response.securityToken.revisedLifetime * (UA_Double)UA_MSEC_TO_DATETIME * 0.75);
  251. retval = response.responseHeader.serviceResult;
  252. if(retval != UA_STATUSCODE_GOOD)
  253. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel could not be opened / renewed");
  254. else {
  255. UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
  256. UA_ChannelSecurityToken_copy(&response.securityToken, &client->channel.securityToken);
  257. /* if the handshake is repeated, replace the old nonce */
  258. UA_ByteString_deleteMembers(&client->channel.serverNonce);
  259. UA_ByteString_copy(&response.serverNonce, &client->channel.serverNonce);
  260. if(renew)
  261. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel renewed");
  262. else
  263. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel opened");
  264. }
  265. UA_OpenSecureChannelResponse_deleteMembers(&response);
  266. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  267. return retval;
  268. }
  269. static UA_StatusCode ActivateSession(UA_Client *client) {
  270. UA_ActivateSessionRequest request;
  271. UA_ActivateSessionRequest_init(&request);
  272. request.requestHeader.requestHandle = 2; //TODO: is it a magic number?
  273. request.requestHeader.authenticationToken = client->authenticationToken;
  274. request.requestHeader.timestamp = UA_DateTime_now();
  275. request.requestHeader.timeoutHint = 600000;
  276. UA_AnonymousIdentityToken identityToken;
  277. UA_AnonymousIdentityToken_init(&identityToken);
  278. UA_String_copy(&client->token.policyId, &identityToken.policyId);
  279. //manual ExtensionObject encoding of the identityToken
  280. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED_NODELETE;
  281. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  282. request.userIdentityToken.content.decoded.data = &identityToken;
  283. UA_ActivateSessionResponse response;
  284. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  285. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  286. UA_AnonymousIdentityToken_deleteMembers(&identityToken);
  287. UA_ActivateSessionRequest_deleteMembers(&request);
  288. UA_ActivateSessionResponse_deleteMembers(&response);
  289. return response.responseHeader.serviceResult; // not deleted
  290. }
  291. /**
  292. * Gets a list of endpoints
  293. * Memory is allocated for endpointDescription array
  294. */
  295. static UA_StatusCode
  296. GetEndpoints(UA_Client *client, size_t* endpointDescriptionsSize, UA_EndpointDescription** endpointDescriptions) {
  297. UA_GetEndpointsRequest request;
  298. UA_GetEndpointsRequest_init(&request);
  299. request.requestHeader.authenticationToken = client->authenticationToken;
  300. request.requestHeader.timestamp = UA_DateTime_now();
  301. request.requestHeader.timeoutHint = 10000;
  302. request.endpointUrl = client->endpointUrl; // assume the endpointurl outlives the service call
  303. UA_GetEndpointsResponse response;
  304. UA_GetEndpointsResponse_init(&response);
  305. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  306. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  307. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  308. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "GetEndpointRequest failed");
  309. UA_GetEndpointsResponse_deleteMembers(&response);
  310. return response.responseHeader.serviceResult;
  311. }
  312. *endpointDescriptionsSize = response.endpointsSize;
  313. *endpointDescriptions = UA_Array_new(response.endpointsSize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  314. for(size_t i=0;i<response.endpointsSize;i++)
  315. UA_EndpointDescription_copy(&response.endpoints[i], &(*endpointDescriptions)[i]);
  316. UA_GetEndpointsResponse_deleteMembers(&response);
  317. return UA_STATUSCODE_GOOD;
  318. }
  319. static UA_StatusCode EndpointsHandshake(UA_Client *client) {
  320. UA_EndpointDescription* endpointArray = NULL;
  321. size_t endpointArraySize = 0;
  322. UA_StatusCode retval = GetEndpoints(client, &endpointArraySize, &endpointArray);
  323. UA_Boolean endpointFound = UA_FALSE;
  324. UA_Boolean tokenFound = UA_FALSE;
  325. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  326. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");
  327. //TODO: compare endpoint information with client->endpointUri
  328. for(size_t i = 0; i < endpointArraySize; i++) {
  329. UA_EndpointDescription* endpoint = &endpointArray[i];
  330. /* look out for binary transport endpoints */
  331. //NODE: Siemens returns empty ProfileUrl, we will accept it as binary
  332. if(endpoint->transportProfileUri.length!=0 && !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  333. continue;
  334. /* look out for an endpoint without security */
  335. if(!UA_String_equal(&endpoint->securityPolicyUri, &securityNone))
  336. continue;
  337. endpointFound = UA_TRUE;
  338. /* endpoint with no security found */
  339. /* look for a user token policy with an anonymous token */
  340. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  341. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  342. if(userToken->tokenType != UA_USERTOKENTYPE_ANONYMOUS)
  343. continue;
  344. tokenFound = UA_TRUE;
  345. UA_UserTokenPolicy_copy(userToken, &client->token);
  346. break;
  347. }
  348. }
  349. //cleanup array
  350. UA_Array_delete(endpointArray,endpointArraySize,&UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  351. if(!endpointFound) {
  352. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "No suitable endpoint found");
  353. return UA_STATUSCODE_BADINTERNALERROR;
  354. }
  355. if(!tokenFound) {
  356. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "No anonymous token found");
  357. return UA_STATUSCODE_BADINTERNALERROR;
  358. }
  359. return retval;
  360. }
  361. static UA_StatusCode SessionHandshake(UA_Client *client) {
  362. UA_CreateSessionRequest request;
  363. UA_CreateSessionRequest_init(&request);
  364. // todo: is this needed for all requests?
  365. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  366. request.requestHeader.timestamp = UA_DateTime_now();
  367. request.requestHeader.timeoutHint = 10000;
  368. UA_ByteString_copy(&client->channel.clientNonce, &request.clientNonce);
  369. request.requestedSessionTimeout = 1200000;
  370. request.maxResponseMessageSize = UA_INT32_MAX;
  371. UA_CreateSessionResponse response;
  372. UA_CreateSessionResponse_init(&response);
  373. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  374. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  375. UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  376. UA_CreateSessionRequest_deleteMembers(&request);
  377. UA_CreateSessionResponse_deleteMembers(&response);
  378. return response.responseHeader.serviceResult; // not deleted
  379. }
  380. static UA_StatusCode CloseSession(UA_Client *client) {
  381. UA_CloseSessionRequest request;
  382. UA_CloseSessionRequest_init(&request);
  383. request.requestHeader.timestamp = UA_DateTime_now();
  384. request.requestHeader.timeoutHint = 10000;
  385. request.deleteSubscriptions = UA_TRUE;
  386. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  387. UA_CloseSessionResponse response;
  388. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  389. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  390. UA_CloseSessionRequest_deleteMembers(&request);
  391. UA_CloseSessionResponse_deleteMembers(&response);
  392. return response.responseHeader.serviceResult; // not deleted
  393. }
  394. static UA_StatusCode CloseSecureChannel(UA_Client *client) {
  395. UA_SecureChannel *channel = &client->channel;
  396. UA_CloseSecureChannelRequest request;
  397. UA_CloseSecureChannelRequest_init(&request);
  398. request.requestHeader.requestHandle = 1; //TODO: magic number?
  399. request.requestHeader.timestamp = UA_DateTime_now();
  400. request.requestHeader.timeoutHint = 10000;
  401. request.requestHeader.authenticationToken = client->authenticationToken;
  402. UA_SecureConversationMessageHeader msgHeader;
  403. msgHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_CLOF;
  404. msgHeader.secureChannelId = client->channel.securityToken.channelId;
  405. UA_SymmetricAlgorithmSecurityHeader symHeader;
  406. symHeader.tokenId = channel->securityToken.tokenId;
  407. UA_SequenceHeader seqHeader;
  408. seqHeader.sequenceNumber = ++channel->sequenceNumber;
  409. seqHeader.requestId = ++client->requestId;
  410. UA_NodeId typeId = UA_NODEID_NUMERIC(0, UA_NS0ID_CLOSESECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  411. UA_ByteString message;
  412. UA_Connection *c = &client->connection;
  413. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  414. if(retval != UA_STATUSCODE_GOOD)
  415. return retval;
  416. size_t offset = 12;
  417. retval |= UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symHeader, &message, &offset);
  418. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  419. retval |= UA_NodeId_encodeBinary(&typeId, &message, &offset);
  420. retval |= UA_encodeBinary(&request, &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST], &message, &offset);
  421. msgHeader.messageHeader.messageSize = (UA_UInt32)offset;
  422. offset = 0;
  423. retval |= UA_SecureConversationMessageHeader_encodeBinary(&msgHeader, &message, &offset);
  424. if(retval != UA_STATUSCODE_GOOD) {
  425. client->connection.releaseSendBuffer(&client->connection, &message);
  426. return retval;
  427. }
  428. message.length = msgHeader.messageHeader.messageSize;
  429. retval = client->connection.send(&client->connection, &message);
  430. return retval;
  431. }
  432. UA_StatusCode
  433. UA_Client_getEndpoints(UA_Client *client, UA_ConnectClientConnection connectFunc,
  434. const char *serverUrl, size_t* endpointDescriptionsSize,
  435. UA_EndpointDescription** endpointDescriptions) {
  436. if(client->state == UA_CLIENTSTATE_CONNECTED)
  437. return UA_STATUSCODE_GOOD;
  438. if(client->state == UA_CLIENTSTATE_ERRORED) {
  439. UA_Client_reset(client);
  440. }
  441. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  442. client->connection = connectFunc(UA_ConnectionConfig_standard, serverUrl, client->logger);
  443. if(client->connection.state != UA_CONNECTION_OPENING) {
  444. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  445. goto cleanup;
  446. }
  447. client->endpointUrl = UA_STRING_ALLOC(serverUrl);
  448. if(!client->endpointUrl.data) {
  449. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  450. goto cleanup;
  451. }
  452. client->connection.localConf = client->config.localConnectionConfig;
  453. retval = HelAckHandshake(client);
  454. if(retval == UA_STATUSCODE_GOOD)
  455. retval = SecureChannelHandshake(client, UA_FALSE);
  456. if(retval == UA_STATUSCODE_GOOD)
  457. retval = GetEndpoints(client, endpointDescriptionsSize, endpointDescriptions);
  458. //we always cleanup
  459. cleanup:
  460. UA_Client_reset(client);
  461. return retval;
  462. }
  463. UA_StatusCode UA_Client_connect(UA_Client *client, UA_ConnectClientConnection connectFunc,
  464. const char *endpointUrl) {
  465. if(client->state == UA_CLIENTSTATE_CONNECTED)
  466. return UA_STATUSCODE_GOOD;
  467. if(client->state == UA_CLIENTSTATE_ERRORED) {
  468. UA_Client_reset(client);
  469. }
  470. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  471. client->connection = connectFunc(UA_ConnectionConfig_standard, endpointUrl, client->logger);
  472. if(client->connection.state != UA_CONNECTION_OPENING) {
  473. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  474. goto cleanup;
  475. }
  476. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  477. if(!client->endpointUrl.data) {
  478. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  479. goto cleanup;
  480. }
  481. client->connection.localConf = client->config.localConnectionConfig;
  482. retval = HelAckHandshake(client);
  483. if(retval == UA_STATUSCODE_GOOD)
  484. retval = SecureChannelHandshake(client, UA_FALSE);
  485. if(retval == UA_STATUSCODE_GOOD)
  486. retval = EndpointsHandshake(client);
  487. if(retval == UA_STATUSCODE_GOOD)
  488. retval = SessionHandshake(client);
  489. if(retval == UA_STATUSCODE_GOOD)
  490. retval = ActivateSession(client);
  491. if(retval == UA_STATUSCODE_GOOD) {
  492. client->connection.state = UA_CONNECTION_ESTABLISHED;
  493. client->state = UA_CLIENTSTATE_CONNECTED;
  494. } else {
  495. goto cleanup;
  496. }
  497. return retval;
  498. cleanup:
  499. UA_Client_reset(client);
  500. return retval;
  501. }
  502. UA_StatusCode UA_Client_disconnect(UA_Client *client) {
  503. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  504. //is a session established?
  505. if(client->state == UA_CLIENTSTATE_CONNECTED && client->channel.connection->state == UA_CONNECTION_ESTABLISHED){
  506. retval = CloseSession(client);
  507. }
  508. //is a secure channel established?
  509. if(retval == UA_STATUSCODE_GOOD && client->channel.connection->state == UA_CONNECTION_ESTABLISHED){
  510. retval = CloseSecureChannel(client);
  511. }
  512. return retval;
  513. }
  514. UA_StatusCode UA_Client_manuallyRenewSecureChannel(UA_Client *client) {
  515. return SecureChannelHandshake(client, UA_TRUE);
  516. }
  517. /****************/
  518. /* Raw Services */
  519. /****************/
  520. void __UA_Client_Service(UA_Client *client, const void *r, const UA_DataType *requestType,
  521. void *response, const UA_DataType *responseType) {
  522. /* Requests always begin witih a RequestHeader, therefore we can cast. */
  523. UA_RequestHeader *request = (void*)(uintptr_t)r;
  524. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  525. UA_init(response, responseType);
  526. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  527. /* make sure we have a valid session */
  528. retval = UA_Client_manuallyRenewSecureChannel(client);
  529. if(retval != UA_STATUSCODE_GOOD) {
  530. respHeader->serviceResult = retval;
  531. client->state = UA_CLIENTSTATE_ERRORED;
  532. return;
  533. }
  534. /* handling request parameters */
  535. UA_NodeId_copy(&client->authenticationToken, &request->authenticationToken);
  536. request->timestamp = UA_DateTime_now();
  537. request->requestHandle = ++client->requestHandle;
  538. /* Send the request */
  539. UA_UInt32 requestId = ++client->requestId;
  540. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  541. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  542. retval = UA_SecureChannel_sendBinaryMessage(&client->channel, requestId, request, requestType);
  543. if(retval != UA_STATUSCODE_GOOD) {
  544. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  545. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  546. else
  547. respHeader->serviceResult = retval;
  548. client->state = UA_CLIENTSTATE_ERRORED;
  549. return;
  550. }
  551. /* Retrieve the response */
  552. // Todo: push this into the generic securechannel implementation for client and server
  553. UA_ByteString reply;
  554. UA_ByteString_init(&reply);
  555. UA_Boolean realloced = UA_FALSE;
  556. do {
  557. retval = client->connection.recv(&client->connection, &reply, client->config.timeout);
  558. retval |= UA_Connection_completeMessages(&client->connection, &reply, &realloced);
  559. if(retval != UA_STATUSCODE_GOOD) {
  560. respHeader->serviceResult = retval;
  561. client->state = UA_CLIENTSTATE_ERRORED;
  562. return;
  563. }
  564. } while(!reply.data);
  565. size_t offset = 0;
  566. UA_SecureConversationMessageHeader msgHeader;
  567. retval |= UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &msgHeader);
  568. UA_SymmetricAlgorithmSecurityHeader symHeader;
  569. retval |= UA_SymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &symHeader);
  570. UA_SequenceHeader seqHeader;
  571. retval |= UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  572. UA_NodeId responseId;
  573. retval |= UA_NodeId_decodeBinary(&reply, &offset, &responseId);
  574. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, responseType->typeId.identifier.numeric +
  575. UA_ENCODINGOFFSET_BINARY);
  576. if(retval != UA_STATUSCODE_GOOD)
  577. goto finish;
  578. /* Todo: we need to demux responses since a publish responses may come at any time */
  579. if(!UA_NodeId_equal(&responseId, &expectedNodeId) || seqHeader.requestId != requestId) {
  580. if(responseId.identifier.numeric != UA_NS0ID_SERVICEFAULT + UA_ENCODINGOFFSET_BINARY) {
  581. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT,
  582. "Reply answers the wrong request. Expected ns=%i,i=%i. But retrieved ns=%i,i=%i",
  583. expectedNodeId.namespaceIndex, expectedNodeId.identifier.numeric,
  584. responseId.namespaceIndex, responseId.identifier.numeric);
  585. respHeader->serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  586. } else
  587. retval = UA_decodeBinary(&reply, &offset, respHeader, &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  588. goto finish;
  589. }
  590. retval = UA_decodeBinary(&reply, &offset, response, responseType);
  591. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  592. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  593. finish:
  594. UA_SymmetricAlgorithmSecurityHeader_deleteMembers(&symHeader);
  595. if(!realloced)
  596. client->connection.releaseRecvBuffer(&client->connection, &reply);
  597. else
  598. UA_ByteString_deleteMembers(&reply);
  599. if(retval != UA_STATUSCODE_GOOD){
  600. UA_LOG_INFO(client->logger, UA_LOGCATEGORY_CLIENT, "Error receiving the response");
  601. client->state = UA_CLIENTSTATE_ERRORED;
  602. respHeader->serviceResult = retval;
  603. }
  604. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT, "Received a response of type %i", responseId.identifier.numeric);
  605. }