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