ua_client_connect_async.c 28 KB

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