ua_client_connect.c 43 KB

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