ua_client_connect_async.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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(
  277. client->config.logger,
  278. UA_LOGCATEGORY_CLIENT,
  279. "ActivateSession failed with error code %s",
  280. UA_StatusCode_name(activateResponse->responseHeader.serviceResult));
  281. }
  282. client->connection.state = UA_CONNECTION_ESTABLISHED;
  283. setClientState(client, UA_CLIENTSTATE_SESSION);
  284. #ifdef UA_ENABLE_SUBSCRIPTIONS
  285. /* A new session has been created. We need to clean up the subscriptions */
  286. UA_Client_Subscriptions_clean(client);
  287. #endif
  288. /* call onConnect (client_async.c) callback */
  289. AsyncServiceCall ac = client->asyncConnectCall;
  290. ac.callback(client, ac.userdata, requestId + 1,
  291. &activateResponse->responseHeader.serviceResult);
  292. }
  293. static UA_StatusCode
  294. requestActivateSession (UA_Client *client, UA_UInt32 *requestId) {
  295. UA_ActivateSessionRequest request;
  296. UA_ActivateSessionRequest_init(&request);
  297. request.requestHeader.requestHandle = ++client->requestHandle;
  298. request.requestHeader.timestamp = UA_DateTime_now ();
  299. request.requestHeader.timeoutHint = 600000;
  300. /* Manual ExtensionObject encoding of the identityToken */
  301. if (client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE) {
  302. UA_AnonymousIdentityToken* identityToken =
  303. UA_AnonymousIdentityToken_new();
  304. UA_AnonymousIdentityToken_init (identityToken);
  305. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  306. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  307. request.userIdentityToken.content.decoded.type =
  308. &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  309. request.userIdentityToken.content.decoded.data = identityToken;
  310. } else {
  311. UA_UserNameIdentityToken* identityToken =
  312. UA_UserNameIdentityToken_new();
  313. UA_UserNameIdentityToken_init (identityToken);
  314. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  315. UA_String_copy(&client->username, &identityToken->userName);
  316. UA_String_copy(&client->password, &identityToken->password);
  317. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  318. request.userIdentityToken.content.decoded.type =
  319. &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  320. request.userIdentityToken.content.decoded.data = identityToken;
  321. }
  322. /* This function call is to prepare a client signature */
  323. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  324. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  325. signActivateSessionRequest(&client->channel, &request);
  326. }
  327. UA_StatusCode retval = UA_Client_sendAsyncRequest (
  328. client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  329. (UA_ClientAsyncServiceCallback) responseActivateSession,
  330. &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE], NULL, requestId);
  331. UA_ActivateSessionRequest_deleteMembers(&request);
  332. client->connectStatus = retval;
  333. return retval;
  334. }
  335. /* Combination of UA_Client_getEndpointsInternal and getEndpoints */
  336. static void
  337. responseGetEndpoints(UA_Client *client, void *userdata, UA_UInt32 requestId,
  338. void *response) {
  339. UA_EndpointDescription* endpointArray = NULL;
  340. size_t endpointArraySize = 0;
  341. UA_GetEndpointsResponse* resp;
  342. resp = (UA_GetEndpointsResponse*)response;
  343. if (resp->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  344. client->connectStatus = resp->responseHeader.serviceResult;
  345. UA_LOG_ERROR (client->config.logger, UA_LOGCATEGORY_CLIENT,
  346. "GetEndpointRequest failed with error code %s",
  347. UA_StatusCode_name (client->connectStatus));
  348. UA_GetEndpointsResponse_deleteMembers(resp);
  349. return;
  350. }
  351. endpointArray = resp->endpoints;
  352. endpointArraySize = resp->endpointsSize;
  353. resp->endpoints = NULL;
  354. resp->endpointsSize = 0;
  355. UA_Boolean endpointFound = false;
  356. UA_Boolean tokenFound = false;
  357. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  358. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  359. "Transport/uatcp-uasc-uabinary");
  360. // TODO: compare endpoint information with client->endpointUri
  361. for(size_t i = 0; i < endpointArraySize; ++i) {
  362. UA_EndpointDescription* endpoint = &endpointArray[i];
  363. /* look out for binary transport endpoints */
  364. /* Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  365. if(endpoint->transportProfileUri.length != 0
  366. && !UA_String_equal (&endpoint->transportProfileUri,
  367. &binaryTransport))
  368. continue;
  369. /* Look for an endpoint corresponding to the client security policy */
  370. if(!UA_String_equal(&endpoint->securityPolicyUri, &client->securityPolicy.policyUri))
  371. continue;
  372. endpointFound = true;
  373. /* Look for a user token policy with an anonymous token */
  374. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  375. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  376. /* Usertokens also have a security policy... */
  377. if(userToken->securityPolicyUri.length > 0
  378. && !UA_String_equal(&userToken->securityPolicyUri,
  379. &securityNone))
  380. continue;
  381. /* UA_CLIENTAUTHENTICATION_NONE == UA_USERTOKENTYPE_ANONYMOUS
  382. * UA_CLIENTAUTHENTICATION_USERNAME == UA_USERTOKENTYPE_USERNAME
  383. * TODO: Check equivalence for other types when adding the support */
  384. if((int)client->authenticationMethod
  385. != (int)userToken->tokenType)
  386. continue;
  387. /* Endpoint with matching usertokenpolicy found */
  388. tokenFound = true;
  389. UA_UserTokenPolicy_deleteMembers(&client->token);
  390. UA_UserTokenPolicy_copy(userToken, &client->token);
  391. break;
  392. }
  393. }
  394. UA_Array_delete(endpointArray, endpointArraySize,
  395. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  396. if(!endpointFound) {
  397. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  398. "No suitable endpoint found");
  399. client->connectStatus = UA_STATUSCODE_BADINTERNALERROR;
  400. } else if(!tokenFound) {
  401. UA_LOG_ERROR(
  402. client->config.logger, UA_LOGCATEGORY_CLIENT,
  403. "No suitable UserTokenPolicy found for the possible endpoints");
  404. client->connectStatus = UA_STATUSCODE_BADINTERNALERROR;
  405. }
  406. requestSession(client, &requestId);
  407. }
  408. static UA_StatusCode
  409. requestGetEndpoints(UA_Client *client, UA_UInt32 *requestId) {
  410. UA_GetEndpointsRequest request;
  411. UA_GetEndpointsRequest_init(&request);
  412. request.requestHeader.timestamp = UA_DateTime_now();
  413. request.requestHeader.timeoutHint = 10000;
  414. /* assume the endpointurl outlives the service call */
  415. UA_String_copy (&client->endpointUrl, &request.endpointUrl);
  416. client->connectStatus = UA_Client_sendAsyncRequest(
  417. client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  418. (UA_ClientAsyncServiceCallback) responseGetEndpoints,
  419. &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE], NULL, requestId);
  420. UA_GetEndpointsRequest_deleteMembers(&request);
  421. return client->connectStatus;
  422. }
  423. static void
  424. responseSessionCallback(UA_Client *client, void *userdata, UA_UInt32 requestId,
  425. void *response) {
  426. UA_CreateSessionResponse *sessionResponse =
  427. (UA_CreateSessionResponse *)response;
  428. UA_NodeId_copy(&sessionResponse->authenticationToken,
  429. &client->authenticationToken);
  430. requestActivateSession(client, &requestId);
  431. }
  432. static UA_StatusCode
  433. requestSession(UA_Client *client, UA_UInt32 *requestId) {
  434. UA_CreateSessionRequest request;
  435. UA_CreateSessionRequest_init(&request);
  436. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  437. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  438. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  439. if(client->channel.localNonce.length != UA_SESSION_LOCALNONCELENGTH) {
  440. UA_ByteString_deleteMembers(&client->channel.localNonce);
  441. retval = UA_ByteString_allocBuffer(&client->channel.localNonce,
  442. UA_SESSION_LOCALNONCELENGTH);
  443. if(retval != UA_STATUSCODE_GOOD)
  444. return retval;
  445. }
  446. retval = client->channel.securityPolicy->symmetricModule.
  447. generateNonce(client->channel.securityPolicy, &client->channel.localNonce);
  448. if(retval != UA_STATUSCODE_GOOD)
  449. return retval;
  450. }
  451. request.requestHeader.requestHandle = ++client->requestHandle;
  452. request.requestHeader.timestamp = UA_DateTime_now();
  453. request.requestHeader.timeoutHint = 10000;
  454. UA_ByteString_copy(&client->channel.localNonce, &request.clientNonce);
  455. request.requestedSessionTimeout = 1200000;
  456. request.maxResponseMessageSize = UA_INT32_MAX;
  457. UA_String_copy(&client->endpointUrl, &request.endpointUrl);
  458. retval = UA_Client_sendAsyncRequest (
  459. client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  460. (UA_ClientAsyncServiceCallback) responseSessionCallback,
  461. &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE], NULL, requestId);
  462. UA_CreateSessionRequest_deleteMembers(&request);
  463. client->connectStatus = retval;
  464. return client->connectStatus;
  465. }
  466. UA_StatusCode
  467. UA_Client_connect_iterate(UA_Client *client) {
  468. UA_LOG_TRACE(client->config.logger, UA_LOGCATEGORY_CLIENT,
  469. "Client connect iterate");
  470. if (client->connection.state == UA_CONNECTION_ESTABLISHED){
  471. if (client->state < UA_CLIENTSTATE_WAITING_FOR_ACK)
  472. return sendHELMessage(client);
  473. }
  474. /* If server is not connected */
  475. if (client->connection.state == UA_CONNECTION_CLOSED) {
  476. client->connectStatus = UA_STATUSCODE_BADCONNECTIONCLOSED;
  477. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_NETWORK,
  478. "No connection to server.");
  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, endpointUrl,
  498. client->config.timeout, client->config.logger);
  499. if(client->connection.state != UA_CONNECTION_OPENING) {
  500. UA_LOG_TRACE(client->config.logger, UA_LOGCATEGORY_CLIENT,
  501. "Could not init async connection");
  502. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  503. goto cleanup;
  504. }
  505. UA_String_deleteMembers(&client->endpointUrl);
  506. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  507. if(!client->endpointUrl.data) {
  508. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  509. goto cleanup;
  510. }
  511. /* Set the channel SecurityMode if not done so far */
  512. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  513. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  514. /* Set the channel SecurityPolicy if not done so far */
  515. if(!client->channel.securityPolicy) {
  516. UA_ByteString remoteCertificate = UA_BYTESTRING_NULL;
  517. retval = UA_SecureChannel_setSecurityPolicy(&client->channel,
  518. &client->securityPolicy,
  519. &remoteCertificate);
  520. if(retval != UA_STATUSCODE_GOOD)
  521. goto cleanup;
  522. }
  523. client->asyncConnectCall.callback = callback;
  524. client->asyncConnectCall.userdata = userdata;
  525. if(!client->connection.connectCallbackID) {
  526. UA_LOG_TRACE(client->config.logger, UA_LOGCATEGORY_CLIENT,
  527. "Adding async connection callback");
  528. retval = UA_Client_addRepeatedCallback(
  529. client, client->config.pollConnectionFunc, &client->connection, 100,
  530. &client->connection.connectCallbackID);
  531. if(retval != UA_STATUSCODE_GOOD)
  532. goto cleanup;
  533. }
  534. retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  535. if(retval != UA_STATUSCODE_GOOD)
  536. goto cleanup;
  537. /* Delete async service. TODO: Move this from connect to the disconnect/cleanup phase */
  538. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  539. #ifdef UA_ENABLE_SUBSCRIPTIONS
  540. client->currentlyOutStandingPublishRequests = 0;
  541. #endif
  542. UA_NodeId_deleteMembers(&client->authenticationToken);
  543. /* Generate new local and remote key */
  544. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  545. if(retval != UA_STATUSCODE_GOOD)
  546. goto cleanup;
  547. return retval;
  548. cleanup:
  549. UA_LOG_TRACE(client->config.logger, UA_LOGCATEGORY_CLIENT,
  550. "Failure during async connect");
  551. UA_Client_disconnect(client);
  552. return retval;
  553. }
  554. /* Async disconnection */
  555. static void
  556. sendCloseSecureChannelAsync(UA_Client *client, void *userdata,
  557. UA_UInt32 requestId, void *response) {
  558. UA_NodeId_deleteMembers (&client->authenticationToken);
  559. client->requestHandle = 0;
  560. UA_SecureChannel *channel = &client->channel;
  561. UA_CloseSecureChannelRequest request;
  562. UA_CloseSecureChannelRequest_init(&request);
  563. request.requestHeader.requestHandle = ++client->requestHandle;
  564. request.requestHeader.timestamp = UA_DateTime_now();
  565. request.requestHeader.timeoutHint = 10000;
  566. request.requestHeader.authenticationToken = client->authenticationToken;
  567. UA_SecureChannel_sendSymmetricMessage(
  568. channel, ++client->requestId, UA_MESSAGETYPE_CLO, &request,
  569. &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
  570. UA_SecureChannel_close(&client->channel);
  571. UA_SecureChannel_deleteMembers(&client->channel);
  572. }
  573. static void
  574. sendCloseSessionAsync(UA_Client *client, UA_UInt32 *requestId) {
  575. UA_CloseSessionRequest request;
  576. UA_CloseSessionRequest_init(&request);
  577. request.requestHeader.timestamp = UA_DateTime_now();
  578. request.requestHeader.timeoutHint = 10000;
  579. request.deleteSubscriptions = true;
  580. UA_Client_sendAsyncRequest(
  581. client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  582. (UA_ClientAsyncServiceCallback) sendCloseSecureChannelAsync,
  583. &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE], NULL, requestId);
  584. }
  585. UA_StatusCode
  586. UA_Client_disconnect_async(UA_Client *client, UA_UInt32 *requestId) {
  587. /* Is a session established? */
  588. if (client->state == UA_CLIENTSTATE_SESSION) {
  589. client->state = UA_CLIENTSTATE_SESSION_DISCONNECTED;
  590. sendCloseSessionAsync(client, requestId);
  591. }
  592. /* Close the TCP connection
  593. * shutdown and close (in tcp.c) are already async*/
  594. if (client->state >= UA_CLIENTSTATE_CONNECTED)
  595. client->connection.close(&client->connection);
  596. else
  597. UA_Client_removeRepeatedCallback(client, client->connection.connectCallbackID);
  598. #ifdef UA_ENABLE_SUBSCRIPTIONS
  599. // TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
  600. /* We need to clean up the subscriptions */
  601. UA_Client_Subscriptions_clean(client);
  602. #endif
  603. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  604. return UA_STATUSCODE_GOOD;
  605. }