ua_client_connect.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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. /* Verify the encrypted response */
  609. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  610. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  611. if(!UA_ByteString_equal(&response.serverCertificate,
  612. &client->channel.remoteCertificate)) {
  613. retval = UA_STATUSCODE_BADCERTIFICATEINVALID;
  614. goto cleanup;
  615. }
  616. /* Verify the client signature */
  617. retval = checkClientSignature(&client->channel, &response);
  618. if(retval != UA_STATUSCODE_GOOD)
  619. goto cleanup;
  620. }
  621. /* Copy nonce and and authenticationtoken */
  622. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  623. retval |= UA_ByteString_copy(&response.serverNonce, &client->channel.remoteNonce);
  624. UA_NodeId_deleteMembers(&client->authenticationToken);
  625. retval |= UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  626. }
  627. retval |= response.responseHeader.serviceResult;
  628. cleanup:
  629. UA_CreateSessionRequest_deleteMembers(&request);
  630. UA_CreateSessionResponse_deleteMembers(&response);
  631. return retval;
  632. }
  633. UA_StatusCode
  634. UA_Client_connectTCPSecureChannel(UA_Client *client, const UA_String endpointUrl) {
  635. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  636. return UA_STATUSCODE_GOOD;
  637. UA_ChannelSecurityToken_init(&client->channel.securityToken);
  638. client->channel.state = UA_SECURECHANNELSTATE_FRESH;
  639. client->channel.sendSequenceNumber = 0;
  640. client->requestId = 0;
  641. /* Set the channel SecurityMode */
  642. client->channel.securityMode = client->config.endpoint.securityMode;
  643. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  644. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  645. /* Initialized the SecureChannel */
  646. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  647. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  648. "Initialize the SecurityPolicy context");
  649. if(!client->channel.securityPolicy) {
  650. /* Set the channel SecurityPolicy to #None if no endpoint is selected */
  651. UA_String sps = client->config.endpoint.securityPolicyUri;
  652. if(client->config.endpoint.securityPolicyUri.length == 0)
  653. sps = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  654. UA_SecurityPolicy *sp = getSecurityPolicy(client, sps);
  655. if(!sp) {
  656. retval = UA_STATUSCODE_BADINTERNALERROR;
  657. goto cleanup;
  658. }
  659. retval =
  660. UA_SecureChannel_setSecurityPolicy(&client->channel, sp,
  661. &client->config.endpoint.serverCertificate);
  662. if(retval != UA_STATUSCODE_GOOD)
  663. goto cleanup;
  664. }
  665. /* Open a TCP connection */
  666. client->connection = client->config.connectionFunc(client->config.localConnectionConfig,
  667. endpointUrl, client->config.timeout,
  668. &client->config.logger);
  669. if(client->connection.state != UA_CONNECTION_OPENING) {
  670. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  671. "Opening the TCP socket failed");
  672. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  673. goto cleanup;
  674. }
  675. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  676. "TCP connection established");
  677. /* Perform the HEL/ACK handshake */
  678. client->connection.config = client->config.localConnectionConfig;
  679. retval = HelAckHandshake(client, endpointUrl);
  680. if(retval != UA_STATUSCODE_GOOD)
  681. goto cleanup;
  682. setClientState(client, UA_CLIENTSTATE_CONNECTED);
  683. /* Open a SecureChannel. */
  684. retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  685. if(retval != UA_STATUSCODE_GOOD)
  686. goto cleanup;
  687. client->channel.connection = &client->connection;
  688. retval = openSecureChannel(client, false);
  689. if(retval != UA_STATUSCODE_GOOD)
  690. goto cleanup;
  691. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  692. if(retval != UA_STATUSCODE_GOOD)
  693. return retval;
  694. setClientState(client, UA_CLIENTSTATE_SECURECHANNEL);
  695. return retval;
  696. cleanup:
  697. UA_Client_disconnect(client);
  698. return retval;
  699. }
  700. UA_StatusCode
  701. UA_Client_connectSession(UA_Client *client) {
  702. if(client->state < UA_CLIENTSTATE_SECURECHANNEL)
  703. return UA_STATUSCODE_BADINTERNALERROR;
  704. /* Delete async service. TODO: Move this from connect to the disconnect/cleanup phase */
  705. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  706. // TODO: actually, reactivate an existing session is working, but currently
  707. // republish is not implemented This option is disabled until we have a good
  708. // implementation of the subscription recovery.
  709. #ifdef UA_SESSION_RECOVERY
  710. /* Try to activate an existing Session for this SecureChannel */
  711. if((!UA_NodeId_equal(&client->authenticationToken, &UA_NODEID_NULL)) && (createNewSession)) {
  712. UA_StatusCode res = activateSession(client);
  713. if(res != UA_STATUSCODE_BADSESSIONIDINVALID) {
  714. if(res == UA_STATUSCODE_GOOD)
  715. setClientState(client, UA_CLIENTSTATE_SESSION_RENEWED);
  716. else
  717. UA_Client_disconnect(client);
  718. return res;
  719. }
  720. }
  721. #endif /* UA_SESSION_RECOVERY */
  722. /* Could not recover an old session. Remove authenticationToken */
  723. UA_NodeId_deleteMembers(&client->authenticationToken);
  724. /* Create a session */
  725. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Create a new session");
  726. UA_StatusCode retval = createSession(client);
  727. if(retval != UA_STATUSCODE_GOOD) {
  728. UA_Client_disconnect(client);
  729. return retval;
  730. }
  731. /* A new session has been created. We need to clean up the subscriptions */
  732. #ifdef UA_ENABLE_SUBSCRIPTIONS
  733. UA_Client_Subscriptions_clean(client);
  734. client->currentlyOutStandingPublishRequests = 0;
  735. #endif
  736. /* Activate the session */
  737. retval = activateSession(client);
  738. if(retval != UA_STATUSCODE_GOOD) {
  739. UA_Client_disconnect(client);
  740. return retval;
  741. }
  742. setClientState(client, UA_CLIENTSTATE_SESSION);
  743. return retval;
  744. }
  745. UA_StatusCode
  746. UA_Client_connectInternal(UA_Client *client, const UA_String endpointUrl) {
  747. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  748. return UA_STATUSCODE_GOOD;
  749. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  750. "Connecting to endpoint %.*s", (int)endpointUrl.length,
  751. endpointUrl.data);
  752. /* Get endpoints only if the description has not been touched (memset to
  753. * zero) */
  754. UA_Byte test = 0;
  755. UA_Byte *pos = (UA_Byte*)&client->config.endpoint;
  756. for(size_t i = 0; i < sizeof(UA_EndpointDescription); i++)
  757. test = test | pos[i];
  758. pos = (UA_Byte*)&client->config.userTokenPolicy;
  759. for(size_t i = 0; i < sizeof(UA_UserTokenPolicy); i++)
  760. test = test | pos[i];
  761. UA_Boolean getEndpoints = (test == 0);
  762. /* Connect up to the SecureChannel */
  763. UA_StatusCode retval = UA_Client_connectTCPSecureChannel(client, endpointUrl);
  764. if(retval != UA_STATUSCODE_GOOD)
  765. goto cleanup;
  766. /* Get and select endpoints if required */
  767. if(getEndpoints) {
  768. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  769. "Endpoint and UserTokenPolicy unconfigured, perform GetEndpoints");
  770. retval = selectEndpoint(client, endpointUrl);
  771. if(retval != UA_STATUSCODE_GOOD)
  772. goto cleanup;
  773. /* Reconnect with a new SecureChannel if the current one does not match
  774. * the selected endpoint */
  775. if(!UA_String_equal(&client->config.endpoint.securityPolicyUri,
  776. &client->channel.securityPolicy->policyUri)) {
  777. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  778. "Disconnect to switch to a different SecurityPolicy");
  779. UA_Client_disconnect(client);
  780. return UA_Client_connectInternal(client, endpointUrl);
  781. }
  782. }
  783. retval = UA_Client_connectSession(client);
  784. if(retval != UA_STATUSCODE_GOOD)
  785. goto cleanup;
  786. return retval;
  787. cleanup:
  788. UA_Client_disconnect(client);
  789. return retval;
  790. }
  791. UA_StatusCode
  792. UA_Client_connect(UA_Client *client, const char *endpointUrl) {
  793. return UA_Client_connectInternal(client, UA_STRING((char*)(uintptr_t)endpointUrl));
  794. }
  795. UA_StatusCode
  796. UA_Client_connect_noSession(UA_Client *client, const char *endpointUrl) {
  797. return UA_Client_connectTCPSecureChannel(client, UA_STRING((char*)(uintptr_t)endpointUrl));
  798. }
  799. UA_StatusCode
  800. UA_Client_connect_username(UA_Client *client, const char *endpointUrl,
  801. const char *username, const char *password) {
  802. UA_UserNameIdentityToken* identityToken = UA_UserNameIdentityToken_new();
  803. if(!identityToken)
  804. return UA_STATUSCODE_BADOUTOFMEMORY;
  805. identityToken->userName = UA_STRING_ALLOC(username);
  806. identityToken->password = UA_STRING_ALLOC(password);
  807. UA_ExtensionObject_deleteMembers(&client->config.userIdentityToken);
  808. client->config.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  809. client->config.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  810. client->config.userIdentityToken.content.decoded.data = identityToken;
  811. return UA_Client_connect(client, endpointUrl);
  812. }
  813. /************************/
  814. /* Close the Connection */
  815. /************************/
  816. static void
  817. sendCloseSession(UA_Client *client) {
  818. UA_CloseSessionRequest request;
  819. UA_CloseSessionRequest_init(&request);
  820. request.requestHeader.timestamp = UA_DateTime_now();
  821. request.requestHeader.timeoutHint = 10000;
  822. request.deleteSubscriptions = true;
  823. UA_CloseSessionResponse response;
  824. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  825. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  826. UA_CloseSessionRequest_deleteMembers(&request);
  827. UA_CloseSessionResponse_deleteMembers(&response);
  828. }
  829. static void
  830. sendCloseSecureChannel(UA_Client *client) {
  831. UA_SecureChannel *channel = &client->channel;
  832. UA_CloseSecureChannelRequest request;
  833. UA_CloseSecureChannelRequest_init(&request);
  834. request.requestHeader.requestHandle = ++client->requestHandle;
  835. request.requestHeader.timestamp = UA_DateTime_now();
  836. request.requestHeader.timeoutHint = 10000;
  837. request.requestHeader.authenticationToken = client->authenticationToken;
  838. UA_SecureChannel_sendSymmetricMessage(channel, ++client->requestId,
  839. UA_MESSAGETYPE_CLO, &request,
  840. &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
  841. UA_CloseSecureChannelRequest_deleteMembers(&request);
  842. UA_SecureChannel_close(&client->channel);
  843. UA_SecureChannel_deleteMembers(&client->channel);
  844. }
  845. UA_StatusCode
  846. UA_Client_disconnect(UA_Client *client) {
  847. /* Is a session established? */
  848. if(client->state >= UA_CLIENTSTATE_SESSION) {
  849. client->state = UA_CLIENTSTATE_SECURECHANNEL;
  850. sendCloseSession(client);
  851. }
  852. UA_NodeId_deleteMembers(&client->authenticationToken);
  853. client->requestHandle = 0;
  854. /* Is a secure channel established? */
  855. if(client->state >= UA_CLIENTSTATE_SECURECHANNEL) {
  856. client->state = UA_CLIENTSTATE_CONNECTED;
  857. sendCloseSecureChannel(client);
  858. }
  859. /* Close the TCP connection */
  860. if(client->connection.state != UA_CONNECTION_CLOSED
  861. && client->connection.state != UA_CONNECTION_OPENING)
  862. /* UA_ClientConnectionTCP_init sets initial state to opening */
  863. if(client->connection.close != NULL)
  864. client->connection.close(&client->connection);
  865. #ifdef UA_ENABLE_SUBSCRIPTIONS
  866. // TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
  867. /* We need to clean up the subscriptions */
  868. UA_Client_Subscriptions_clean(client);
  869. #endif
  870. UA_SecureChannel_deleteMembers(&client->channel);
  871. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  872. return UA_STATUSCODE_GOOD;
  873. }