ua_client_connect.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  6. * Copyright 2017-2018 (c) Thomas Stalder, Blue Time Concept SA
  7. * Copyright 2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  8. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  9. * Copyright 2018 (c) Kalycito Infotech Private Limited
  10. */
  11. #include "ua_client_internal.h"
  12. #include "ua_transport_generated.h"
  13. #include "ua_transport_generated_handling.h"
  14. #include "ua_transport_generated_encoding_binary.h"
  15. #include "ua_types_encoding_binary.h"
  16. #include "ua_types_generated_encoding_binary.h"
  17. /* Size are refered in bytes */
  18. #define UA_MINMESSAGESIZE 8192
  19. #define UA_SESSION_LOCALNONCELENGTH 32
  20. #define MAX_DATA_SIZE 4096
  21. /********************/
  22. /* Set client state */
  23. /********************/
  24. void
  25. setClientState(UA_Client *client, UA_ClientState state) {
  26. if(client->state != state) {
  27. client->state = state;
  28. if(client->config.stateCallback)
  29. client->config.stateCallback(client, client->state);
  30. }
  31. }
  32. /***********************/
  33. /* Open the Connection */
  34. /***********************/
  35. #define UA_BITMASK_MESSAGETYPE 0x00ffffff
  36. #define UA_BITMASK_CHUNKTYPE 0xff000000
  37. static UA_StatusCode
  38. processACKResponse(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  39. UA_Client *client = (UA_Client*)application;
  40. /* Decode the message */
  41. size_t offset = 0;
  42. UA_StatusCode retval;
  43. UA_TcpMessageHeader messageHeader;
  44. UA_TcpAcknowledgeMessage ackMessage;
  45. retval = UA_TcpMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  46. if(retval != UA_STATUSCODE_GOOD) {
  47. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  48. "Decoding ACK message failed");
  49. return retval;
  50. }
  51. // check if we got an error response from the server
  52. UA_MessageType messageType = (UA_MessageType)
  53. (messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  54. UA_ChunkType chunkType = (UA_ChunkType)
  55. (messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  56. if (messageType == UA_MESSAGETYPE_ERR) {
  57. // Header + ErrorMessage (error + reasonLength_field + length)
  58. UA_StatusCode error = *(UA_StatusCode*)(&chunk->data[offset]);
  59. UA_UInt32 len = *((UA_UInt32*)&chunk->data[offset + 4]);
  60. UA_Byte *data = (UA_Byte*)&chunk->data[offset + 4+4];
  61. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  62. "Received ERR response. %s - %.*s", UA_StatusCode_name(error), len, data);
  63. return error;
  64. }
  65. if (chunkType != UA_CHUNKTYPE_FINAL) {
  66. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  67. }
  68. /* Decode the ACK message */
  69. retval = UA_TcpAcknowledgeMessage_decodeBinary(chunk, &offset, &ackMessage);
  70. if(retval != UA_STATUSCODE_GOOD) {
  71. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  72. "Decoding ACK message failed");
  73. return retval;
  74. }
  75. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  76. /* Process the ACK message */
  77. return UA_Connection_processHELACK(connection, &client->config.localConnectionConfig,
  78. (const UA_ConnectionConfig*)&ackMessage);
  79. }
  80. static UA_StatusCode
  81. HelAckHandshake(UA_Client *client, const UA_String endpointUrl) {
  82. /* Get a buffer */
  83. UA_ByteString message;
  84. UA_Connection *conn = &client->connection;
  85. UA_StatusCode retval = conn->getSendBuffer(conn, UA_MINMESSAGESIZE, &message);
  86. if(retval != UA_STATUSCODE_GOOD)
  87. return retval;
  88. /* Prepare the HEL message and encode at offset 8 */
  89. UA_TcpHelloMessage hello;
  90. UA_String_copy(&endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  91. memcpy(&hello, &client->config.localConnectionConfig, sizeof(UA_ConnectionConfig)); /* same struct layout */
  92. UA_Byte *bufPos = &message.data[8]; /* skip the header */
  93. const UA_Byte *bufEnd = &message.data[message.length];
  94. retval = UA_TcpHelloMessage_encodeBinary(&hello, &bufPos, bufEnd);
  95. UA_TcpHelloMessage_deleteMembers(&hello);
  96. if(retval != UA_STATUSCODE_GOOD) {
  97. conn->releaseSendBuffer(conn, &message);
  98. return retval;
  99. }
  100. /* Encode the message header at offset 0 */
  101. UA_TcpMessageHeader messageHeader;
  102. messageHeader.messageTypeAndChunkType = UA_CHUNKTYPE_FINAL + UA_MESSAGETYPE_HEL;
  103. messageHeader.messageSize = (UA_UInt32)((uintptr_t)bufPos - (uintptr_t)message.data);
  104. bufPos = message.data;
  105. retval = UA_TcpMessageHeader_encodeBinary(&messageHeader, &bufPos, bufEnd);
  106. if(retval != UA_STATUSCODE_GOOD) {
  107. conn->releaseSendBuffer(conn, &message);
  108. return retval;
  109. }
  110. /* Send the HEL message */
  111. message.length = messageHeader.messageSize;
  112. retval = conn->send(conn, &message);
  113. if(retval != UA_STATUSCODE_GOOD) {
  114. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  115. "Sending HEL failed");
  116. return retval;
  117. }
  118. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  119. "Sent HEL message");
  120. /* Loop until we have a complete chunk */
  121. retval = UA_Connection_receiveChunksBlocking(conn, client, processACKResponse,
  122. client->config.timeout);
  123. if(retval != UA_STATUSCODE_GOOD) {
  124. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  125. "Receiving ACK message failed with %s", UA_StatusCode_name(retval));
  126. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  127. client->state = UA_CLIENTSTATE_DISCONNECTED;
  128. UA_Client_disconnect(client);
  129. }
  130. return retval;
  131. }
  132. UA_SecurityPolicy *
  133. getSecurityPolicy(UA_Client *client, UA_String policyUri) {
  134. for(size_t i = 0; i < client->config.securityPoliciesSize; i++) {
  135. if(UA_String_equal(&policyUri, &client->config.securityPolicies[i].policyUri))
  136. return &client->config.securityPolicies[i];
  137. }
  138. return NULL;
  139. }
  140. static void
  141. processDecodedOPNResponse(UA_Client *client, UA_OpenSecureChannelResponse *response, UA_Boolean renew) {
  142. /* Replace the token */
  143. if (renew)
  144. client->channel.nextSecurityToken = response->securityToken; // Set the next token
  145. else
  146. client->channel.securityToken = response->securityToken; // Set initial token
  147. /* Replace the nonce */
  148. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  149. client->channel.remoteNonce = response->serverNonce;
  150. UA_ByteString_init(&response->serverNonce);
  151. if(client->channel.state == UA_SECURECHANNELSTATE_OPEN)
  152. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  153. "SecureChannel in the server renewed");
  154. else
  155. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  156. "Opened SecureChannel acknowledged by the server");
  157. /* Response.securityToken.revisedLifetime is UInt32 we need to cast it to
  158. * DateTime=Int64 we take 75% of lifetime to start renewing as described in
  159. * standard */
  160. client->channel.state = UA_SECURECHANNELSTATE_OPEN;
  161. client->nextChannelRenewal = UA_DateTime_nowMonotonic() + (UA_DateTime)
  162. (client->channel.securityToken.revisedLifetime * (UA_Double)UA_DATETIME_MSEC * 0.75);
  163. }
  164. UA_StatusCode
  165. openSecureChannel(UA_Client *client, UA_Boolean renew) {
  166. /* Check if sc is still valid */
  167. if(renew && client->nextChannelRenewal > UA_DateTime_nowMonotonic())
  168. return UA_STATUSCODE_GOOD;
  169. UA_Connection *conn = &client->connection;
  170. if(conn->state != UA_CONNECTION_ESTABLISHED)
  171. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  172. /* Prepare the OpenSecureChannelRequest */
  173. UA_OpenSecureChannelRequest opnSecRq;
  174. UA_OpenSecureChannelRequest_init(&opnSecRq);
  175. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  176. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  177. if(renew) {
  178. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  179. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  180. "Requesting to renew the SecureChannel");
  181. } else {
  182. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  183. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  184. "Requesting to open a SecureChannel");
  185. }
  186. /* Set the securityMode to input securityMode from client data */
  187. opnSecRq.securityMode = client->channel.securityMode;
  188. opnSecRq.clientNonce = client->channel.localNonce;
  189. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  190. /* Send the OPN message */
  191. UA_UInt32 requestId = ++client->requestId;
  192. UA_StatusCode retval =
  193. UA_SecureChannel_sendAsymmetricOPNMessage(&client->channel, requestId, &opnSecRq,
  194. &UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST]);
  195. if(retval != UA_STATUSCODE_GOOD) {
  196. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  197. "Sending OPN message failed with error %s", UA_StatusCode_name(retval));
  198. UA_Client_disconnect(client);
  199. return retval;
  200. }
  201. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "OPN message sent");
  202. /* Increase nextChannelRenewal to avoid that we re-start renewal when
  203. * publish responses are received before the OPN response arrives. */
  204. client->nextChannelRenewal = UA_DateTime_nowMonotonic() +
  205. (2 * ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC));
  206. /* Receive / decrypt / decode the OPN response. Process async services in
  207. * the background until the OPN response arrives. */
  208. UA_OpenSecureChannelResponse response;
  209. retval = receiveServiceResponse(client, &response,
  210. &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE],
  211. UA_DateTime_nowMonotonic() +
  212. ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC),
  213. &requestId);
  214. if(retval != UA_STATUSCODE_GOOD) {
  215. UA_Client_disconnect(client);
  216. return retval;
  217. }
  218. processDecodedOPNResponse(client, &response, renew);
  219. UA_OpenSecureChannelResponse_deleteMembers(&response);
  220. return retval;
  221. }
  222. /* Function to verify the signature corresponds to ClientNonce
  223. * using the local certificate.
  224. *
  225. * @param channel current channel in which the client runs
  226. * @param response create session response from the server
  227. * @return Returns an error code or UA_STATUSCODE_GOOD. */
  228. UA_StatusCode
  229. checkClientSignature(const UA_SecureChannel *channel, const UA_CreateSessionResponse *response) {
  230. if(channel == NULL || response == NULL)
  231. return UA_STATUSCODE_BADINTERNALERROR;
  232. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  233. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  234. return UA_STATUSCODE_GOOD;
  235. if(!channel->securityPolicy)
  236. return UA_STATUSCODE_BADINTERNALERROR;
  237. const UA_SecurityPolicy* securityPolicy = channel->securityPolicy;
  238. const UA_ByteString* localCertificate = &securityPolicy->localCertificate;
  239. size_t dataToVerifySize = localCertificate->length + channel->localNonce.length;
  240. UA_ByteString dataToVerify = UA_BYTESTRING_NULL;
  241. UA_StatusCode retval = UA_ByteString_allocBuffer(&dataToVerify, dataToVerifySize);
  242. if(retval != UA_STATUSCODE_GOOD)
  243. return retval;
  244. memcpy(dataToVerify.data, localCertificate->data, localCertificate->length);
  245. memcpy(dataToVerify.data + localCertificate->length,
  246. channel->localNonce.data, channel->localNonce.length);
  247. retval = securityPolicy->
  248. certificateSigningAlgorithm.verify(securityPolicy,
  249. channel->channelContext,
  250. &dataToVerify,
  251. &response->serverSignature.signature);
  252. UA_ByteString_deleteMembers(&dataToVerify);
  253. return retval;
  254. }
  255. /* Function to create a signature using remote certificate and nonce
  256. *
  257. * @param channel current channel in which the client runs
  258. * @param request activate session request message to server
  259. * @return Returns an error or UA_STATUSCODE_GOOD */
  260. UA_StatusCode
  261. signActivateSessionRequest(UA_SecureChannel *channel,
  262. UA_ActivateSessionRequest *request) {
  263. if(channel == NULL || request == NULL)
  264. return UA_STATUSCODE_BADINTERNALERROR;
  265. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  266. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  267. return UA_STATUSCODE_GOOD;
  268. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  269. UA_SignatureData *signatureData = &request->clientSignature;
  270. /* Prepare the signature */
  271. size_t signatureSize = securityPolicy->certificateSigningAlgorithm.
  272. getLocalSignatureSize(securityPolicy, channel->channelContext);
  273. UA_StatusCode retval = UA_String_copy(&securityPolicy->certificateSigningAlgorithm.uri,
  274. &signatureData->algorithm);
  275. if(retval != UA_STATUSCODE_GOOD)
  276. return retval;
  277. retval = UA_ByteString_allocBuffer(&signatureData->signature, signatureSize);
  278. if(retval != UA_STATUSCODE_GOOD)
  279. return retval;
  280. /* Allocate a temporary buffer */
  281. size_t dataToSignSize = channel->remoteCertificate.length + channel->remoteNonce.length;
  282. /* Prevent stack-smashing. TODO: Compute MaxSenderCertificateSize */
  283. if(dataToSignSize > MAX_DATA_SIZE)
  284. return UA_STATUSCODE_BADINTERNALERROR;
  285. UA_ByteString dataToSign;
  286. retval = UA_ByteString_allocBuffer(&dataToSign, dataToSignSize);
  287. if(retval != UA_STATUSCODE_GOOD)
  288. return retval; /* signatureData->signature is cleaned up with the response */
  289. /* Sign the signature */
  290. memcpy(dataToSign.data, channel->remoteCertificate.data, channel->remoteCertificate.length);
  291. memcpy(dataToSign.data + channel->remoteCertificate.length,
  292. channel->remoteNonce.data, channel->remoteNonce.length);
  293. retval = securityPolicy->certificateSigningAlgorithm.
  294. sign(securityPolicy, channel->channelContext, &dataToSign,
  295. &signatureData->signature);
  296. /* Clean up */
  297. UA_ByteString_deleteMembers(&dataToSign);
  298. return retval;
  299. }
  300. UA_StatusCode
  301. encryptUserIdentityToken(UA_Client *client, const UA_String *userTokenSecurityPolicy,
  302. UA_ExtensionObject *userIdentityToken) {
  303. UA_IssuedIdentityToken *iit = NULL;
  304. UA_UserNameIdentityToken *unit = NULL;
  305. UA_ByteString *tokenData;
  306. if(userIdentityToken->content.decoded.type == &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]) {
  307. iit = (UA_IssuedIdentityToken*)userIdentityToken->content.decoded.data;
  308. tokenData = &iit->tokenData;
  309. } else if(userIdentityToken->content.decoded.type == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) {
  310. unit = (UA_UserNameIdentityToken*)userIdentityToken->content.decoded.data;
  311. tokenData = &unit->password;
  312. } else {
  313. return UA_STATUSCODE_GOOD;
  314. }
  315. /* No encryption */
  316. const UA_String none = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  317. if(userTokenSecurityPolicy->length == 0 ||
  318. UA_String_equal(userTokenSecurityPolicy, &none)) {
  319. return UA_STATUSCODE_GOOD;
  320. }
  321. UA_SecurityPolicy *sp = getSecurityPolicy(client, *userTokenSecurityPolicy);
  322. if(!sp) {
  323. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  324. "Could not find the required SecurityPolicy for the UserToken");
  325. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  326. }
  327. /* Create a temp channel context */
  328. void *channelContext;
  329. UA_StatusCode retval = sp->channelModule.
  330. newContext(sp, &client->config.endpoint.serverCertificate, &channelContext);
  331. if(retval != UA_STATUSCODE_GOOD) {
  332. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  333. "Could not instantiate the SecurityPolicy for the UserToken");
  334. return UA_STATUSCODE_BADINTERNALERROR;
  335. }
  336. /* Compute the encrypted length (at least one byte padding) */
  337. size_t plainTextBlockSize = sp->asymmetricModule.cryptoModule.
  338. encryptionAlgorithm.getRemotePlainTextBlockSize(sp, channelContext);
  339. UA_UInt32 length = (UA_UInt32)(tokenData->length + client->channel.remoteNonce.length);
  340. UA_UInt32 totalLength = length + 4; /* Including the length field */
  341. size_t blocks = totalLength / plainTextBlockSize;
  342. if(totalLength % plainTextBlockSize != 0)
  343. blocks++;
  344. size_t overHead =
  345. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(sp, channelContext,
  346. blocks * plainTextBlockSize);
  347. /* Allocate memory for encryption overhead */
  348. UA_ByteString encrypted;
  349. retval = UA_ByteString_allocBuffer(&encrypted, (blocks * plainTextBlockSize) + overHead);
  350. if(retval != UA_STATUSCODE_GOOD) {
  351. sp->channelModule.deleteContext(channelContext);
  352. return UA_STATUSCODE_BADOUTOFMEMORY;
  353. }
  354. UA_Byte *pos = encrypted.data;
  355. const UA_Byte *end = &encrypted.data[encrypted.length];
  356. UA_UInt32_encodeBinary(&length, &pos, end);
  357. memcpy(pos, tokenData->data, tokenData->length);
  358. memcpy(&pos[tokenData->length], client->channel.remoteNonce.data,
  359. client->channel.remoteNonce.length);
  360. /* Add padding
  361. *
  362. * 7.36.2.2 Legacy Encrypted Token Secret Format: A Client should not add any
  363. * padding after the secret. If a Client adds padding then all bytes shall
  364. * be zero. A Server shall check for padding added by Clients and ensure
  365. * that all padding bytes are zeros. */
  366. size_t paddedLength = plainTextBlockSize * blocks;
  367. for(size_t i = totalLength; i < paddedLength; i++)
  368. encrypted.data[i] = 0;
  369. encrypted.length = paddedLength;
  370. retval = sp->asymmetricModule.cryptoModule.encryptionAlgorithm.encrypt(sp, channelContext,
  371. &encrypted);
  372. encrypted.length = (blocks * plainTextBlockSize) + overHead;
  373. if(iit) {
  374. retval |= UA_String_copy(&sp->asymmetricModule.cryptoModule.encryptionAlgorithm.uri,
  375. &iit->encryptionAlgorithm);
  376. } else {
  377. retval |= UA_String_copy(&sp->asymmetricModule.cryptoModule.encryptionAlgorithm.uri,
  378. &unit->encryptionAlgorithm);
  379. }
  380. UA_ByteString_deleteMembers(tokenData);
  381. *tokenData = encrypted;
  382. /* Delete the temp channel context */
  383. sp->channelModule.deleteContext(channelContext);
  384. return retval;
  385. }
  386. static UA_StatusCode
  387. activateSession(UA_Client *client) {
  388. UA_ActivateSessionRequest request;
  389. UA_ActivateSessionRequest_init(&request);
  390. request.requestHeader.requestHandle = ++client->requestHandle;
  391. request.requestHeader.timestamp = UA_DateTime_now();
  392. request.requestHeader.timeoutHint = 600000;
  393. UA_StatusCode retval =
  394. UA_ExtensionObject_copy(&client->config.userIdentityToken, &request.userIdentityToken);
  395. if(retval != UA_STATUSCODE_GOOD)
  396. return retval;
  397. /* If not token is set, use anonymous */
  398. if(request.userIdentityToken.encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
  399. UA_AnonymousIdentityToken *t = UA_AnonymousIdentityToken_new();
  400. if(!t) {
  401. UA_ActivateSessionRequest_deleteMembers(&request);
  402. return UA_STATUSCODE_BADOUTOFMEMORY;
  403. }
  404. request.userIdentityToken.content.decoded.data = t;
  405. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  406. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  407. }
  408. /* Set the policy-Id from the endpoint. Every IdentityToken starts with a
  409. * string. */
  410. retval |= UA_String_copy(&client->config.userTokenPolicy.policyId,
  411. (UA_String*)request.userIdentityToken.content.decoded.data);
  412. /* Encrypt the UserIdentityToken */
  413. const UA_String *userTokenPolicy = &client->channel.securityPolicy->policyUri;
  414. if(client->config.userTokenPolicy.securityPolicyUri.length > 0)
  415. userTokenPolicy = &client->config.userTokenPolicy.securityPolicyUri;
  416. retval |= encryptUserIdentityToken(client, userTokenPolicy, &request.userIdentityToken);
  417. if(retval != UA_STATUSCODE_GOOD) {
  418. UA_ActivateSessionRequest_deleteMembers(&request);
  419. return retval;
  420. }
  421. /* This function call is to prepare a client signature */
  422. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  423. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  424. signActivateSessionRequest(&client->channel, &request);
  425. }
  426. UA_ActivateSessionResponse response;
  427. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  428. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  429. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  430. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  431. "ActivateSession failed with error code %s",
  432. UA_StatusCode_name(response.responseHeader.serviceResult));
  433. }
  434. retval = response.responseHeader.serviceResult;
  435. UA_ActivateSessionRequest_deleteMembers(&request);
  436. UA_ActivateSessionResponse_deleteMembers(&response);
  437. return retval;
  438. }
  439. /* Gets a list of endpoints. Memory is allocated for endpointDescription array */
  440. UA_StatusCode
  441. UA_Client_getEndpointsInternal(UA_Client *client, const UA_String endpointUrl,
  442. size_t *endpointDescriptionsSize,
  443. UA_EndpointDescription **endpointDescriptions) {
  444. UA_GetEndpointsRequest request;
  445. UA_GetEndpointsRequest_init(&request);
  446. request.requestHeader.timestamp = UA_DateTime_now();
  447. request.requestHeader.timeoutHint = 10000;
  448. // assume the endpointurl outlives the service call
  449. request.endpointUrl = endpointUrl;
  450. UA_GetEndpointsResponse response;
  451. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  452. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  453. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  454. UA_StatusCode retval = response.responseHeader.serviceResult;
  455. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  456. "GetEndpointRequest failed with error code %s",
  457. UA_StatusCode_name(retval));
  458. UA_GetEndpointsResponse_deleteMembers(&response);
  459. return retval;
  460. }
  461. *endpointDescriptions = response.endpoints;
  462. *endpointDescriptionsSize = response.endpointsSize;
  463. response.endpoints = NULL;
  464. response.endpointsSize = 0;
  465. UA_GetEndpointsResponse_deleteMembers(&response);
  466. return UA_STATUSCODE_GOOD;
  467. }
  468. static UA_StatusCode
  469. selectEndpoint(UA_Client *client, const UA_String endpointUrl) {
  470. UA_EndpointDescription* endpointArray = NULL;
  471. size_t endpointArraySize = 0;
  472. UA_StatusCode retval =
  473. UA_Client_getEndpointsInternal(client, endpointUrl, &endpointArraySize, &endpointArray);
  474. if(retval != UA_STATUSCODE_GOOD)
  475. return retval;
  476. UA_Boolean endpointFound = false;
  477. UA_Boolean tokenFound = false;
  478. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  479. "Transport/uatcp-uasc-uabinary");
  480. for(size_t i = 0; i < endpointArraySize; ++i) {
  481. UA_EndpointDescription* endpoint = &endpointArray[i];
  482. /* Match Binary TransportProfile?
  483. * Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  484. if(endpoint->transportProfileUri.length != 0 &&
  485. !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  486. continue;
  487. /* Valid SecurityMode? */
  488. if(endpoint->securityMode < 1 || endpoint->securityMode > 3)
  489. continue;
  490. /* Selected SecurityMode? */
  491. if(client->config.securityMode > 0 &&
  492. client->config.securityMode != endpoint->securityMode)
  493. continue;
  494. /* Matching SecurityPolicy? */
  495. if(client->config.securityPolicyUri.length > 0 &&
  496. !UA_String_equal(&client->config.securityPolicyUri,
  497. &endpoint->securityPolicyUri))
  498. continue;
  499. /* SecurityPolicy available? */
  500. if(!getSecurityPolicy(client, endpoint->securityPolicyUri))
  501. continue;
  502. endpointFound = true;
  503. /* Select a matching UserTokenPolicy inside the endpoint */
  504. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  505. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  506. /* Usertokens also have a security policy... */
  507. if(userToken->securityPolicyUri.length > 0 &&
  508. !getSecurityPolicy(client, userToken->securityPolicyUri))
  509. continue;
  510. if(userToken->tokenType > 3)
  511. continue;
  512. /* Does the token type match the client configuration? */
  513. if((userToken->tokenType == UA_USERTOKENTYPE_ANONYMOUS &&
  514. client->config.userIdentityToken.content.decoded.type !=
  515. &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN] &&
  516. client->config.userIdentityToken.content.decoded.type != NULL) ||
  517. (userToken->tokenType == UA_USERTOKENTYPE_USERNAME &&
  518. client->config.userIdentityToken.content.decoded.type !=
  519. &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) ||
  520. (userToken->tokenType == UA_USERTOKENTYPE_CERTIFICATE &&
  521. client->config.userIdentityToken.content.decoded.type !=
  522. &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN]) ||
  523. (userToken->tokenType == UA_USERTOKENTYPE_ISSUEDTOKEN &&
  524. client->config.userIdentityToken.content.decoded.type !=
  525. &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]))
  526. continue;
  527. /* Endpoint with matching UserTokenPolicy found. Copy to the
  528. * configuration. */
  529. tokenFound = true;
  530. UA_EndpointDescription_deleteMembers(&client->config.endpoint);
  531. UA_EndpointDescription temp = *endpoint;
  532. temp.userIdentityTokensSize = 0;
  533. temp.userIdentityTokens = NULL;
  534. retval = UA_EndpointDescription_copy(&temp, &client->config.endpoint);
  535. UA_UserTokenPolicy_deleteMembers(&client->config.userTokenPolicy);
  536. retval |= UA_UserTokenPolicy_copy(userToken, &client->config.userTokenPolicy);
  537. if(retval != UA_STATUSCODE_GOOD)
  538. break;
  539. #if UA_LOGLEVEL <= 300
  540. const char *securityModeNames[3] = {"None", "Sign", "SignAndEncrypt"};
  541. const char *userTokenTypeNames[4] = {"Anonymous", "UserName",
  542. "Certificate", "IssuedToken"};
  543. UA_String *securityPolicyUri = &userToken->securityPolicyUri;
  544. if(securityPolicyUri->length == 0)
  545. securityPolicyUri = &endpoint->securityPolicyUri;
  546. #endif
  547. /* Log the selected endpoint */
  548. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  549. "Selected Endpoint %.*s with SecurityMode %s and SecurityPolicy %.*s",
  550. (int)endpoint->endpointUrl.length, endpoint->endpointUrl.data,
  551. securityModeNames[endpoint->securityMode - 1],
  552. (int)endpoint->securityPolicyUri.length,
  553. endpoint->securityPolicyUri.data);
  554. /* Log the selected UserTokenPolicy */
  555. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  556. "Selected UserTokenPolicy %.*s with UserTokenType %s and SecurityPolicy %.*s",
  557. (int)userToken->policyId.length, userToken->policyId.data,
  558. userTokenTypeNames[userToken->tokenType],
  559. (int)securityPolicyUri->length, securityPolicyUri->data);
  560. break;
  561. }
  562. if(tokenFound)
  563. break;
  564. }
  565. UA_Array_delete(endpointArray, endpointArraySize,
  566. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  567. if(retval != UA_STATUSCODE_GOOD)
  568. return retval;
  569. if(!endpointFound) {
  570. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  571. "No suitable endpoint found");
  572. retval = UA_STATUSCODE_BADINTERNALERROR;
  573. } else if(!tokenFound) {
  574. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  575. "No suitable UserTokenPolicy found for the possible endpoints");
  576. retval = UA_STATUSCODE_BADINTERNALERROR;
  577. }
  578. return retval;
  579. }
  580. static UA_StatusCode
  581. createSession(UA_Client *client) {
  582. UA_CreateSessionRequest request;
  583. UA_CreateSessionRequest_init(&request);
  584. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  585. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  586. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  587. if(client->channel.localNonce.length != UA_SESSION_LOCALNONCELENGTH) {
  588. UA_ByteString_deleteMembers(&client->channel.localNonce);
  589. retval = UA_ByteString_allocBuffer(&client->channel.localNonce,
  590. UA_SESSION_LOCALNONCELENGTH);
  591. if(retval != UA_STATUSCODE_GOOD)
  592. return retval;
  593. }
  594. retval = client->channel.securityPolicy->symmetricModule.
  595. generateNonce(client->channel.securityPolicy, &client->channel.localNonce);
  596. if(retval != UA_STATUSCODE_GOOD)
  597. return retval;
  598. }
  599. request.requestHeader.timestamp = UA_DateTime_now();
  600. request.requestHeader.timeoutHint = 10000;
  601. UA_ByteString_copy(&client->channel.localNonce, &request.clientNonce);
  602. request.requestedSessionTimeout = client->config.requestedSessionTimeout;
  603. request.maxResponseMessageSize = UA_INT32_MAX;
  604. UA_String_copy(&client->config.endpoint.endpointUrl, &request.endpointUrl);
  605. UA_ApplicationDescription_copy(&client->config.clientDescription,
  606. &request.clientDescription);
  607. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  608. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  609. UA_ByteString_copy(&client->channel.securityPolicy->localCertificate,
  610. &request.clientCertificate);
  611. }
  612. UA_CreateSessionResponse response;
  613. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  614. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  615. if(response.responseHeader.serviceResult == UA_STATUSCODE_GOOD &&
  616. (client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  617. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)) {
  618. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  619. UA_ByteString_copy(&response.serverNonce, &client->channel.remoteNonce);
  620. if(!UA_ByteString_equal(&response.serverCertificate,
  621. &client->channel.remoteCertificate)) {
  622. return UA_STATUSCODE_BADCERTIFICATEINVALID;
  623. }
  624. /* Verify the client signature */
  625. retval = checkClientSignature(&client->channel, &response);
  626. if(retval != UA_STATUSCODE_GOOD)
  627. return retval;
  628. }
  629. UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  630. retval = response.responseHeader.serviceResult;
  631. UA_CreateSessionRequest_deleteMembers(&request);
  632. UA_CreateSessionResponse_deleteMembers(&response);
  633. return retval;
  634. }
  635. UA_StatusCode
  636. UA_Client_connectTCPSecureChannel(UA_Client *client, const UA_String endpointUrl) {
  637. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  638. return UA_STATUSCODE_GOOD;
  639. UA_ChannelSecurityToken_init(&client->channel.securityToken);
  640. client->channel.state = UA_SECURECHANNELSTATE_FRESH;
  641. client->channel.sendSequenceNumber = 0;
  642. client->requestId = 0;
  643. /* Set the channel SecurityMode */
  644. client->channel.securityMode = client->config.endpoint.securityMode;
  645. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  646. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  647. /* Initialized the SecureChannel */
  648. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  649. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  650. "Initialize the SecurityPolicy context");
  651. if(!client->channel.securityPolicy) {
  652. /* Set the channel SecurityPolicy to #None if no endpoint is selected */
  653. UA_String sps = client->config.endpoint.securityPolicyUri;
  654. if(client->config.endpoint.securityPolicyUri.length == 0)
  655. sps = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  656. UA_SecurityPolicy *sp = getSecurityPolicy(client, sps);
  657. if(!sp) {
  658. retval = UA_STATUSCODE_BADINTERNALERROR;
  659. goto cleanup;
  660. }
  661. retval =
  662. UA_SecureChannel_setSecurityPolicy(&client->channel, sp,
  663. &client->config.endpoint.serverCertificate);
  664. if(retval != UA_STATUSCODE_GOOD)
  665. goto cleanup;
  666. }
  667. /* Open a TCP connection */
  668. client->connection = client->config.connectionFunc(client->config.localConnectionConfig,
  669. endpointUrl, client->config.timeout,
  670. &client->config.logger);
  671. if(client->connection.state != UA_CONNECTION_OPENING) {
  672. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  673. "Opening the TCP socket failed");
  674. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  675. goto cleanup;
  676. }
  677. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  678. "TCP connection established");
  679. /* Perform the HEL/ACK handshake */
  680. client->connection.config = client->config.localConnectionConfig;
  681. retval = HelAckHandshake(client, endpointUrl);
  682. if(retval != UA_STATUSCODE_GOOD)
  683. goto cleanup;
  684. setClientState(client, UA_CLIENTSTATE_CONNECTED);
  685. /* Open a SecureChannel. */
  686. retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  687. if(retval != UA_STATUSCODE_GOOD)
  688. goto cleanup;
  689. client->channel.connection = &client->connection;
  690. retval = openSecureChannel(client, false);
  691. if(retval != UA_STATUSCODE_GOOD)
  692. goto cleanup;
  693. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  694. if(retval != UA_STATUSCODE_GOOD)
  695. return retval;
  696. setClientState(client, UA_CLIENTSTATE_SECURECHANNEL);
  697. return retval;
  698. cleanup:
  699. UA_Client_disconnect(client);
  700. return retval;
  701. }
  702. UA_StatusCode
  703. UA_Client_connectSession(UA_Client *client) {
  704. if(client->state < UA_CLIENTSTATE_SECURECHANNEL)
  705. return UA_STATUSCODE_BADINTERNALERROR;
  706. /* Delete async service. TODO: Move this from connect to the disconnect/cleanup phase */
  707. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  708. // TODO: actually, reactivate an existing session is working, but currently
  709. // republish is not implemented This option is disabled until we have a good
  710. // implementation of the subscription recovery.
  711. #ifdef UA_SESSION_RECOVERY
  712. /* Try to activate an existing Session for this SecureChannel */
  713. if((!UA_NodeId_equal(&client->authenticationToken, &UA_NODEID_NULL)) && (createNewSession)) {
  714. UA_StatusCode res = activateSession(client);
  715. if(res != UA_STATUSCODE_BADSESSIONIDINVALID) {
  716. if(res == UA_STATUSCODE_GOOD)
  717. setClientState(client, UA_CLIENTSTATE_SESSION_RENEWED);
  718. else
  719. UA_Client_disconnect(client);
  720. return res;
  721. }
  722. }
  723. #endif /* UA_SESSION_RECOVERY */
  724. /* Could not recover an old session. Remove authenticationToken */
  725. UA_NodeId_deleteMembers(&client->authenticationToken);
  726. /* Create a session */
  727. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Create a new session");
  728. UA_StatusCode retval = createSession(client);
  729. if(retval != UA_STATUSCODE_GOOD) {
  730. UA_Client_disconnect(client);
  731. return retval;
  732. }
  733. /* A new session has been created. We need to clean up the subscriptions */
  734. #ifdef UA_ENABLE_SUBSCRIPTIONS
  735. UA_Client_Subscriptions_clean(client);
  736. client->currentlyOutStandingPublishRequests = 0;
  737. #endif
  738. /* Activate the session */
  739. retval = activateSession(client);
  740. if(retval != UA_STATUSCODE_GOOD) {
  741. UA_Client_disconnect(client);
  742. return retval;
  743. }
  744. setClientState(client, UA_CLIENTSTATE_SESSION);
  745. return retval;
  746. }
  747. UA_StatusCode
  748. UA_Client_connectInternal(UA_Client *client, const UA_String endpointUrl) {
  749. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  750. return UA_STATUSCODE_GOOD;
  751. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  752. "Connecting to endpoint %.*s", (int)endpointUrl.length,
  753. endpointUrl.data);
  754. /* Get endpoints only if the description has not been touched (memset to
  755. * zero) */
  756. UA_Byte test = 0;
  757. UA_Byte *pos = (UA_Byte*)&client->config.endpoint;
  758. for(size_t i = 0; i < sizeof(UA_EndpointDescription); i++)
  759. test = test | pos[i];
  760. pos = (UA_Byte*)&client->config.userTokenPolicy;
  761. for(size_t i = 0; i < sizeof(UA_UserTokenPolicy); i++)
  762. test = test | pos[i];
  763. UA_Boolean getEndpoints = (test == 0);
  764. /* Connect up to the SecureChannel */
  765. UA_StatusCode retval = UA_Client_connectTCPSecureChannel(client, endpointUrl);
  766. if(retval != UA_STATUSCODE_GOOD)
  767. goto cleanup;
  768. /* Get and select endpoints if required */
  769. if(getEndpoints) {
  770. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  771. "Endpoint and UserTokenPolicy unconfigured, perform GetEndpoints");
  772. retval = selectEndpoint(client, endpointUrl);
  773. if(retval != UA_STATUSCODE_GOOD)
  774. goto cleanup;
  775. /* Reconnect with a new SecureChannel if the current one does not match
  776. * the selected endpoint */
  777. if(!UA_String_equal(&client->config.endpoint.securityPolicyUri,
  778. &client->channel.securityPolicy->policyUri)) {
  779. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  780. "Disconnect to switch to a different SecurityPolicy");
  781. UA_Client_disconnect(client);
  782. return UA_Client_connectInternal(client, endpointUrl);
  783. }
  784. }
  785. retval = UA_Client_connectSession(client);
  786. if(retval != UA_STATUSCODE_GOOD)
  787. goto cleanup;
  788. return retval;
  789. cleanup:
  790. UA_Client_disconnect(client);
  791. return retval;
  792. }
  793. UA_StatusCode
  794. UA_Client_connect(UA_Client *client, const char *endpointUrl) {
  795. return UA_Client_connectInternal(client, UA_STRING((char*)(uintptr_t)endpointUrl));
  796. }
  797. UA_StatusCode
  798. UA_Client_connect_noSession(UA_Client *client, const char *endpointUrl) {
  799. return UA_Client_connectTCPSecureChannel(client, UA_STRING((char*)(uintptr_t)endpointUrl));
  800. }
  801. UA_StatusCode
  802. UA_Client_connect_username(UA_Client *client, const char *endpointUrl,
  803. const char *username, const char *password) {
  804. UA_UserNameIdentityToken* identityToken = UA_UserNameIdentityToken_new();
  805. if(!identityToken)
  806. return UA_STATUSCODE_BADOUTOFMEMORY;
  807. identityToken->userName = UA_STRING_ALLOC(username);
  808. identityToken->password = UA_STRING_ALLOC(password);
  809. UA_ExtensionObject_deleteMembers(&client->config.userIdentityToken);
  810. client->config.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  811. client->config.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  812. client->config.userIdentityToken.content.decoded.data = identityToken;
  813. return UA_Client_connect(client, endpointUrl);
  814. }
  815. /************************/
  816. /* Close the Connection */
  817. /************************/
  818. static void
  819. sendCloseSession(UA_Client *client) {
  820. UA_CloseSessionRequest request;
  821. UA_CloseSessionRequest_init(&request);
  822. request.requestHeader.timestamp = UA_DateTime_now();
  823. request.requestHeader.timeoutHint = 10000;
  824. request.deleteSubscriptions = true;
  825. UA_CloseSessionResponse response;
  826. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  827. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  828. UA_CloseSessionRequest_deleteMembers(&request);
  829. UA_CloseSessionResponse_deleteMembers(&response);
  830. }
  831. static void
  832. sendCloseSecureChannel(UA_Client *client) {
  833. UA_SecureChannel *channel = &client->channel;
  834. UA_CloseSecureChannelRequest request;
  835. UA_CloseSecureChannelRequest_init(&request);
  836. request.requestHeader.requestHandle = ++client->requestHandle;
  837. request.requestHeader.timestamp = UA_DateTime_now();
  838. request.requestHeader.timeoutHint = 10000;
  839. request.requestHeader.authenticationToken = client->authenticationToken;
  840. UA_SecureChannel_sendSymmetricMessage(channel, ++client->requestId,
  841. UA_MESSAGETYPE_CLO, &request,
  842. &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
  843. UA_CloseSecureChannelRequest_deleteMembers(&request);
  844. UA_SecureChannel_close(&client->channel);
  845. UA_SecureChannel_deleteMembers(&client->channel);
  846. }
  847. UA_StatusCode
  848. UA_Client_disconnect(UA_Client *client) {
  849. /* Is a session established? */
  850. if(client->state >= UA_CLIENTSTATE_SESSION) {
  851. client->state = UA_CLIENTSTATE_SECURECHANNEL;
  852. sendCloseSession(client);
  853. }
  854. UA_NodeId_deleteMembers(&client->authenticationToken);
  855. client->requestHandle = 0;
  856. /* Is a secure channel established? */
  857. if(client->state >= UA_CLIENTSTATE_SECURECHANNEL) {
  858. client->state = UA_CLIENTSTATE_CONNECTED;
  859. sendCloseSecureChannel(client);
  860. }
  861. /* Close the TCP connection */
  862. if(client->connection.state != UA_CONNECTION_CLOSED
  863. && client->connection.state != UA_CONNECTION_OPENING)
  864. /*UA_ClientConnectionTCP_init sets initial state to opening */
  865. if(client->connection.close != NULL)
  866. client->connection.close(&client->connection);
  867. #ifdef UA_ENABLE_SUBSCRIPTIONS
  868. // TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
  869. /* We need to clean up the subscriptions */
  870. UA_Client_Subscriptions_clean(client);
  871. #endif
  872. UA_SecureChannel_deleteMembers(&client->channel);
  873. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  874. return UA_STATUSCODE_GOOD;
  875. }