ua_client_connect_async.c 30 KB

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