ua_client_connect.c 42 KB

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