ua_client_connect_async.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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_internal.h"
  5. #include "ua_transport_generated.h"
  6. #include "ua_transport_generated_handling.h"
  7. #include "ua_transport_generated_encoding_binary.h"
  8. #include "ua_types_encoding_binary.h"
  9. #include "ua_types_generated_encoding_binary.h"
  10. #define UA_MINMESSAGESIZE 8192
  11. #define UA_SESSION_LOCALNONCELENGTH 32
  12. #define MAX_DATA_SIZE 4096
  13. /* Asynchronous client connection
  14. * To prepare an async connection, UA_Client_connectAsync() is called, which does not connect the
  15. * client directly. UA_Client_run_iterate() takes care of actually connecting the client:
  16. * if client is disconnected:
  17. * send hello msg and set the client state to be WAITING_FOR_ACK
  18. * (see UA_Client_connect_iterate())
  19. * if client is waiting for the ACK:
  20. * call the non-blocking receiving function and register processACKResponseAsync() as its callback
  21. * (see receivePacketAsync())
  22. * if ACK is processed (callback called):
  23. * processACKResponseAsync() calls openSecureChannelAsync() at the end, which prepares the request
  24. * to open secure channel and the client is connected
  25. * if client is connected:
  26. * call the non-blocking receiving function and register processOPNResponse() as its callback
  27. * (see receivePacketAsync())
  28. * if OPN-request processed (callback called)
  29. * send session request, where the session response is put into a normal AsyncServiceCall, and when
  30. * called, request to activate session is sent, where its response is again put into an AsyncServiceCall
  31. * in the very last step responseActivateSession():
  32. * the user defined callback that is passed into UA_Client_connectAsync() is called and the
  33. * async connection finalized.
  34. * */
  35. /***********************/
  36. /* Open the Connection */
  37. /***********************/
  38. static UA_StatusCode
  39. openSecureChannelAsync(UA_Client *client/*, UA_Boolean renew*/);
  40. static UA_StatusCode
  41. requestSession(UA_Client *client, UA_UInt32 *requestId);
  42. static UA_StatusCode
  43. requestGetEndpoints(UA_Client *client, UA_UInt32 *requestId);
  44. /*receives hello ack, opens secure channel*/
  45. UA_StatusCode
  46. processACKResponseAsync(void *application, UA_Connection *connection,
  47. UA_ByteString *chunk) {
  48. UA_Client *client = (UA_Client*)application;
  49. /* Decode the message */
  50. size_t offset = 0;
  51. UA_TcpMessageHeader messageHeader;
  52. UA_TcpAcknowledgeMessage ackMessage;
  53. client->connectStatus = UA_TcpMessageHeader_decodeBinary (chunk, &offset,
  54. &messageHeader);
  55. client->connectStatus |= UA_TcpAcknowledgeMessage_decodeBinary(
  56. chunk, &offset, &ackMessage);
  57. if (client->connectStatus != UA_STATUSCODE_GOOD) {
  58. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  59. "Decoding ACK message failed");
  60. return client->connectStatus;
  61. }
  62. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  63. client->connectStatus =
  64. UA_Connection_processHELACK(connection, &client->config.localConnectionConfig,
  65. (const UA_ConnectionConfig*)&ackMessage);
  66. if(client->connectStatus != UA_STATUSCODE_GOOD)
  67. return client->connectStatus;
  68. client->state = UA_CLIENTSTATE_CONNECTED;
  69. /* Open a SecureChannel. TODO: Select with endpoint */
  70. client->channel.connection = &client->connection;
  71. client->connectStatus = openSecureChannelAsync(client/*, false*/);
  72. return client->connectStatus;
  73. }
  74. static UA_StatusCode
  75. sendHELMessage(UA_Client *client) {
  76. /* Get a buffer */
  77. UA_ByteString message;
  78. UA_Connection *conn = &client->connection;
  79. UA_StatusCode retval = conn->getSendBuffer(conn, UA_MINMESSAGESIZE, &message);
  80. if(retval != UA_STATUSCODE_GOOD)
  81. return retval;
  82. /* Prepare the HEL message and encode at offset 8 */
  83. UA_TcpHelloMessage hello;
  84. UA_String_copy(&client->endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  85. memcpy(&hello, &client->config.localConnectionConfig, 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. AsyncServiceCall ac = client->asyncConnectCall;
  279. ac.callback(client, ac.userdata, requestId + 1,
  280. &activateResponse->responseHeader.serviceResult);
  281. }
  282. static UA_StatusCode
  283. requestActivateSession (UA_Client *client, UA_UInt32 *requestId) {
  284. UA_ActivateSessionRequest request;
  285. UA_ActivateSessionRequest_init(&request);
  286. request.requestHeader.requestHandle = ++client->requestHandle;
  287. request.requestHeader.timestamp = UA_DateTime_now ();
  288. request.requestHeader.timeoutHint = 600000;
  289. /* Manual ExtensionObject encoding of the identityToken */
  290. if (client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE) {
  291. UA_AnonymousIdentityToken* identityToken =
  292. UA_AnonymousIdentityToken_new();
  293. UA_AnonymousIdentityToken_init (identityToken);
  294. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  295. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  296. request.userIdentityToken.content.decoded.type =
  297. &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  298. request.userIdentityToken.content.decoded.data = identityToken;
  299. } else {
  300. UA_UserNameIdentityToken* identityToken =
  301. UA_UserNameIdentityToken_new();
  302. UA_UserNameIdentityToken_init (identityToken);
  303. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  304. UA_String_copy(&client->username, &identityToken->userName);
  305. UA_String_copy(&client->password, &identityToken->password);
  306. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  307. request.userIdentityToken.content.decoded.type =
  308. &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  309. request.userIdentityToken.content.decoded.data = identityToken;
  310. }
  311. /* This function call is to prepare a client signature */
  312. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  313. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  314. signActivateSessionRequest(&client->channel, &request);
  315. }
  316. UA_StatusCode retval = UA_Client_sendAsyncRequest (
  317. client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  318. (UA_ClientAsyncServiceCallback) responseActivateSession,
  319. &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE], NULL, requestId);
  320. UA_ActivateSessionRequest_deleteMembers(&request);
  321. client->connectStatus = retval;
  322. return retval;
  323. }
  324. /* Combination of UA_Client_getEndpointsInternal and getEndpoints */
  325. static void
  326. responseGetEndpoints(UA_Client *client, void *userdata, UA_UInt32 requestId,
  327. void *response) {
  328. UA_EndpointDescription* endpointArray = NULL;
  329. size_t endpointArraySize = 0;
  330. UA_GetEndpointsResponse* resp;
  331. resp = (UA_GetEndpointsResponse*)response;
  332. if (resp->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  333. client->connectStatus = resp->responseHeader.serviceResult;
  334. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  335. "GetEndpointRequest failed with error code %s",
  336. UA_StatusCode_name (client->connectStatus));
  337. UA_GetEndpointsResponse_deleteMembers(resp);
  338. return;
  339. }
  340. endpointArray = resp->endpoints;
  341. endpointArraySize = resp->endpointsSize;
  342. resp->endpoints = NULL;
  343. resp->endpointsSize = 0;
  344. UA_Boolean endpointFound = false;
  345. UA_Boolean tokenFound = false;
  346. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  347. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  348. "Transport/uatcp-uasc-uabinary");
  349. // TODO: compare endpoint information with client->endpointUri
  350. for(size_t i = 0; i < endpointArraySize; ++i) {
  351. UA_EndpointDescription* endpoint = &endpointArray[i];
  352. /* look out for binary transport endpoints */
  353. /* Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  354. if(endpoint->transportProfileUri.length != 0
  355. && !UA_String_equal (&endpoint->transportProfileUri,
  356. &binaryTransport))
  357. continue;
  358. /* Look for an endpoint corresponding to the client security policy */
  359. if(!UA_String_equal(&endpoint->securityPolicyUri, &client->securityPolicy.policyUri))
  360. continue;
  361. endpointFound = true;
  362. /* Look for a user token policy with an anonymous token */
  363. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  364. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  365. /* Usertokens also have a security policy... */
  366. if(userToken->securityPolicyUri.length > 0
  367. && !UA_String_equal(&userToken->securityPolicyUri,
  368. &securityNone))
  369. continue;
  370. /* UA_CLIENTAUTHENTICATION_NONE == UA_USERTOKENTYPE_ANONYMOUS
  371. * UA_CLIENTAUTHENTICATION_USERNAME == UA_USERTOKENTYPE_USERNAME
  372. * TODO: Check equivalence for other types when adding the support */
  373. if((int)client->authenticationMethod
  374. != (int)userToken->tokenType)
  375. continue;
  376. /* Endpoint with matching usertokenpolicy found */
  377. tokenFound = true;
  378. UA_UserTokenPolicy_deleteMembers(&client->token);
  379. UA_UserTokenPolicy_copy(userToken, &client->token);
  380. break;
  381. }
  382. }
  383. UA_Array_delete(endpointArray, endpointArraySize,
  384. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  385. if(!endpointFound) {
  386. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  387. "No suitable endpoint found");
  388. client->connectStatus = UA_STATUSCODE_BADINTERNALERROR;
  389. } else if(!tokenFound) {
  390. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  391. "No suitable UserTokenPolicy found for the possible endpoints");
  392. client->connectStatus = UA_STATUSCODE_BADINTERNALERROR;
  393. }
  394. requestSession(client, &requestId);
  395. }
  396. static UA_StatusCode
  397. requestGetEndpoints(UA_Client *client, UA_UInt32 *requestId) {
  398. UA_GetEndpointsRequest request;
  399. UA_GetEndpointsRequest_init(&request);
  400. request.requestHeader.timestamp = UA_DateTime_now();
  401. request.requestHeader.timeoutHint = 10000;
  402. /* assume the endpointurl outlives the service call */
  403. UA_String_copy (&client->endpointUrl, &request.endpointUrl);
  404. client->connectStatus = UA_Client_sendAsyncRequest(
  405. client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  406. (UA_ClientAsyncServiceCallback) responseGetEndpoints,
  407. &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE], NULL, requestId);
  408. UA_GetEndpointsRequest_deleteMembers(&request);
  409. return client->connectStatus;
  410. }
  411. static void
  412. responseSessionCallback(UA_Client *client, void *userdata, UA_UInt32 requestId,
  413. void *response) {
  414. UA_CreateSessionResponse *sessionResponse =
  415. (UA_CreateSessionResponse *)response;
  416. UA_NodeId_copy(&sessionResponse->authenticationToken,
  417. &client->authenticationToken);
  418. requestActivateSession(client, &requestId);
  419. }
  420. static UA_StatusCode
  421. requestSession(UA_Client *client, UA_UInt32 *requestId) {
  422. UA_CreateSessionRequest request;
  423. UA_CreateSessionRequest_init(&request);
  424. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  425. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  426. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  427. if(client->channel.localNonce.length != UA_SESSION_LOCALNONCELENGTH) {
  428. UA_ByteString_deleteMembers(&client->channel.localNonce);
  429. retval = UA_ByteString_allocBuffer(&client->channel.localNonce,
  430. UA_SESSION_LOCALNONCELENGTH);
  431. if(retval != UA_STATUSCODE_GOOD)
  432. return retval;
  433. }
  434. retval = client->channel.securityPolicy->symmetricModule.
  435. generateNonce(client->channel.securityPolicy, &client->channel.localNonce);
  436. if(retval != UA_STATUSCODE_GOOD)
  437. return retval;
  438. }
  439. request.requestHeader.requestHandle = ++client->requestHandle;
  440. request.requestHeader.timestamp = UA_DateTime_now();
  441. request.requestHeader.timeoutHint = 10000;
  442. UA_ByteString_copy(&client->channel.localNonce, &request.clientNonce);
  443. request.requestedSessionTimeout = client->config.requestedSessionTimeout;
  444. request.maxResponseMessageSize = UA_INT32_MAX;
  445. UA_String_copy(&client->endpointUrl, &request.endpointUrl);
  446. retval = UA_Client_sendAsyncRequest (
  447. client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  448. (UA_ClientAsyncServiceCallback) responseSessionCallback,
  449. &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE], NULL, requestId);
  450. UA_CreateSessionRequest_deleteMembers(&request);
  451. client->connectStatus = retval;
  452. return client->connectStatus;
  453. }
  454. UA_StatusCode
  455. UA_Client_connect_iterate(UA_Client *client) {
  456. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  457. "Client connect iterate");
  458. if (client->connection.state == UA_CONNECTION_ESTABLISHED){
  459. if(client->state < UA_CLIENTSTATE_WAITING_FOR_ACK) {
  460. client->connectStatus = sendHELMessage(client);
  461. if(client->connectStatus == UA_STATUSCODE_GOOD) {
  462. setClientState(client, UA_CLIENTSTATE_WAITING_FOR_ACK);
  463. } else {
  464. client->connection.close(&client->connection);
  465. client->connection.free(&client->connection);
  466. }
  467. return client->connectStatus;
  468. }
  469. }
  470. /* If server is not connected */
  471. if(client->connection.state == UA_CONNECTION_CLOSED) {
  472. client->connectStatus = UA_STATUSCODE_BADCONNECTIONCLOSED;
  473. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  474. "No connection to server.");
  475. }
  476. if(client->connectStatus != UA_STATUSCODE_GOOD) {
  477. client->connection.close(&client->connection);
  478. client->connection.free(&client->connection);
  479. }
  480. return client->connectStatus;
  481. }
  482. UA_StatusCode
  483. UA_Client_connect_async(UA_Client *client, const char *endpointUrl,
  484. UA_ClientAsyncServiceCallback callback,
  485. void *userdata) {
  486. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  487. "Client internal async");
  488. if(client->state >= UA_CLIENTSTATE_WAITING_FOR_ACK)
  489. return UA_STATUSCODE_GOOD;
  490. UA_ChannelSecurityToken_init(&client->channel.securityToken);
  491. client->channel.state = UA_SECURECHANNELSTATE_FRESH;
  492. client->endpointsHandshake = true;
  493. client->channel.sendSequenceNumber = 0;
  494. client->requestId = 0;
  495. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  496. client->connection = client->config.initConnectionFunc(
  497. client->config.localConnectionConfig,
  498. UA_STRING((char*)(uintptr_t)endpointUrl),
  499. client->config.timeout, &client->config.logger);
  500. if(client->connection.state != UA_CONNECTION_OPENING) {
  501. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  502. "Could not init async connection");
  503. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  504. goto cleanup;
  505. }
  506. UA_String_deleteMembers(&client->endpointUrl);
  507. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  508. if(!client->endpointUrl.data) {
  509. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  510. goto cleanup;
  511. }
  512. /* Set the channel SecurityMode if not done so far */
  513. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  514. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  515. /* Set the channel SecurityPolicy if not done so far */
  516. if(!client->channel.securityPolicy) {
  517. UA_ByteString remoteCertificate = UA_BYTESTRING_NULL;
  518. retval = UA_SecureChannel_setSecurityPolicy(&client->channel,
  519. &client->securityPolicy,
  520. &remoteCertificate);
  521. if(retval != UA_STATUSCODE_GOOD)
  522. goto cleanup;
  523. }
  524. client->asyncConnectCall.callback = callback;
  525. client->asyncConnectCall.userdata = userdata;
  526. if(!client->connection.connectCallbackID) {
  527. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  528. "Adding async connection callback");
  529. retval = UA_Client_addRepeatedCallback(
  530. client, client->config.pollConnectionFunc, &client->connection, 100.0,
  531. &client->connection.connectCallbackID);
  532. if(retval != UA_STATUSCODE_GOOD)
  533. goto cleanup;
  534. }
  535. retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  536. if(retval != UA_STATUSCODE_GOOD)
  537. goto cleanup;
  538. /* Delete async service. TODO: Move this from connect to the disconnect/cleanup phase */
  539. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  540. #ifdef UA_ENABLE_SUBSCRIPTIONS
  541. client->currentlyOutStandingPublishRequests = 0;
  542. #endif
  543. UA_NodeId_deleteMembers(&client->authenticationToken);
  544. /* Generate new local and remote key */
  545. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  546. if(retval != UA_STATUSCODE_GOOD)
  547. goto cleanup;
  548. return retval;
  549. cleanup:
  550. UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  551. "Failure during async connect");
  552. UA_Client_disconnect(client);
  553. return retval;
  554. }
  555. /* Async disconnection */
  556. static void
  557. sendCloseSecureChannelAsync(UA_Client *client, void *userdata,
  558. UA_UInt32 requestId, void *response) {
  559. UA_NodeId_deleteMembers (&client->authenticationToken);
  560. client->requestHandle = 0;
  561. UA_SecureChannel *channel = &client->channel;
  562. UA_CloseSecureChannelRequest request;
  563. UA_CloseSecureChannelRequest_init(&request);
  564. request.requestHeader.requestHandle = ++client->requestHandle;
  565. request.requestHeader.timestamp = UA_DateTime_now();
  566. request.requestHeader.timeoutHint = 10000;
  567. request.requestHeader.authenticationToken = client->authenticationToken;
  568. UA_SecureChannel_sendSymmetricMessage(
  569. channel, ++client->requestId, UA_MESSAGETYPE_CLO, &request,
  570. &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
  571. UA_SecureChannel_close(&client->channel);
  572. UA_SecureChannel_deleteMembers(&client->channel);
  573. }
  574. static void
  575. sendCloseSessionAsync(UA_Client *client, UA_UInt32 *requestId) {
  576. UA_CloseSessionRequest request;
  577. UA_CloseSessionRequest_init(&request);
  578. request.requestHeader.timestamp = UA_DateTime_now();
  579. request.requestHeader.timeoutHint = 10000;
  580. request.deleteSubscriptions = true;
  581. UA_Client_sendAsyncRequest(
  582. client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  583. (UA_ClientAsyncServiceCallback) sendCloseSecureChannelAsync,
  584. &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE], NULL, requestId);
  585. }
  586. UA_StatusCode
  587. UA_Client_disconnect_async(UA_Client *client, UA_UInt32 *requestId) {
  588. /* Is a session established? */
  589. if (client->state == UA_CLIENTSTATE_SESSION) {
  590. client->state = UA_CLIENTSTATE_SESSION_DISCONNECTED;
  591. sendCloseSessionAsync(client, requestId);
  592. }
  593. /* Close the TCP connection
  594. * shutdown and close (in tcp.c) are already async*/
  595. if (client->state >= UA_CLIENTSTATE_CONNECTED)
  596. client->connection.close(&client->connection);
  597. else
  598. UA_Client_removeRepeatedCallback(client, client->connection.connectCallbackID);
  599. #ifdef UA_ENABLE_SUBSCRIPTIONS
  600. // TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
  601. /* We need to clean up the subscriptions */
  602. UA_Client_Subscriptions_clean(client);
  603. #endif
  604. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  605. return UA_STATUSCODE_GOOD;
  606. }