ua_client_connect.c 46 KB

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