ua_client.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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. }
  160. UA_SequenceHeader seqHeader;
  161. seqHeader.sequenceNumber = ++client->channel.sequenceNumber;
  162. seqHeader.requestId = ++client->requestId;
  163. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  164. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  165. asymHeader.securityPolicyUri = UA_STRING_ALLOC("http://opcfoundation.org/UA/SecurityPolicy#None");
  166. /* id of opensecurechannelrequest */
  167. UA_NodeId requestType = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  168. UA_OpenSecureChannelRequest opnSecRq;
  169. UA_OpenSecureChannelRequest_init(&opnSecRq);
  170. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  171. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  172. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  173. if(renew) {
  174. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  175. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to renew the SecureChannel");
  176. } else {
  177. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  178. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to open a SecureChannel");
  179. }
  180. UA_ByteString_copy(&client->channel.clientNonce, &opnSecRq.clientNonce);
  181. opnSecRq.securityMode = UA_MESSAGESECURITYMODE_NONE;
  182. UA_ByteString message;
  183. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  184. if(retval != UA_STATUSCODE_GOOD) {
  185. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  186. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  187. return retval;
  188. }
  189. size_t offset = 12;
  190. retval = UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &message, &offset);
  191. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  192. retval |= UA_NodeId_encodeBinary(&requestType, &message, &offset);
  193. retval |= UA_OpenSecureChannelRequest_encodeBinary(&opnSecRq, &message, &offset);
  194. messageHeader.messageHeader.messageSize = (UA_UInt32)offset;
  195. offset = 0;
  196. retval |= UA_SecureConversationMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  197. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  198. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  199. if(retval != UA_STATUSCODE_GOOD) {
  200. client->connection.releaseSendBuffer(&client->connection, &message);
  201. return retval;
  202. }
  203. message.length = messageHeader.messageHeader.messageSize;
  204. retval = client->connection.send(&client->connection, &message);
  205. if(retval != UA_STATUSCODE_GOOD)
  206. return retval;
  207. UA_ByteString reply;
  208. UA_ByteString_init(&reply);
  209. UA_Boolean realloced = UA_FALSE;
  210. do {
  211. retval = c->recv(c, &reply, client->config.timeout);
  212. retval |= UA_Connection_completeMessages(c, &reply, &realloced);
  213. if(retval != UA_STATUSCODE_GOOD) {
  214. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL,
  215. "Receiving OpenSecureChannelResponse failed");
  216. return retval;
  217. }
  218. } while(reply.length == 0);
  219. offset = 0;
  220. UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  221. UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &asymHeader);
  222. UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  223. UA_NodeId_decodeBinary(&reply, &offset, &requestType);
  224. UA_NodeId expectedRequest = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE +
  225. UA_ENCODINGOFFSET_BINARY);
  226. if(!UA_NodeId_equal(&requestType, &expectedRequest)) {
  227. UA_ByteString_deleteMembers(&reply);
  228. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  229. UA_NodeId_deleteMembers(&requestType);
  230. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  231. "Reply answers the wrong request. Expected OpenSecureChannelResponse.");
  232. return UA_STATUSCODE_BADINTERNALERROR;
  233. }
  234. UA_OpenSecureChannelResponse response;
  235. UA_OpenSecureChannelResponse_init(&response);
  236. retval = UA_OpenSecureChannelResponse_decodeBinary(&reply, &offset, &response);
  237. if(!realloced)
  238. c->releaseRecvBuffer(c, &reply);
  239. else
  240. UA_ByteString_deleteMembers(&reply);
  241. if(retval != UA_STATUSCODE_GOOD) {
  242. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL,
  243. "Decoding OpenSecureChannelResponse failed");
  244. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  245. UA_OpenSecureChannelResponse_init(&response);
  246. response.responseHeader.serviceResult = retval;
  247. return retval;
  248. }
  249. //response.securityToken.revisedLifetime is UInt32 we need to cast it to DateTime=Int64
  250. //we take 75% of lifetime to start renewing as described in standard
  251. client->scRenewAt = UA_DateTime_now() + (UA_DateTime)(response.securityToken.revisedLifetime * (UA_Double)UA_MSEC_TO_DATETIME * 0.75);
  252. retval = response.responseHeader.serviceResult;
  253. if(retval != UA_STATUSCODE_GOOD)
  254. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL,
  255. "SecureChannel could not be opened / renewed");
  256. else {
  257. UA_ChannelSecurityToken_copy(&response.securityToken, &client->channel.securityToken);
  258. /* if the handshake is repeated, replace the old nonce */
  259. UA_ByteString_deleteMembers(&client->channel.serverNonce);
  260. UA_ByteString_copy(&response.serverNonce, &client->channel.serverNonce);
  261. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel opened/renewed");
  262. }
  263. UA_OpenSecureChannelResponse_deleteMembers(&response);
  264. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  265. return retval;
  266. }
  267. static UA_StatusCode ActivateSession(UA_Client *client) {
  268. UA_ActivateSessionRequest request;
  269. UA_ActivateSessionRequest_init(&request);
  270. request.requestHeader.requestHandle = 2; //TODO: is it a magic number?
  271. request.requestHeader.authenticationToken = client->authenticationToken;
  272. request.requestHeader.timestamp = UA_DateTime_now();
  273. request.requestHeader.timeoutHint = 600000;
  274. UA_AnonymousIdentityToken identityToken;
  275. UA_AnonymousIdentityToken_init(&identityToken);
  276. UA_String_copy(&client->token.policyId, &identityToken.policyId);
  277. //manual ExtensionObject encoding of the identityToken
  278. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED_NODELETE;
  279. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  280. request.userIdentityToken.content.decoded.data = &identityToken;
  281. UA_ActivateSessionResponse response;
  282. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  283. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  284. UA_AnonymousIdentityToken_deleteMembers(&identityToken);
  285. UA_ActivateSessionRequest_deleteMembers(&request);
  286. UA_ActivateSessionResponse_deleteMembers(&response);
  287. return response.responseHeader.serviceResult; // not deleted
  288. }
  289. /**
  290. * Gets a list of endpoints
  291. * Memory is allocated for endpointDescription array
  292. */
  293. static UA_StatusCode GetEndpoints(UA_Client *client, size_t* endpointDescriptionsSize, UA_EndpointDescription** endpointDescriptions) {
  294. UA_GetEndpointsRequest request;
  295. UA_GetEndpointsRequest_init(&request);
  296. request.requestHeader.authenticationToken = client->authenticationToken;
  297. request.requestHeader.timestamp = UA_DateTime_now();
  298. request.requestHeader.timeoutHint = 10000;
  299. request.endpointUrl = client->endpointUrl; //here we assume the endpointUrl is on the stack
  300. //no filter for endpoints
  301. request.profileUrisSize = 0;
  302. UA_GetEndpointsResponse response;
  303. UA_GetEndpointsResponse_init(&response);
  304. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  305. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  306. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  307. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "GetEndpointRequest failed");
  308. return response.responseHeader.serviceResult;
  309. }
  310. *endpointDescriptionsSize = response.endpointsSize;
  311. *endpointDescriptions = UA_Array_new(response.endpointsSize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  312. for(size_t i=0;i<response.endpointsSize;i++){
  313. UA_EndpointDescription_copy(&response.endpoints[i], &(*endpointDescriptions)[i]);
  314. }
  315. UA_GetEndpointsResponse_deleteMembers(&response);
  316. return response.responseHeader.serviceResult;
  317. }
  318. static UA_StatusCode EndpointsHandshake(UA_Client *client) {
  319. UA_EndpointDescription* endpointArray = NULL;
  320. size_t endpointArraySize = 0;
  321. UA_StatusCode retval = GetEndpoints(client, &endpointArraySize, &endpointArray);
  322. UA_Boolean endpointFound = UA_FALSE;
  323. UA_Boolean tokenFound = UA_FALSE;
  324. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  325. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");
  326. //TODO: compare endpoint information with client->endpointUri
  327. for(size_t i = 0; i < endpointArraySize; i++) {
  328. UA_EndpointDescription* endpoint = &endpointArray[i];
  329. /* look out for binary transport endpoints */
  330. //NODE: Siemens returns empty ProfileUrl, we will accept it as binary
  331. if(endpoint->transportProfileUri.length!=0 && !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  332. continue;
  333. /* look out for an endpoint without security */
  334. if(!UA_String_equal(&endpoint->securityPolicyUri, &securityNone))
  335. continue;
  336. endpointFound = UA_TRUE;
  337. /* endpoint with no security found */
  338. /* look for a user token policy with an anonymous token */
  339. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  340. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  341. if(userToken->tokenType != UA_USERTOKENTYPE_ANONYMOUS)
  342. continue;
  343. tokenFound = UA_TRUE;
  344. UA_UserTokenPolicy_copy(userToken, &client->token);
  345. break;
  346. }
  347. }
  348. //cleanup array
  349. UA_Array_delete(endpointArray,endpointArraySize,&UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  350. if(!endpointFound) {
  351. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "No suitable endpoint found");
  352. return UA_STATUSCODE_BADINTERNALERROR;
  353. }
  354. if(!tokenFound) {
  355. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "No anonymous token found");
  356. return UA_STATUSCODE_BADINTERNALERROR;
  357. }
  358. return retval;
  359. }
  360. static UA_StatusCode SessionHandshake(UA_Client *client) {
  361. UA_CreateSessionRequest request;
  362. UA_CreateSessionRequest_init(&request);
  363. // todo: is this needed for all requests?
  364. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  365. request.requestHeader.timestamp = UA_DateTime_now();
  366. request.requestHeader.timeoutHint = 10000;
  367. UA_ByteString_copy(&client->channel.clientNonce, &request.clientNonce);
  368. request.requestedSessionTimeout = 1200000;
  369. request.maxResponseMessageSize = UA_INT32_MAX;
  370. UA_CreateSessionResponse response;
  371. UA_CreateSessionResponse_init(&response);
  372. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  373. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  374. UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  375. UA_CreateSessionRequest_deleteMembers(&request);
  376. UA_CreateSessionResponse_deleteMembers(&response);
  377. return response.responseHeader.serviceResult; // not deleted
  378. }
  379. static UA_StatusCode CloseSession(UA_Client *client) {
  380. UA_CloseSessionRequest request;
  381. UA_CloseSessionRequest_init(&request);
  382. request.requestHeader.timestamp = UA_DateTime_now();
  383. request.requestHeader.timeoutHint = 10000;
  384. request.deleteSubscriptions = UA_TRUE;
  385. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  386. UA_CloseSessionResponse response;
  387. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  388. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  389. UA_CloseSessionRequest_deleteMembers(&request);
  390. UA_CloseSessionResponse_deleteMembers(&response);
  391. return response.responseHeader.serviceResult; // not deleted
  392. }
  393. static UA_StatusCode CloseSecureChannel(UA_Client *client) {
  394. UA_SecureChannel *channel = &client->channel;
  395. UA_CloseSecureChannelRequest request;
  396. UA_CloseSecureChannelRequest_init(&request);
  397. request.requestHeader.requestHandle = 1; //TODO: magic number?
  398. request.requestHeader.timestamp = UA_DateTime_now();
  399. request.requestHeader.timeoutHint = 10000;
  400. request.requestHeader.authenticationToken = client->authenticationToken;
  401. UA_SecureConversationMessageHeader msgHeader;
  402. msgHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_CLOF;
  403. msgHeader.secureChannelId = client->channel.securityToken.channelId;
  404. UA_SymmetricAlgorithmSecurityHeader symHeader;
  405. symHeader.tokenId = channel->securityToken.tokenId;
  406. UA_SequenceHeader seqHeader;
  407. seqHeader.sequenceNumber = ++channel->sequenceNumber;
  408. seqHeader.requestId = ++client->requestId;
  409. UA_NodeId typeId = UA_NODEID_NUMERIC(0, UA_NS0ID_CLOSESECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  410. UA_ByteString message;
  411. UA_Connection *c = &client->connection;
  412. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  413. if(retval != UA_STATUSCODE_GOOD)
  414. return retval;
  415. size_t offset = 12;
  416. retval |= UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symHeader, &message, &offset);
  417. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  418. retval |= UA_NodeId_encodeBinary(&typeId, &message, &offset);
  419. retval |= UA_encodeBinary(&request, &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST], &message, &offset);
  420. msgHeader.messageHeader.messageSize = (UA_UInt32)offset;
  421. offset = 0;
  422. retval |= UA_SecureConversationMessageHeader_encodeBinary(&msgHeader, &message, &offset);
  423. if(retval != UA_STATUSCODE_GOOD) {
  424. client->connection.releaseSendBuffer(&client->connection, &message);
  425. return retval;
  426. }
  427. message.length = msgHeader.messageHeader.messageSize;
  428. retval = client->connection.send(&client->connection, &message);
  429. return retval;
  430. }
  431. UA_StatusCode
  432. UA_Client_getEndpoints(UA_Client *client, UA_ConnectClientConnection connectFunc,
  433. const char *serverUrl, size_t* endpointDescriptionsSize,
  434. UA_EndpointDescription** endpointDescriptions) {
  435. if(client->state == UA_CLIENTSTATE_CONNECTED)
  436. return UA_STATUSCODE_GOOD;
  437. if(client->state == UA_CLIENTSTATE_ERRORED) {
  438. UA_Client_reset(client);
  439. }
  440. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  441. client->connection = connectFunc(UA_ConnectionConfig_standard, serverUrl, client->logger);
  442. if(client->connection.state != UA_CONNECTION_OPENING) {
  443. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  444. goto cleanup;
  445. }
  446. client->endpointUrl = UA_STRING_ALLOC(serverUrl);
  447. if(client->endpointUrl.data == NULL) {
  448. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  449. goto cleanup;
  450. }
  451. client->connection.localConf = client->config.localConnectionConfig;
  452. retval = HelAckHandshake(client);
  453. if(retval == UA_STATUSCODE_GOOD)
  454. retval = SecureChannelHandshake(client, UA_FALSE);
  455. if(retval == UA_STATUSCODE_GOOD)
  456. retval = GetEndpoints(client, endpointDescriptionsSize, endpointDescriptions);
  457. //we always cleanup
  458. cleanup:
  459. UA_Client_reset(client);
  460. return retval;
  461. }
  462. UA_StatusCode UA_Client_connect(UA_Client *client, UA_ConnectClientConnection connectFunc,
  463. const char *endpointUrl) {
  464. if(client->state == UA_CLIENTSTATE_CONNECTED)
  465. return UA_STATUSCODE_GOOD;
  466. if(client->state == UA_CLIENTSTATE_ERRORED) {
  467. UA_Client_reset(client);
  468. }
  469. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  470. client->connection = connectFunc(UA_ConnectionConfig_standard, endpointUrl, client->logger);
  471. if(client->connection.state != UA_CONNECTION_OPENING) {
  472. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  473. goto cleanup;
  474. }
  475. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  476. if(client->endpointUrl.data == NULL) {
  477. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  478. goto cleanup;
  479. }
  480. client->connection.localConf = client->config.localConnectionConfig;
  481. retval = HelAckHandshake(client);
  482. if(retval == UA_STATUSCODE_GOOD)
  483. retval = SecureChannelHandshake(client, UA_FALSE);
  484. if(retval == UA_STATUSCODE_GOOD)
  485. retval = EndpointsHandshake(client);
  486. if(retval == UA_STATUSCODE_GOOD)
  487. retval = SessionHandshake(client);
  488. if(retval == UA_STATUSCODE_GOOD)
  489. retval = ActivateSession(client);
  490. if(retval == UA_STATUSCODE_GOOD) {
  491. client->connection.state = UA_CONNECTION_ESTABLISHED;
  492. client->state = UA_CLIENTSTATE_CONNECTED;
  493. } else {
  494. goto cleanup;
  495. }
  496. return retval;
  497. cleanup:
  498. UA_Client_reset(client);
  499. return retval;
  500. }
  501. UA_StatusCode UA_Client_disconnect(UA_Client *client) {
  502. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  503. //is a session established?
  504. if(client->state == UA_CLIENTSTATE_CONNECTED && client->channel.connection->state == UA_CONNECTION_ESTABLISHED){
  505. retval = CloseSession(client);
  506. }
  507. //is a secure channel established?
  508. if(retval == UA_STATUSCODE_GOOD && client->channel.connection->state == UA_CONNECTION_ESTABLISHED){
  509. retval = CloseSecureChannel(client);
  510. }
  511. return retval;
  512. }
  513. UA_StatusCode UA_Client_manuallyRenewSecureChannel(UA_Client *client) {
  514. return SecureChannelHandshake(client, UA_TRUE);
  515. }
  516. /****************/
  517. /* Raw Services */
  518. /****************/
  519. void __UA_Client_Service(UA_Client *client, const void *r, const UA_DataType *requestType,
  520. void *response, const UA_DataType *responseType) {
  521. /* Requests always begin witih a RequestHeader, therefore we can cast. */
  522. UA_RequestHeader *request = (void*)(uintptr_t)r;
  523. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  524. UA_init(response, responseType);
  525. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  526. /* make sure we have a valid session */
  527. retval = UA_Client_manuallyRenewSecureChannel(client);
  528. if(retval != UA_STATUSCODE_GOOD) {
  529. respHeader->serviceResult = retval;
  530. client->state = UA_CLIENTSTATE_ERRORED;
  531. return;
  532. }
  533. /* handling request parameters */
  534. UA_NodeId_copy(&client->authenticationToken, &request->authenticationToken);
  535. request->timestamp = UA_DateTime_now();
  536. request->requestHandle = ++client->requestHandle;
  537. /* Send the request */
  538. UA_UInt32 requestId = ++client->requestId;
  539. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  540. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  541. retval = UA_SecureChannel_sendBinaryMessage(&client->channel, requestId, request, requestType);
  542. if(retval != UA_STATUSCODE_GOOD) {
  543. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  544. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  545. else
  546. respHeader->serviceResult = retval;
  547. client->state = UA_CLIENTSTATE_ERRORED;
  548. return;
  549. }
  550. /* Retrieve the response */
  551. // Todo: push this into the generic securechannel implementation for client and server
  552. UA_ByteString reply;
  553. UA_ByteString_init(&reply);
  554. UA_Boolean realloced = UA_FALSE;
  555. do {
  556. retval = client->connection.recv(&client->connection, &reply, client->config.timeout);
  557. retval |= UA_Connection_completeMessages(&client->connection, &reply, &realloced);
  558. if(retval != UA_STATUSCODE_GOOD) {
  559. respHeader->serviceResult = retval;
  560. client->state = UA_CLIENTSTATE_ERRORED;
  561. return;
  562. }
  563. } while(!reply.data);
  564. size_t offset = 0;
  565. UA_SecureConversationMessageHeader msgHeader;
  566. retval |= UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &msgHeader);
  567. UA_SymmetricAlgorithmSecurityHeader symHeader;
  568. retval |= UA_SymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &symHeader);
  569. UA_SequenceHeader seqHeader;
  570. retval |= UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  571. UA_NodeId responseId;
  572. retval |= UA_NodeId_decodeBinary(&reply, &offset, &responseId);
  573. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, responseType->typeId.identifier.numeric +
  574. UA_ENCODINGOFFSET_BINARY);
  575. if(retval != UA_STATUSCODE_GOOD)
  576. goto finish;
  577. /* Todo: we need to demux responses since a publish responses may come at any time */
  578. if(!UA_NodeId_equal(&responseId, &expectedNodeId) || seqHeader.requestId != requestId) {
  579. if(responseId.identifier.numeric != UA_NS0ID_SERVICEFAULT + UA_ENCODINGOFFSET_BINARY) {
  580. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT,
  581. "Reply answers the wrong request. Expected ns=%i,i=%i. But retrieved ns=%i,i=%i",
  582. expectedNodeId.namespaceIndex, expectedNodeId.identifier.numeric,
  583. responseId.namespaceIndex, responseId.identifier.numeric);
  584. respHeader->serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  585. } else
  586. retval = UA_decodeBinary(&reply, &offset, respHeader, &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  587. goto finish;
  588. }
  589. retval = UA_decodeBinary(&reply, &offset, response, responseType);
  590. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  591. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  592. finish:
  593. UA_SymmetricAlgorithmSecurityHeader_deleteMembers(&symHeader);
  594. if(!realloced)
  595. client->connection.releaseRecvBuffer(&client->connection, &reply);
  596. else
  597. UA_ByteString_deleteMembers(&reply);
  598. if(retval != UA_STATUSCODE_GOOD){
  599. UA_LOG_INFO(client->logger, UA_LOGCATEGORY_CLIENT, "Error receiving the response");
  600. client->state = UA_CLIENTSTATE_ERRORED;
  601. respHeader->serviceResult = retval;
  602. }
  603. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  604. "Received a response of type %i", responseId.identifier.numeric);
  605. }