ua_client.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. #include "ua_util.h"
  2. #include "ua_client.h"
  3. #include "ua_client_highlevel.h"
  4. #include "ua_client_internal.h"
  5. #include "ua_connection_internal.h"
  6. #include "ua_types_generated.h"
  7. #include "ua_nodeids.h"
  8. #include "ua_types_encoding_binary.h"
  9. #include "ua_transport_generated.h"
  10. #include "ua_types_generated_encoding_binary.h"
  11. #include "ua_transport_generated_encoding_binary.h"
  12. /*********************/
  13. /* Create and Delete */
  14. /*********************/
  15. static void UA_Client_init(UA_Client* client, UA_ClientConfig config) {
  16. client->state = UA_CLIENTSTATE_READY;
  17. UA_Connection_init(&client->connection);
  18. UA_SecureChannel_init(&client->channel);
  19. client->channel.connection = &client->connection;
  20. UA_String_init(&client->endpointUrl);
  21. client->requestId = 0;
  22. client->authenticationMethod = UA_CLIENTAUTHENTICATION_NONE;
  23. UA_String_init(&client->username);
  24. UA_String_init(&client->password);
  25. UA_NodeId_init(&client->authenticationToken);
  26. client->requestHandle = 0;
  27. client->config = config;
  28. client->scRenewAt = 0;
  29. #ifdef UA_ENABLE_SUBSCRIPTIONS
  30. client->monitoredItemHandles = 0;
  31. LIST_INIT(&client->pendingNotificationsAcks);
  32. LIST_INIT(&client->subscriptions);
  33. #endif
  34. }
  35. UA_Client * UA_Client_new(UA_ClientConfig config) {
  36. UA_Client *client = UA_calloc(1, sizeof(UA_Client));
  37. if(!client)
  38. return NULL;
  39. UA_Client_init(client, config);
  40. return client;
  41. }
  42. static void UA_Client_deleteMembers(UA_Client* client) {
  43. UA_Client_disconnect(client);
  44. UA_Connection_deleteMembers(&client->connection);
  45. UA_SecureChannel_deleteMembersCleanup(&client->channel);
  46. if(client->endpointUrl.data)
  47. UA_String_deleteMembers(&client->endpointUrl);
  48. UA_UserTokenPolicy_deleteMembers(&client->token);
  49. if(client->username.data)
  50. UA_String_deleteMembers(&client->username);
  51. if(client->password.data)
  52. UA_String_deleteMembers(&client->password);
  53. #ifdef UA_ENABLE_SUBSCRIPTIONS
  54. UA_Client_NotificationsAckNumber *n, *tmp;
  55. LIST_FOREACH_SAFE(n, &client->pendingNotificationsAcks, listEntry, tmp) {
  56. LIST_REMOVE(n, listEntry);
  57. free(n);
  58. }
  59. UA_Client_Subscription *sub, *tmps;
  60. LIST_FOREACH_SAFE(sub, &client->subscriptions, listEntry, tmps)
  61. UA_Client_Subscriptions_forceDelete(client, sub); /* force local removal */
  62. #endif
  63. }
  64. void UA_Client_reset(UA_Client* client){
  65. UA_Client_deleteMembers(client);
  66. UA_Client_init(client, client->config);
  67. }
  68. void UA_Client_delete(UA_Client* client){
  69. UA_Client_deleteMembers(client);
  70. UA_free(client);
  71. }
  72. UA_ClientState UA_EXPORT UA_Client_getState(UA_Client *client) {
  73. if(!client)
  74. return UA_CLIENTSTATE_ERRORED;
  75. return client->state;
  76. }
  77. /*************************/
  78. /* Manage the Connection */
  79. /*************************/
  80. static UA_StatusCode HelAckHandshake(UA_Client *client) {
  81. UA_TcpMessageHeader messageHeader;
  82. messageHeader.messageTypeAndChunkType = UA_CHUNKTYPE_FINAL + UA_MESSAGETYPE_HEL;
  83. UA_TcpHelloMessage hello;
  84. UA_String_copy(&client->endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  85. UA_Connection *conn = &client->connection;
  86. hello.maxChunkCount = conn->localConf.maxChunkCount;
  87. hello.maxMessageSize = conn->localConf.maxMessageSize;
  88. hello.protocolVersion = conn->localConf.protocolVersion;
  89. hello.receiveBufferSize = conn->localConf.recvBufferSize;
  90. hello.sendBufferSize = conn->localConf.sendBufferSize;
  91. UA_ByteString message;
  92. UA_StatusCode retval;
  93. retval = client->connection.getSendBuffer(&client->connection, client->connection.remoteConf.recvBufferSize, &message);
  94. if(retval != UA_STATUSCODE_GOOD)
  95. return retval;
  96. size_t offset = 8;
  97. retval |= UA_TcpHelloMessage_encodeBinary(&hello, &message, &offset);
  98. messageHeader.messageSize = (UA_UInt32)offset;
  99. offset = 0;
  100. retval |= UA_TcpMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  101. UA_TcpHelloMessage_deleteMembers(&hello);
  102. if(retval != UA_STATUSCODE_GOOD) {
  103. client->connection.releaseSendBuffer(&client->connection, &message);
  104. return retval;
  105. }
  106. message.length = messageHeader.messageSize;
  107. retval = client->connection.send(&client->connection, &message);
  108. if(retval != UA_STATUSCODE_GOOD) {
  109. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_NETWORK, "Sending HEL failed");
  110. return retval;
  111. }
  112. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_NETWORK, "Sent HEL message");
  113. UA_ByteString reply;
  114. UA_ByteString_init(&reply);
  115. UA_Boolean realloced = false;
  116. do {
  117. retval = client->connection.recv(&client->connection, &reply, client->config.timeout);
  118. retval |= UA_Connection_completeMessages(&client->connection, &reply, &realloced);
  119. if(retval != UA_STATUSCODE_GOOD) {
  120. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_NETWORK, "Receiving ACK message failed");
  121. return retval;
  122. }
  123. } while(reply.length == 0);
  124. offset = 0;
  125. UA_TcpMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  126. UA_TcpAcknowledgeMessage ackMessage;
  127. retval = UA_TcpAcknowledgeMessage_decodeBinary(&reply, &offset, &ackMessage);
  128. if(!realloced)
  129. client->connection.releaseRecvBuffer(&client->connection, &reply);
  130. else
  131. UA_ByteString_deleteMembers(&reply);
  132. if(retval != UA_STATUSCODE_GOOD) {
  133. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_NETWORK, "Decoding ACK message failed");
  134. return retval;
  135. }
  136. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  137. /* TODO: verify that remote and local configurations match, adjust local configuration in the other case */
  138. conn->remoteConf.maxChunkCount = ackMessage.maxChunkCount;
  139. conn->remoteConf.maxMessageSize = ackMessage.maxMessageSize;
  140. conn->remoteConf.protocolVersion = ackMessage.protocolVersion;
  141. conn->remoteConf.recvBufferSize = ackMessage.receiveBufferSize;
  142. conn->remoteConf.sendBufferSize = ackMessage.sendBufferSize;
  143. conn->state = UA_CONNECTION_ESTABLISHED;
  144. if (conn->remoteConf.recvBufferSize < conn->localConf.sendBufferSize)
  145. conn->localConf.sendBufferSize = conn->remoteConf.recvBufferSize;
  146. return UA_STATUSCODE_GOOD;
  147. }
  148. static UA_StatusCode SecureChannelHandshake(UA_Client *client, UA_Boolean renew) {
  149. /* Check if sc is still valid */
  150. if(renew && client->scRenewAt - UA_DateTime_now() > 0)
  151. return UA_STATUSCODE_GOOD;
  152. UA_Connection *c = &client->connection;
  153. if(c->state != UA_CONNECTION_ESTABLISHED)
  154. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  155. UA_SecureConversationMessageHeader messageHeader;
  156. messageHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  157. if(renew)
  158. messageHeader.secureChannelId = client->channel.securityToken.channelId;
  159. else
  160. messageHeader.secureChannelId = 0;
  161. UA_SequenceHeader seqHeader;
  162. seqHeader.sequenceNumber = ++client->channel.sendSequenceNumber;
  163. seqHeader.requestId = ++client->requestId;
  164. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  165. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  166. asymHeader.securityPolicyUri = UA_STRING_ALLOC("http://opcfoundation.org/UA/SecurityPolicy#None");
  167. /* id of opensecurechannelrequest */
  168. UA_NodeId requestType = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  169. UA_OpenSecureChannelRequest opnSecRq;
  170. UA_OpenSecureChannelRequest_init(&opnSecRq);
  171. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  172. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  173. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  174. if(renew) {
  175. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  176. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to renew the SecureChannel");
  177. } else {
  178. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  179. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to open a SecureChannel");
  180. }
  181. UA_ByteString_copy(&client->channel.clientNonce, &opnSecRq.clientNonce);
  182. opnSecRq.securityMode = UA_MESSAGESECURITYMODE_NONE;
  183. UA_ByteString message;
  184. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  185. if(retval != UA_STATUSCODE_GOOD) {
  186. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  187. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  188. return retval;
  189. }
  190. size_t offset = 12;
  191. retval = UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &message, &offset);
  192. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  193. retval |= UA_NodeId_encodeBinary(&requestType, &message, &offset);
  194. retval |= UA_OpenSecureChannelRequest_encodeBinary(&opnSecRq, &message, &offset);
  195. messageHeader.messageHeader.messageSize = (UA_UInt32)offset;
  196. offset = 0;
  197. retval |= UA_SecureConversationMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  198. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  199. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  200. if(retval != UA_STATUSCODE_GOOD) {
  201. client->connection.releaseSendBuffer(&client->connection, &message);
  202. return retval;
  203. }
  204. message.length = messageHeader.messageHeader.messageSize;
  205. retval = client->connection.send(&client->connection, &message);
  206. if(retval != UA_STATUSCODE_GOOD)
  207. return retval;
  208. UA_ByteString reply;
  209. UA_ByteString_init(&reply);
  210. UA_Boolean realloced = false;
  211. do {
  212. retval = c->recv(c, &reply, client->config.timeout);
  213. retval |= UA_Connection_completeMessages(c, &reply, &realloced);
  214. if(retval != UA_STATUSCODE_GOOD) {
  215. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  216. "Receiving OpenSecureChannelResponse failed");
  217. return retval;
  218. }
  219. } while(reply.length == 0);
  220. offset = 0;
  221. UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  222. UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &asymHeader);
  223. UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  224. UA_NodeId_decodeBinary(&reply, &offset, &requestType);
  225. UA_NodeId expectedRequest = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE +
  226. UA_ENCODINGOFFSET_BINARY);
  227. if(!UA_NodeId_equal(&requestType, &expectedRequest)) {
  228. UA_ByteString_deleteMembers(&reply);
  229. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  230. UA_NodeId_deleteMembers(&requestType);
  231. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  232. "Reply answers the wrong request. Expected OpenSecureChannelResponse.");
  233. return UA_STATUSCODE_BADINTERNALERROR;
  234. }
  235. UA_OpenSecureChannelResponse response;
  236. UA_OpenSecureChannelResponse_init(&response);
  237. retval = UA_OpenSecureChannelResponse_decodeBinary(&reply, &offset, &response);
  238. if(!realloced)
  239. c->releaseRecvBuffer(c, &reply);
  240. else
  241. UA_ByteString_deleteMembers(&reply);
  242. if(retval != UA_STATUSCODE_GOOD) {
  243. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  244. "Decoding OpenSecureChannelResponse failed");
  245. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  246. UA_OpenSecureChannelResponse_init(&response);
  247. response.responseHeader.serviceResult = retval;
  248. return retval;
  249. }
  250. retval = response.responseHeader.serviceResult;
  251. if(retval == UA_STATUSCODE_GOOD) {
  252. /* Response.securityToken.revisedLifetime is UInt32 we need to cast it
  253. to DateTime=Int64 we take 75% of lifetime to start renewing as
  254. described in standard */
  255. client->scRenewAt = UA_DateTime_now() +
  256. (UA_DateTime)(response.securityToken.revisedLifetime * (UA_Double)UA_MSEC_TO_DATETIME * 0.75);
  257. /* Replace the old nonce */
  258. UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
  259. UA_ChannelSecurityToken_copy(&response.securityToken, &client->channel.securityToken);
  260. UA_ByteString_deleteMembers(&client->channel.serverNonce);
  261. UA_ByteString_copy(&response.serverNonce, &client->channel.serverNonce);
  262. if(renew)
  263. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel renewed");
  264. else
  265. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel opened");
  266. } else {
  267. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel could "
  268. "not be opened / renewed with statuscode %i", retval);
  269. }
  270. UA_OpenSecureChannelResponse_deleteMembers(&response);
  271. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  272. return retval;
  273. }
  274. static UA_StatusCode ActivateSession(UA_Client *client) {
  275. UA_ActivateSessionRequest request;
  276. UA_ActivateSessionRequest_init(&request);
  277. request.requestHeader.requestHandle = ++client->requestHandle;
  278. request.requestHeader.authenticationToken = client->authenticationToken;
  279. request.requestHeader.timestamp = UA_DateTime_now();
  280. request.requestHeader.timeoutHint = 600000;
  281. //manual ExtensionObject encoding of the identityToken
  282. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE) {
  283. UA_AnonymousIdentityToken* identityToken = UA_malloc(sizeof(UA_AnonymousIdentityToken));
  284. UA_AnonymousIdentityToken_init(identityToken);
  285. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  286. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  287. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  288. request.userIdentityToken.content.decoded.data = identityToken;
  289. } else {
  290. UA_UserNameIdentityToken* identityToken = UA_malloc(sizeof(UA_UserNameIdentityToken));
  291. UA_UserNameIdentityToken_init(identityToken);
  292. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  293. UA_String_copy(&client->username, &identityToken->userName);
  294. UA_String_copy(&client->password, &identityToken->password);
  295. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  296. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  297. request.userIdentityToken.content.decoded.data = identityToken;
  298. }
  299. UA_ActivateSessionResponse response;
  300. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  301. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  302. if(response.responseHeader.serviceResult) {
  303. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  304. "ActivateSession failed with statuscode 0x%08x", response.responseHeader.serviceResult);
  305. }
  306. UA_ActivateSessionRequest_deleteMembers(&request);
  307. UA_ActivateSessionResponse_deleteMembers(&response);
  308. return response.responseHeader.serviceResult; // not deleted
  309. }
  310. /**
  311. * Gets a list of endpoints
  312. * Memory is allocated for endpointDescription array
  313. */
  314. static UA_StatusCode
  315. GetEndpoints(UA_Client *client, size_t* endpointDescriptionsSize, UA_EndpointDescription** endpointDescriptions) {
  316. UA_GetEndpointsRequest request;
  317. UA_GetEndpointsRequest_init(&request);
  318. request.requestHeader.authenticationToken = client->authenticationToken;
  319. request.requestHeader.timestamp = UA_DateTime_now();
  320. request.requestHeader.timeoutHint = 10000;
  321. request.endpointUrl = client->endpointUrl; // assume the endpointurl outlives the service call
  322. UA_GetEndpointsResponse response;
  323. UA_GetEndpointsResponse_init(&response);
  324. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  325. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  326. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  327. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  328. "GetEndpointRequest failed with statuscode 0x%08x", response.responseHeader.serviceResult);
  329. UA_GetEndpointsResponse_deleteMembers(&response);
  330. return response.responseHeader.serviceResult;
  331. }
  332. *endpointDescriptionsSize = response.endpointsSize;
  333. *endpointDescriptions = UA_Array_new(response.endpointsSize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  334. for(size_t i=0;i<response.endpointsSize;i++)
  335. UA_EndpointDescription_copy(&response.endpoints[i], &(*endpointDescriptions)[i]);
  336. UA_GetEndpointsResponse_deleteMembers(&response);
  337. return UA_STATUSCODE_GOOD;
  338. }
  339. static UA_StatusCode EndpointsHandshake(UA_Client *client) {
  340. UA_EndpointDescription* endpointArray = NULL;
  341. size_t endpointArraySize = 0;
  342. UA_StatusCode retval = GetEndpoints(client, &endpointArraySize, &endpointArray);
  343. if(retval != UA_STATUSCODE_GOOD)
  344. return retval;
  345. UA_Boolean endpointFound = false;
  346. UA_Boolean tokenFound = false;
  347. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  348. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");
  349. //TODO: compare endpoint information with client->endpointUri
  350. for(size_t i = 0; i < endpointArraySize; i++) {
  351. UA_EndpointDescription* endpoint = &endpointArray[i];
  352. /* look out for binary transport endpoints */
  353. //NODE: Siemens returns empty ProfileUrl, we will accept it as binary
  354. if(endpoint->transportProfileUri.length!=0 && !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  355. continue;
  356. /* look out for an endpoint without security */
  357. if(!UA_String_equal(&endpoint->securityPolicyUri, &securityNone))
  358. continue;
  359. endpointFound = true;
  360. /* endpoint with no security found */
  361. /* look for a user token policy with an anonymous token */
  362. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  363. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  364. //anonymous authentication
  365. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE){
  366. if(userToken->tokenType != UA_USERTOKENTYPE_ANONYMOUS)
  367. continue;
  368. }else{
  369. //username authentication
  370. if(userToken->tokenType != UA_USERTOKENTYPE_USERNAME)
  371. continue;
  372. }
  373. tokenFound = true;
  374. UA_UserTokenPolicy_copy(userToken, &client->token);
  375. break;
  376. }
  377. }
  378. UA_Array_delete(endpointArray, endpointArraySize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  379. if(!endpointFound) {
  380. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT, "No suitable endpoint found");
  381. return UA_STATUSCODE_BADINTERNALERROR;
  382. }
  383. if(!tokenFound) {
  384. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT, "No anonymous token found");
  385. return UA_STATUSCODE_BADINTERNALERROR;
  386. }
  387. return retval;
  388. }
  389. static UA_StatusCode SessionHandshake(UA_Client *client) {
  390. UA_CreateSessionRequest request;
  391. UA_CreateSessionRequest_init(&request);
  392. // todo: is this needed for all requests?
  393. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  394. request.requestHeader.timestamp = UA_DateTime_now();
  395. request.requestHeader.timeoutHint = 10000;
  396. UA_ByteString_copy(&client->channel.clientNonce, &request.clientNonce);
  397. request.requestedSessionTimeout = 1200000;
  398. request.maxResponseMessageSize = UA_INT32_MAX;
  399. UA_CreateSessionResponse response;
  400. UA_CreateSessionResponse_init(&response);
  401. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  402. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  403. UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  404. UA_CreateSessionRequest_deleteMembers(&request);
  405. UA_CreateSessionResponse_deleteMembers(&response);
  406. return response.responseHeader.serviceResult; // not deleted
  407. }
  408. static UA_StatusCode CloseSession(UA_Client *client) {
  409. UA_CloseSessionRequest request;
  410. UA_CloseSessionRequest_init(&request);
  411. request.requestHeader.timestamp = UA_DateTime_now();
  412. request.requestHeader.timeoutHint = 10000;
  413. request.deleteSubscriptions = true;
  414. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  415. UA_CloseSessionResponse response;
  416. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  417. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  418. UA_CloseSessionRequest_deleteMembers(&request);
  419. UA_CloseSessionResponse_deleteMembers(&response);
  420. return response.responseHeader.serviceResult; // not deleted
  421. }
  422. static UA_StatusCode CloseSecureChannel(UA_Client *client) {
  423. UA_SecureChannel *channel = &client->channel;
  424. UA_CloseSecureChannelRequest request;
  425. UA_CloseSecureChannelRequest_init(&request);
  426. request.requestHeader.requestHandle = ++client->requestHandle;
  427. request.requestHeader.timestamp = UA_DateTime_now();
  428. request.requestHeader.timeoutHint = 10000;
  429. request.requestHeader.authenticationToken = client->authenticationToken;
  430. UA_SecureConversationMessageHeader msgHeader;
  431. msgHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_CLO + UA_CHUNKTYPE_FINAL;
  432. msgHeader.secureChannelId = client->channel.securityToken.channelId;
  433. UA_SymmetricAlgorithmSecurityHeader symHeader;
  434. symHeader.tokenId = channel->securityToken.tokenId;
  435. UA_SequenceHeader seqHeader;
  436. seqHeader.sequenceNumber = ++channel->sendSequenceNumber;
  437. seqHeader.requestId = ++client->requestId;
  438. UA_NodeId typeId = UA_NODEID_NUMERIC(0, UA_NS0ID_CLOSESECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  439. UA_ByteString message;
  440. UA_Connection *c = &client->connection;
  441. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  442. if(retval != UA_STATUSCODE_GOOD)
  443. return retval;
  444. size_t offset = 12;
  445. retval |= UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symHeader, &message, &offset);
  446. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  447. retval |= UA_NodeId_encodeBinary(&typeId, &message, &offset);
  448. retval |= UA_encodeBinary(&request, &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST], NULL,
  449. NULL, &message, &offset);
  450. msgHeader.messageHeader.messageSize = (UA_UInt32)offset;
  451. offset = 0;
  452. retval |= UA_SecureConversationMessageHeader_encodeBinary(&msgHeader, &message, &offset);
  453. if(retval == UA_STATUSCODE_GOOD) {
  454. message.length = msgHeader.messageHeader.messageSize;
  455. retval = client->connection.send(&client->connection, &message);
  456. } else {
  457. client->connection.releaseSendBuffer(&client->connection, &message);
  458. }
  459. client->connection.close(&client->connection);
  460. return retval;
  461. }
  462. UA_StatusCode
  463. UA_Client_getEndpoints(UA_Client *client, const char *serverUrl,
  464. size_t* endpointDescriptionsSize,
  465. UA_EndpointDescription** endpointDescriptions) {
  466. if(client->state == UA_CLIENTSTATE_CONNECTED)
  467. return UA_STATUSCODE_GOOD;
  468. if(client->state == UA_CLIENTSTATE_ERRORED)
  469. UA_Client_reset(client);
  470. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  471. client->connection = client->config.connectionFunc(UA_ConnectionConfig_standard, serverUrl,
  472. client->config.logger);
  473. if(client->connection.state != UA_CONNECTION_OPENING) {
  474. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  475. goto cleanup;
  476. }
  477. client->endpointUrl = UA_STRING_ALLOC(serverUrl);
  478. if(!client->endpointUrl.data) {
  479. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  480. goto cleanup;
  481. }
  482. client->connection.localConf = client->config.localConnectionConfig;
  483. retval = HelAckHandshake(client);
  484. if(retval == UA_STATUSCODE_GOOD)
  485. retval = SecureChannelHandshake(client, false);
  486. if(retval == UA_STATUSCODE_GOOD)
  487. retval = GetEndpoints(client, endpointDescriptionsSize, endpointDescriptions);
  488. /* always cleanup */
  489. cleanup:
  490. UA_Client_disconnect(client);
  491. UA_Client_reset(client);
  492. return retval;
  493. }
  494. UA_StatusCode
  495. UA_Client_connect_username(UA_Client *client, const char *endpointUrl,
  496. const char *username, const char *password){
  497. client->authenticationMethod=UA_CLIENTAUTHENTICATION_USERNAME;
  498. client->username = UA_STRING_ALLOC(username);
  499. client->password = UA_STRING_ALLOC(password);
  500. return UA_Client_connect(client, endpointUrl);
  501. }
  502. UA_StatusCode
  503. UA_Client_connect(UA_Client *client, const char *endpointUrl) {
  504. if(client->state == UA_CLIENTSTATE_CONNECTED)
  505. return UA_STATUSCODE_GOOD;
  506. if(client->state == UA_CLIENTSTATE_ERRORED) {
  507. UA_Client_reset(client);
  508. }
  509. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  510. client->connection = client->config.connectionFunc(UA_ConnectionConfig_standard, endpointUrl, client->config.logger);
  511. if(client->connection.state != UA_CONNECTION_OPENING) {
  512. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  513. goto cleanup;
  514. }
  515. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  516. if(!client->endpointUrl.data) {
  517. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  518. goto cleanup;
  519. }
  520. client->connection.localConf = client->config.localConnectionConfig;
  521. retval = HelAckHandshake(client);
  522. if(retval == UA_STATUSCODE_GOOD)
  523. retval = SecureChannelHandshake(client, false);
  524. if(retval == UA_STATUSCODE_GOOD)
  525. retval = EndpointsHandshake(client);
  526. if(retval == UA_STATUSCODE_GOOD)
  527. retval = SessionHandshake(client);
  528. if(retval == UA_STATUSCODE_GOOD)
  529. retval = ActivateSession(client);
  530. if(retval == UA_STATUSCODE_GOOD) {
  531. client->connection.state = UA_CONNECTION_ESTABLISHED;
  532. client->state = UA_CLIENTSTATE_CONNECTED;
  533. } else {
  534. goto cleanup;
  535. }
  536. return retval;
  537. cleanup:
  538. UA_Client_reset(client);
  539. return retval;
  540. }
  541. UA_StatusCode UA_Client_disconnect(UA_Client *client) {
  542. if(client->state != UA_CLIENTSTATE_CONNECTED)
  543. return UA_STATUSCODE_BADNOTCONNECTED;
  544. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  545. /* Is a session established? */
  546. if(client->channel.connection->state == UA_CONNECTION_ESTABLISHED &&
  547. !UA_NodeId_equal(&client->authenticationToken, &UA_NODEID_NULL))
  548. retval = CloseSession(client);
  549. /* Is a secure channel established? */
  550. if(client->channel.connection->state == UA_CONNECTION_ESTABLISHED)
  551. retval |= CloseSecureChannel(client);
  552. return retval;
  553. }
  554. UA_StatusCode UA_Client_manuallyRenewSecureChannel(UA_Client *client) {
  555. UA_StatusCode retval = SecureChannelHandshake(client, true);
  556. if(retval == UA_STATUSCODE_GOOD)
  557. client->state = UA_CLIENTSTATE_CONNECTED;
  558. return retval;
  559. }
  560. /****************/
  561. /* Raw Services */
  562. /****************/
  563. void __UA_Client_Service(UA_Client *client, const void *r, const UA_DataType *requestType,
  564. void *response, const UA_DataType *responseType) {
  565. /* Requests always begin witih a RequestHeader, therefore we can cast. */
  566. UA_RequestHeader *request = (void*)(uintptr_t)r;
  567. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  568. UA_init(response, responseType);
  569. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  570. /* make sure we have a valid session */
  571. retval = UA_Client_manuallyRenewSecureChannel(client);
  572. if(retval != UA_STATUSCODE_GOOD) {
  573. respHeader->serviceResult = retval;
  574. client->state = UA_CLIENTSTATE_ERRORED;
  575. return;
  576. }
  577. /* handling request parameters */
  578. UA_NodeId_copy(&client->authenticationToken, &request->authenticationToken);
  579. request->timestamp = UA_DateTime_now();
  580. request->requestHandle = ++client->requestHandle;
  581. /* Send the request */
  582. UA_UInt32 requestId = ++client->requestId;
  583. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  584. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  585. retval = UA_SecureChannel_sendBinaryMessage(&client->channel, requestId, request, requestType);
  586. if(retval != UA_STATUSCODE_GOOD) {
  587. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  588. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  589. else
  590. respHeader->serviceResult = retval;
  591. client->state = UA_CLIENTSTATE_ERRORED;
  592. return;
  593. }
  594. /* Retrieve the response */
  595. // Todo: push this into the generic securechannel implementation for client and server
  596. UA_ByteString reply;
  597. UA_ByteString_init(&reply);
  598. UA_Boolean realloced = false;
  599. do {
  600. retval = client->connection.recv(&client->connection, &reply, client->config.timeout);
  601. retval |= UA_Connection_completeMessages(&client->connection, &reply, &realloced);
  602. if(retval != UA_STATUSCODE_GOOD) {
  603. respHeader->serviceResult = retval;
  604. client->state = UA_CLIENTSTATE_ERRORED;
  605. return;
  606. }
  607. } while(!reply.data);
  608. size_t offset = 0;
  609. UA_SecureConversationMessageHeader msgHeader;
  610. retval |= UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &msgHeader);
  611. UA_SymmetricAlgorithmSecurityHeader symHeader;
  612. retval |= UA_SymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &symHeader);
  613. UA_SequenceHeader seqHeader;
  614. retval |= UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  615. UA_NodeId responseId;
  616. retval |= UA_NodeId_decodeBinary(&reply, &offset, &responseId);
  617. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, responseType->typeId.identifier.numeric +
  618. UA_ENCODINGOFFSET_BINARY);
  619. if(retval != UA_STATUSCODE_GOOD)
  620. goto finish;
  621. /* Todo: we need to demux responses since a publish responses may come at any time */
  622. if(!UA_NodeId_equal(&responseId, &expectedNodeId) || seqHeader.requestId != requestId) {
  623. if(responseId.identifier.numeric != UA_NS0ID_SERVICEFAULT + UA_ENCODINGOFFSET_BINARY) {
  624. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  625. "Reply answers the wrong request. Expected ns=%i,i=%i. But retrieved ns=%i,i=%i",
  626. expectedNodeId.namespaceIndex, expectedNodeId.identifier.numeric,
  627. responseId.namespaceIndex, responseId.identifier.numeric);
  628. respHeader->serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  629. } else
  630. retval = UA_decodeBinary(&reply, &offset, respHeader, &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  631. goto finish;
  632. }
  633. retval = UA_decodeBinary(&reply, &offset, response, responseType);
  634. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  635. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  636. finish:
  637. UA_SymmetricAlgorithmSecurityHeader_deleteMembers(&symHeader);
  638. if(!realloced)
  639. client->connection.releaseRecvBuffer(&client->connection, &reply);
  640. else
  641. UA_ByteString_deleteMembers(&reply);
  642. if(retval != UA_STATUSCODE_GOOD){
  643. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT, "Error receiving the response");
  644. client->state = UA_CLIENTSTATE_FAULTED;
  645. respHeader->serviceResult = retval;
  646. } else {
  647. client->state = UA_CLIENTSTATE_CONNECTED;
  648. }
  649. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  650. "Received a response of type %i", responseId.identifier.numeric);
  651. }