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