ua_client_connect_async.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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. #include <open62541/transport_generated.h>
  5. #include <open62541/transport_generated_encoding_binary.h>
  6. #include <open62541/transport_generated_handling.h>
  7. #include <open62541/types_generated_encoding_binary.h>
  8. #include "ua_client_internal.h"
  9. #define UA_MINMESSAGESIZE 8192
  10. #define UA_SESSION_LOCALNONCELENGTH 32
  11. #define MAX_DATA_SIZE 4096
  12. /* Asynchronous client connection
  13. * To prepare an async connection, UA_Client_connectAsync() is called, which does not connect the
  14. * client directly. UA_Client_run_iterate() takes care of actually connecting the client:
  15. * if client is disconnected:
  16. * send hello msg and set the client state to be WAITING_FOR_ACK
  17. * (see UA_Client_connect_iterate())
  18. * if client is waiting for the ACK:
  19. * call the non-blocking receiving function and register processACKResponseAsync() as its callback
  20. * (see receivePacketAsync())
  21. * if ACK is processed (callback called):
  22. * processACKResponseAsync() calls openSecureChannelAsync() at the end, which prepares the request
  23. * to open secure channel and the client is connected
  24. * if client is connected:
  25. * call the non-blocking receiving function and register processOPNResponse() as its callback
  26. * (see receivePacketAsync())
  27. * if OPN-request processed (callback called)
  28. * send session request, where the session response is put into a normal AsyncServiceCall, and when
  29. * called, request to activate session is sent, where its response is again put into an AsyncServiceCall
  30. * in the very last step responseActivateSession():
  31. * the user defined callback that is passed into UA_Client_connectAsync() is called and the
  32. * async connection finalized.
  33. * */
  34. /***********************/
  35. /* Open the Connection */
  36. /***********************/
  37. static UA_StatusCode
  38. openSecureChannelAsync(UA_Client *client/*, UA_Boolean renew*/);
  39. static UA_StatusCode
  40. requestSession(UA_Client *client, UA_UInt32 *requestId);
  41. static UA_StatusCode
  42. requestGetEndpoints(UA_Client *client, UA_UInt32 *requestId);
  43. /*receives hello ack, opens secure channel*/
  44. UA_StatusCode
  45. processACKResponseAsync(void *application, UA_Connection *connection,
  46. UA_ByteString *chunk) {
  47. UA_Client *client = (UA_Client*)application;
  48. /* Decode the message */
  49. size_t offset = 0;
  50. UA_TcpMessageHeader messageHeader;
  51. UA_TcpAcknowledgeMessage ackMessage;
  52. client->connectStatus = UA_TcpMessageHeader_decodeBinary (chunk, &offset,
  53. &messageHeader);
  54. client->connectStatus |= UA_TcpAcknowledgeMessage_decodeBinary(
  55. chunk, &offset, &ackMessage);
  56. if (client->connectStatus != UA_STATUSCODE_GOOD) {
  57. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  58. "Decoding ACK message failed");
  59. return client->connectStatus;
  60. }
  61. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  62. client->connectStatus =
  63. UA_Connection_processHELACK(connection, &client->config.localConnectionConfig,
  64. (const UA_ConnectionConfig*)&ackMessage);
  65. if(client->connectStatus != UA_STATUSCODE_GOOD)
  66. return client->connectStatus;
  67. client->state = UA_CLIENTSTATE_CONNECTED;
  68. /* Open a SecureChannel. TODO: Select with endpoint */
  69. client->channel.connection = &client->connection;
  70. client->connectStatus = openSecureChannelAsync(client/*, false*/);
  71. return client->connectStatus;
  72. }
  73. static UA_StatusCode
  74. sendHELMessage(UA_Client *client) {
  75. /* Get a buffer */
  76. UA_ByteString message;
  77. UA_Connection *conn = &client->connection;
  78. UA_StatusCode retval = conn->getSendBuffer(conn, UA_MINMESSAGESIZE, &message);
  79. if(retval != UA_STATUSCODE_GOOD)
  80. return retval;
  81. /* Prepare the HEL message and encode at offset 8 */
  82. UA_TcpHelloMessage hello;
  83. UA_String_copy(&client->endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  84. memcpy(&hello, &client->config.localConnectionConfig,
  85. sizeof(UA_ConnectionConfig)); /* same struct layout */
  86. UA_Byte *bufPos = &message.data[8]; /* skip the header */
  87. const UA_Byte *bufEnd = &message.data[message.length];
  88. client->connectStatus = UA_TcpHelloMessage_encodeBinary(&hello, &bufPos, bufEnd);
  89. UA_TcpHelloMessage_deleteMembers (&hello);
  90. /* Encode the message header at offset 0 */
  91. UA_TcpMessageHeader messageHeader;
  92. messageHeader.messageTypeAndChunkType = UA_CHUNKTYPE_FINAL + UA_MESSAGETYPE_HEL;
  93. messageHeader.messageSize = (UA_UInt32) ((uintptr_t)bufPos - (uintptr_t)message.data);
  94. bufPos = message.data;
  95. retval = UA_TcpMessageHeader_encodeBinary(&messageHeader, &bufPos, bufEnd);
  96. if(retval != UA_STATUSCODE_GOOD) {
  97. conn->releaseSendBuffer(conn, &message);
  98. return retval;
  99. }
  100. /* Send the HEL message */
  101. message.length = messageHeader.messageSize;
  102. retval = conn->send (conn, &message);
  103. if(retval == UA_STATUSCODE_GOOD) {
  104. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK, "Sent HEL message");
  105. } else {
  106. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK, "Sending HEL failed");
  107. }
  108. return retval;
  109. }
  110. static void
  111. processDecodedOPNResponseAsync(void *application, UA_SecureChannel *channel,
  112. UA_MessageType messageType,
  113. UA_UInt32 requestId,
  114. const UA_ByteString *message) {
  115. /* Does the request id match? */
  116. UA_Client *client = (UA_Client*)application;
  117. if(requestId != client->requestId) {
  118. UA_Client_disconnect(client);
  119. return;
  120. }
  121. /* Is the content of the expected type? */
  122. size_t offset = 0;
  123. UA_NodeId responseId;
  124. UA_NodeId expectedId = UA_NODEID_NUMERIC(
  125. 0, UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE].binaryEncodingId);
  126. UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset,
  127. &responseId);
  128. if(retval != UA_STATUSCODE_GOOD) {
  129. UA_Client_disconnect(client);
  130. return;
  131. }
  132. if(!UA_NodeId_equal(&responseId, &expectedId)) {
  133. UA_NodeId_deleteMembers(&responseId);
  134. UA_Client_disconnect(client);
  135. return;
  136. }
  137. UA_NodeId_deleteMembers (&responseId);
  138. /* Decode the response */
  139. UA_OpenSecureChannelResponse response;
  140. retval = UA_OpenSecureChannelResponse_decodeBinary(message, &offset,
  141. &response);
  142. if(retval != UA_STATUSCODE_GOOD) {
  143. UA_Client_disconnect(client);
  144. return;
  145. }
  146. /* Response.securityToken.revisedLifetime is UInt32 we need to cast it to
  147. * DateTime=Int64 we take 75% of lifetime to start renewing as described in
  148. * standard */
  149. client->nextChannelRenewal = UA_DateTime_nowMonotonic()
  150. + (UA_DateTime) (response.securityToken.revisedLifetime
  151. * (UA_Double) UA_DATETIME_MSEC * 0.75);
  152. /* Replace the token and nonce */
  153. UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
  154. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  155. client->channel.securityToken = response.securityToken;
  156. client->channel.remoteNonce = response.serverNonce;
  157. UA_ResponseHeader_deleteMembers(&response.responseHeader); /* the other members were moved */
  158. if(client->channel.state == UA_SECURECHANNELSTATE_OPEN)
  159. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel renewed");
  160. else
  161. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel opened");
  162. client->channel.state = UA_SECURECHANNELSTATE_OPEN;
  163. if(client->state < UA_CLIENTSTATE_SECURECHANNEL)
  164. setClientState(client, UA_CLIENTSTATE_SECURECHANNEL);
  165. }
  166. UA_StatusCode
  167. processOPNResponseAsync(void *application, UA_Connection *connection,
  168. UA_ByteString *chunk) {
  169. UA_Client *client = (UA_Client*) application;
  170. UA_StatusCode retval = UA_SecureChannel_decryptAddChunk(&client->channel, chunk, true);
  171. client->connectStatus = retval;
  172. if(retval != UA_STATUSCODE_GOOD)
  173. goto error;
  174. UA_SecureChannel_processCompleteMessages(&client->channel, client, processDecodedOPNResponseAsync);
  175. if(client->state < UA_CLIENTSTATE_SECURECHANNEL) {
  176. retval = UA_STATUSCODE_BADSECURECHANNELCLOSED;
  177. goto error;
  178. }
  179. retval = UA_SecureChannel_persistIncompleteMessages(&client->channel);
  180. if(retval != UA_STATUSCODE_GOOD)
  181. goto error;
  182. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  183. if(retval != UA_STATUSCODE_GOOD)
  184. goto error;
  185. /* Following requests and responses */
  186. UA_UInt32 reqId;
  187. if(client->endpointsHandshake)
  188. retval = requestGetEndpoints (client, &reqId);
  189. else
  190. retval = requestSession (client, &reqId);
  191. if(retval != UA_STATUSCODE_GOOD)
  192. goto error;
  193. return retval;
  194. error:
  195. UA_Client_disconnect(client);
  196. return retval;
  197. }
  198. /* OPN messges to renew the channel are sent asynchronous */
  199. static UA_StatusCode
  200. openSecureChannelAsync(UA_Client *client/*, UA_Boolean renew*/) {
  201. /* Check if sc is still valid */
  202. /*if(renew && client->nextChannelRenewal - UA_DateTime_nowMonotonic () > 0)
  203. return UA_STATUSCODE_GOOD;*/
  204. UA_Connection *conn = &client->connection;
  205. if(conn->state != UA_CONNECTION_ESTABLISHED)
  206. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  207. /* Prepare the OpenSecureChannelRequest */
  208. UA_OpenSecureChannelRequest opnSecRq;
  209. UA_OpenSecureChannelRequest_init(&opnSecRq);
  210. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  211. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  212. /*if(renew) {
  213. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  214. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  215. "Requesting to renew the SecureChannel");
  216. } else {*/
  217. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  218. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  219. "Requesting to open a SecureChannel");
  220. //}
  221. opnSecRq.securityMode = client->channel.securityMode;
  222. opnSecRq.clientNonce = client->channel.localNonce;
  223. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  224. /* Prepare the entry for the linked list */
  225. UA_UInt32 requestId = ++client->requestId;
  226. /*AsyncServiceCall *ac = NULL;
  227. if(renew) {
  228. ac = (AsyncServiceCall*)UA_malloc(sizeof(AsyncServiceCall));
  229. if (!ac)
  230. return UA_STATUSCODE_BADOUTOFMEMORY;
  231. ac->callback =
  232. (UA_ClientAsyncServiceCallback) processDecodedOPNResponseAsync;
  233. ac->responseType = &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE];
  234. ac->requestId = requestId;
  235. ac->userdata = NULL;
  236. }*/
  237. /* Send the OPN message */
  238. UA_StatusCode retval = UA_SecureChannel_sendAsymmetricOPNMessage (
  239. &client->channel, requestId, &opnSecRq,
  240. &UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST]);
  241. client->connectStatus = retval;
  242. if(retval != UA_STATUSCODE_GOOD) {
  243. client->connectStatus = retval;
  244. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  245. "Sending OPN message failed with error %s",
  246. UA_StatusCode_name(retval));
  247. UA_Client_disconnect(client);
  248. //if(renew)
  249. // UA_free(ac);
  250. return retval;
  251. }
  252. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  253. "OPN message sent");
  254. /* Store the entry for async processing and return */
  255. /*if(renew) {
  256. LIST_INSERT_HEAD(&client->asyncServiceCalls, ac, pointers);
  257. return retval;
  258. }*/
  259. return retval;
  260. }
  261. static void
  262. responseActivateSession(UA_Client *client, void *userdata, UA_UInt32 requestId,
  263. void *response) {
  264. UA_ActivateSessionResponse *activateResponse =
  265. (UA_ActivateSessionResponse *) response;
  266. if(activateResponse->responseHeader.serviceResult) {
  267. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  268. "ActivateSession failed with error code %s",
  269. UA_StatusCode_name(activateResponse->responseHeader.serviceResult));
  270. }
  271. client->connection.state = UA_CONNECTION_ESTABLISHED;
  272. setClientState(client, UA_CLIENTSTATE_SESSION);
  273. #ifdef UA_ENABLE_SUBSCRIPTIONS
  274. /* A new session has been created. We need to clean up the subscriptions */
  275. UA_Client_Subscriptions_clean(client);
  276. #endif
  277. /* Call onConnect (client_async.c) callback */
  278. if(client->asyncConnectCall.callback)
  279. client->asyncConnectCall.callback(client, client->asyncConnectCall.userdata,
  280. requestId + 1,
  281. &activateResponse->responseHeader.serviceResult);
  282. }
  283. static UA_StatusCode
  284. requestActivateSession (UA_Client *client, UA_UInt32 *requestId) {
  285. UA_ActivateSessionRequest request;
  286. UA_ActivateSessionRequest_init(&request);
  287. request.requestHeader.requestHandle = ++client->requestHandle;
  288. request.requestHeader.timestamp = UA_DateTime_now ();
  289. request.requestHeader.timeoutHint = 600000;
  290. UA_StatusCode retval =
  291. UA_ExtensionObject_copy(&client->config.userIdentityToken, &request.userIdentityToken);
  292. if(retval != UA_STATUSCODE_GOOD)
  293. return retval;
  294. /* If not token is set, use anonymous */
  295. if(request.userIdentityToken.encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
  296. UA_AnonymousIdentityToken *t = UA_AnonymousIdentityToken_new();
  297. if(!t) {
  298. UA_ActivateSessionRequest_deleteMembers(&request);
  299. return UA_STATUSCODE_BADOUTOFMEMORY;
  300. }
  301. request.userIdentityToken.content.decoded.data = t;
  302. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  303. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  304. }
  305. /* Set the policy-Id from the endpoint. Every IdentityToken starts with a
  306. * string. */
  307. retval = UA_String_copy(&client->config.userTokenPolicy.policyId,
  308. (UA_String*)request.userIdentityToken.content.decoded.data);
  309. #ifdef UA_ENABLE_ENCRYPTION
  310. /* Encrypt the UserIdentityToken */
  311. const UA_String *userTokenPolicy = &client->channel.securityPolicy->policyUri;
  312. if(client->config.userTokenPolicy.securityPolicyUri.length > 0)
  313. userTokenPolicy = &client->config.userTokenPolicy.securityPolicyUri;
  314. retval |= encryptUserIdentityToken(client, userTokenPolicy, &request.userIdentityToken);
  315. /* This function call is to prepare a client signature */
  316. retval |= signActivateSessionRequest(&client->channel, &request);
  317. #endif
  318. if(retval != UA_STATUSCODE_GOOD) {
  319. UA_ActivateSessionRequest_deleteMembers(&request);
  320. client->connectStatus = retval;
  321. return retval;
  322. }
  323. retval = UA_Client_sendAsyncRequest (
  324. client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  325. (UA_ClientAsyncServiceCallback) responseActivateSession,
  326. &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE], NULL, requestId);
  327. UA_ActivateSessionRequest_deleteMembers(&request);
  328. client->connectStatus = retval;
  329. return retval;
  330. }
  331. /* Combination of UA_Client_getEndpointsInternal and getEndpoints */
  332. static void
  333. responseGetEndpoints(UA_Client *client, void *userdata, UA_UInt32 requestId,
  334. void *response) {
  335. UA_EndpointDescription* endpointArray = NULL;
  336. size_t endpointArraySize = 0;
  337. UA_GetEndpointsResponse* resp;
  338. resp = (UA_GetEndpointsResponse*)response;
  339. if (resp->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  340. client->connectStatus = resp->responseHeader.serviceResult;
  341. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  342. "GetEndpointRequest failed with error code %s",
  343. UA_StatusCode_name (client->connectStatus));
  344. UA_GetEndpointsResponse_deleteMembers(resp);
  345. return;
  346. }
  347. endpointArray = resp->endpoints;
  348. endpointArraySize = resp->endpointsSize;
  349. resp->endpoints = NULL;
  350. resp->endpointsSize = 0;
  351. UA_Boolean endpointFound = false;
  352. UA_Boolean tokenFound = false;
  353. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  354. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  355. "Transport/uatcp-uasc-uabinary");
  356. // TODO: compare endpoint information with client->endpointUri
  357. for(size_t i = 0; i < endpointArraySize; ++i) {
  358. UA_EndpointDescription* endpoint = &endpointArray[i];
  359. /* look out for binary transport endpoints */
  360. /* Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  361. if(endpoint->transportProfileUri.length != 0
  362. && !UA_String_equal (&endpoint->transportProfileUri,
  363. &binaryTransport))
  364. continue;
  365. /* Look for an endpoint corresponding to the client security policy */
  366. if(!UA_String_equal(&endpoint->securityPolicyUri, &client->channel.securityPolicy->policyUri))
  367. continue;
  368. endpointFound = true;
  369. /* Look for a user token policy with an anonymous token */
  370. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  371. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  372. /* Usertokens also have a security policy... */
  373. if(userToken->securityPolicyUri.length > 0 &&
  374. !UA_String_equal(&userToken->securityPolicyUri, &securityNone))
  375. continue;
  376. /* Does the token type match the client configuration? */
  377. if((userToken->tokenType == UA_USERTOKENTYPE_ANONYMOUS &&
  378. client->config.userIdentityToken.content.decoded.type !=
  379. &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN] &&
  380. client->config.userIdentityToken.content.decoded.type != NULL) ||
  381. (userToken->tokenType == UA_USERTOKENTYPE_USERNAME &&
  382. client->config.userIdentityToken.content.decoded.type !=
  383. &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) ||
  384. (userToken->tokenType == UA_USERTOKENTYPE_CERTIFICATE &&
  385. client->config.userIdentityToken.content.decoded.type !=
  386. &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN]) ||
  387. (userToken->tokenType == UA_USERTOKENTYPE_ISSUEDTOKEN &&
  388. client->config.userIdentityToken.content.decoded.type !=
  389. &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]))
  390. continue;
  391. /* Endpoint with matching usertokenpolicy found */
  392. tokenFound = true;
  393. UA_EndpointDescription_deleteMembers(&client->config.endpoint);
  394. UA_EndpointDescription_copy(endpoint, &client->config.endpoint);
  395. UA_UserTokenPolicy_deleteMembers(&client->config.userTokenPolicy);
  396. UA_UserTokenPolicy_copy(userToken, &client->config.userTokenPolicy);
  397. break;
  398. }
  399. }
  400. UA_Array_delete(endpointArray, endpointArraySize,
  401. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  402. if(!endpointFound) {
  403. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  404. "No suitable endpoint found");
  405. client->connectStatus = UA_STATUSCODE_BADINTERNALERROR;
  406. } else if(!tokenFound) {
  407. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  408. "No suitable UserTokenPolicy found for the possible endpoints");
  409. client->connectStatus = UA_STATUSCODE_BADINTERNALERROR;
  410. }
  411. requestSession(client, &requestId);
  412. }
  413. static UA_StatusCode
  414. requestGetEndpoints(UA_Client *client, UA_UInt32 *requestId) {
  415. UA_GetEndpointsRequest request;
  416. UA_GetEndpointsRequest_init(&request);
  417. request.requestHeader.timestamp = UA_DateTime_now();
  418. request.requestHeader.timeoutHint = 10000;
  419. /* assume the endpointurl outlives the service call */
  420. UA_String_copy(&client->endpointUrl, &request.endpointUrl);
  421. client->connectStatus = UA_Client_sendAsyncRequest(
  422. client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  423. (UA_ClientAsyncServiceCallback) responseGetEndpoints,
  424. &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE], NULL, requestId);
  425. UA_GetEndpointsRequest_deleteMembers(&request);
  426. return client->connectStatus;
  427. }
  428. static void
  429. responseSessionCallback(UA_Client *client, void *userdata, UA_UInt32 requestId,
  430. void *response) {
  431. UA_CreateSessionResponse *sessionResponse =
  432. (UA_CreateSessionResponse *)response;
  433. UA_NodeId_copy(&sessionResponse->authenticationToken,
  434. &client->authenticationToken);
  435. requestActivateSession(client, &requestId);
  436. }
  437. static UA_StatusCode
  438. requestSession(UA_Client *client, UA_UInt32 *requestId) {
  439. UA_CreateSessionRequest request;
  440. UA_CreateSessionRequest_init(&request);
  441. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  442. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  443. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  444. if(client->channel.localNonce.length != UA_SESSION_LOCALNONCELENGTH) {
  445. UA_ByteString_deleteMembers(&client->channel.localNonce);
  446. retval = UA_ByteString_allocBuffer(&client->channel.localNonce,
  447. UA_SESSION_LOCALNONCELENGTH);
  448. if(retval != UA_STATUSCODE_GOOD)
  449. return retval;
  450. }
  451. retval = client->channel.securityPolicy->symmetricModule.
  452. generateNonce(client->channel.securityPolicy, &client->channel.localNonce);
  453. if(retval != UA_STATUSCODE_GOOD)
  454. return retval;
  455. }
  456. request.requestHeader.requestHandle = ++client->requestHandle;
  457. request.requestHeader.timestamp = UA_DateTime_now();
  458. request.requestHeader.timeoutHint = 10000;
  459. UA_ByteString_copy(&client->channel.localNonce, &request.clientNonce);
  460. request.requestedSessionTimeout = client->config.requestedSessionTimeout;
  461. request.maxResponseMessageSize = UA_INT32_MAX;
  462. UA_String_copy(&client->config.endpoint.endpointUrl, &request.endpointUrl);
  463. UA_ApplicationDescription_copy(&client->config.clientDescription,
  464. &request.clientDescription);
  465. retval = UA_Client_sendAsyncRequest (
  466. client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  467. (UA_ClientAsyncServiceCallback) responseSessionCallback,
  468. &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE], NULL, requestId);
  469. UA_CreateSessionRequest_deleteMembers(&request);
  470. client->connectStatus = retval;
  471. return client->connectStatus;
  472. }
  473. UA_StatusCode
  474. UA_Client_connect_iterate(UA_Client *client) {
  475. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  476. "Client connect iterate");
  477. if (client->connection.state == UA_CONNECTION_ESTABLISHED){
  478. if(client->state < UA_CLIENTSTATE_WAITING_FOR_ACK) {
  479. client->connectStatus = sendHELMessage(client);
  480. if(client->connectStatus == UA_STATUSCODE_GOOD) {
  481. setClientState(client, UA_CLIENTSTATE_WAITING_FOR_ACK);
  482. } else {
  483. client->connection.close(&client->connection);
  484. client->connection.free(&client->connection);
  485. }
  486. return client->connectStatus;
  487. }
  488. }
  489. /* If server is not connected */
  490. if(client->connection.state == UA_CONNECTION_CLOSED) {
  491. client->connectStatus = UA_STATUSCODE_BADCONNECTIONCLOSED;
  492. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  493. "No connection to server.");
  494. }
  495. if(client->connectStatus != UA_STATUSCODE_GOOD) {
  496. client->connection.close(&client->connection);
  497. client->connection.free(&client->connection);
  498. }
  499. return client->connectStatus;
  500. }
  501. UA_StatusCode
  502. UA_Client_connect_async(UA_Client *client, const char *endpointUrl,
  503. UA_ClientAsyncServiceCallback callback,
  504. void *userdata) {
  505. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  506. "Client internal async");
  507. if(client->state >= UA_CLIENTSTATE_WAITING_FOR_ACK)
  508. return UA_STATUSCODE_GOOD;
  509. UA_ChannelSecurityToken_init(&client->channel.securityToken);
  510. client->channel.state = UA_SECURECHANNELSTATE_FRESH;
  511. client->endpointsHandshake = true;
  512. client->channel.sendSequenceNumber = 0;
  513. client->requestId = 0;
  514. UA_String_deleteMembers(&client->endpointUrl);
  515. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  516. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  517. client->connection =
  518. client->config.initConnectionFunc(client->config.localConnectionConfig,
  519. client->endpointUrl,
  520. client->config.timeout, &client->config.logger);
  521. if(client->connection.state != UA_CONNECTION_OPENING) {
  522. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  523. "Could not init async connection");
  524. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  525. goto cleanup;
  526. }
  527. /* Set the channel SecurityMode if not done so far */
  528. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  529. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  530. /* Set the channel SecurityPolicy if not done so far */
  531. if(!client->channel.securityPolicy) {
  532. UA_SecurityPolicy *sp =
  533. getSecurityPolicy(client, UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None"));
  534. if(!sp) {
  535. retval = UA_STATUSCODE_BADINTERNALERROR;
  536. goto cleanup;
  537. }
  538. UA_ByteString remoteCertificate = UA_BYTESTRING_NULL;
  539. retval = UA_SecureChannel_setSecurityPolicy(&client->channel, sp,
  540. &remoteCertificate);
  541. if(retval != UA_STATUSCODE_GOOD)
  542. goto cleanup;
  543. }
  544. client->asyncConnectCall.callback = callback;
  545. client->asyncConnectCall.userdata = userdata;
  546. if(!client->connection.connectCallbackID) {
  547. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  548. "Adding async connection callback");
  549. retval = UA_Client_addRepeatedCallback(
  550. client, client->config.pollConnectionFunc, &client->connection, 100.0,
  551. &client->connection.connectCallbackID);
  552. if(retval != UA_STATUSCODE_GOOD)
  553. goto cleanup;
  554. }
  555. retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  556. if(retval != UA_STATUSCODE_GOOD)
  557. goto cleanup;
  558. /* Delete async service. TODO: Move this from connect to the disconnect/cleanup phase */
  559. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  560. #ifdef UA_ENABLE_SUBSCRIPTIONS
  561. client->currentlyOutStandingPublishRequests = 0;
  562. #endif
  563. UA_NodeId_deleteMembers(&client->authenticationToken);
  564. /* Generate new local and remote key */
  565. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  566. if(retval != UA_STATUSCODE_GOOD)
  567. goto cleanup;
  568. return retval;
  569. cleanup:
  570. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  571. "Failure during async connect");
  572. UA_Client_disconnect(client);
  573. return retval;
  574. }
  575. /* Async disconnection */
  576. static void
  577. sendCloseSecureChannelAsync(UA_Client *client, void *userdata,
  578. UA_UInt32 requestId, void *response) {
  579. UA_NodeId_deleteMembers (&client->authenticationToken);
  580. client->requestHandle = 0;
  581. UA_SecureChannel *channel = &client->channel;
  582. UA_CloseSecureChannelRequest request;
  583. UA_CloseSecureChannelRequest_init(&request);
  584. request.requestHeader.requestHandle = ++client->requestHandle;
  585. request.requestHeader.timestamp = UA_DateTime_now();
  586. request.requestHeader.timeoutHint = 10000;
  587. request.requestHeader.authenticationToken = client->authenticationToken;
  588. UA_SecureChannel_sendSymmetricMessage(
  589. channel, ++client->requestId, UA_MESSAGETYPE_CLO, &request,
  590. &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
  591. UA_SecureChannel_close(&client->channel);
  592. UA_SecureChannel_deleteMembers(&client->channel);
  593. }
  594. static void
  595. sendCloseSessionAsync(UA_Client *client, UA_UInt32 *requestId) {
  596. UA_CloseSessionRequest request;
  597. UA_CloseSessionRequest_init(&request);
  598. request.requestHeader.timestamp = UA_DateTime_now();
  599. request.requestHeader.timeoutHint = 10000;
  600. request.deleteSubscriptions = true;
  601. UA_Client_sendAsyncRequest(
  602. client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  603. (UA_ClientAsyncServiceCallback) sendCloseSecureChannelAsync,
  604. &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE], NULL, requestId);
  605. }
  606. UA_StatusCode
  607. UA_Client_disconnect_async(UA_Client *client, UA_UInt32 *requestId) {
  608. /* Is a session established? */
  609. if (client->state == UA_CLIENTSTATE_SESSION) {
  610. client->state = UA_CLIENTSTATE_SESSION_DISCONNECTED;
  611. sendCloseSessionAsync(client, requestId);
  612. }
  613. /* Close the TCP connection
  614. * shutdown and close (in tcp.c) are already async*/
  615. if (client->state >= UA_CLIENTSTATE_CONNECTED)
  616. client->connection.close(&client->connection);
  617. else
  618. UA_Client_removeRepeatedCallback(client, client->connection.connectCallbackID);
  619. #ifdef UA_ENABLE_SUBSCRIPTIONS
  620. // TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
  621. /* We need to clean up the subscriptions */
  622. UA_Client_Subscriptions_clean(client);
  623. #endif
  624. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  625. return UA_STATUSCODE_GOOD;
  626. }