ua_client.c 31 KB

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