ua_client_connect_async.c 28 KB

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