ua_client.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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 == NULL)
  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.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_HELF;
  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.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_OPNF;
  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, "Decoding OpenSecureChannelResponse failed");
  249. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  250. UA_OpenSecureChannelResponse_init(&response);
  251. response.responseHeader.serviceResult = retval;
  252. return retval;
  253. }
  254. //response.securityToken.revisedLifetime is UInt32 we need to cast it to DateTime=Int64
  255. //we take 75% of lifetime to start renewing as described in standard
  256. client->scRenewAt = UA_DateTime_now() +
  257. (UA_DateTime)(response.securityToken.revisedLifetime * (UA_Double)UA_MSEC_TO_DATETIME * 0.75);
  258. retval = response.responseHeader.serviceResult;
  259. if(retval != UA_STATUSCODE_GOOD)
  260. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel could not be opened / renewed");
  261. else {
  262. UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
  263. UA_ChannelSecurityToken_copy(&response.securityToken, &client->channel.securityToken);
  264. /* if the handshake is repeated, replace the old nonce */
  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. }
  272. UA_OpenSecureChannelResponse_deleteMembers(&response);
  273. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  274. return retval;
  275. }
  276. static UA_StatusCode ActivateSession(UA_Client *client) {
  277. UA_ActivateSessionRequest request;
  278. UA_ActivateSessionRequest_init(&request);
  279. request.requestHeader.requestHandle = 2; //TODO: is it a magic number?
  280. request.requestHeader.authenticationToken = client->authenticationToken;
  281. request.requestHeader.timestamp = UA_DateTime_now();
  282. request.requestHeader.timeoutHint = 600000;
  283. //manual ExtensionObject encoding of the identityToken
  284. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE){
  285. UA_AnonymousIdentityToken* identityToken = UA_malloc(sizeof(UA_AnonymousIdentityToken));
  286. UA_AnonymousIdentityToken_init(identityToken);
  287. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  288. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  289. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  290. request.userIdentityToken.content.decoded.data = identityToken;
  291. }else{
  292. UA_UserNameIdentityToken* identityToken = UA_malloc(sizeof(UA_UserNameIdentityToken));
  293. UA_UserNameIdentityToken_init(identityToken);
  294. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  295. UA_String_copy(&client->username, &identityToken->userName);
  296. UA_String_copy(&client->password, &identityToken->password);
  297. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  298. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  299. request.userIdentityToken.content.decoded.data = identityToken;
  300. }
  301. UA_ActivateSessionResponse response;
  302. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  303. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  304. UA_ActivateSessionRequest_deleteMembers(&request);
  305. UA_ActivateSessionResponse_deleteMembers(&response);
  306. return response.responseHeader.serviceResult; // not deleted
  307. }
  308. /**
  309. * Gets a list of endpoints
  310. * Memory is allocated for endpointDescription array
  311. */
  312. static UA_StatusCode
  313. GetEndpoints(UA_Client *client, size_t* endpointDescriptionsSize, UA_EndpointDescription** endpointDescriptions) {
  314. UA_GetEndpointsRequest request;
  315. UA_GetEndpointsRequest_init(&request);
  316. request.requestHeader.authenticationToken = client->authenticationToken;
  317. request.requestHeader.timestamp = UA_DateTime_now();
  318. request.requestHeader.timeoutHint = 10000;
  319. request.endpointUrl = client->endpointUrl; // assume the endpointurl outlives the service call
  320. UA_GetEndpointsResponse response;
  321. UA_GetEndpointsResponse_init(&response);
  322. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  323. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  324. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  325. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT, "GetEndpointRequest failed");
  326. UA_GetEndpointsResponse_deleteMembers(&response);
  327. return response.responseHeader.serviceResult;
  328. }
  329. *endpointDescriptionsSize = response.endpointsSize;
  330. *endpointDescriptions = UA_Array_new(response.endpointsSize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  331. for(size_t i=0;i<response.endpointsSize;i++)
  332. UA_EndpointDescription_copy(&response.endpoints[i], &(*endpointDescriptions)[i]);
  333. UA_GetEndpointsResponse_deleteMembers(&response);
  334. return UA_STATUSCODE_GOOD;
  335. }
  336. static UA_StatusCode EndpointsHandshake(UA_Client *client) {
  337. UA_EndpointDescription* endpointArray = NULL;
  338. size_t endpointArraySize = 0;
  339. UA_StatusCode retval = GetEndpoints(client, &endpointArraySize, &endpointArray);
  340. UA_Boolean endpointFound = false;
  341. UA_Boolean tokenFound = false;
  342. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  343. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");
  344. //TODO: compare endpoint information with client->endpointUri
  345. for(size_t i = 0; i < endpointArraySize; i++) {
  346. UA_EndpointDescription* endpoint = &endpointArray[i];
  347. /* look out for binary transport endpoints */
  348. //NODE: Siemens returns empty ProfileUrl, we will accept it as binary
  349. if(endpoint->transportProfileUri.length!=0 && !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  350. continue;
  351. /* look out for an endpoint without security */
  352. if(!UA_String_equal(&endpoint->securityPolicyUri, &securityNone))
  353. continue;
  354. endpointFound = true;
  355. /* endpoint with no security found */
  356. /* look for a user token policy with an anonymous token */
  357. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  358. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  359. //anonymous authentication
  360. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE){
  361. if(userToken->tokenType != UA_USERTOKENTYPE_ANONYMOUS)
  362. continue;
  363. }else{
  364. //username authentication
  365. if(userToken->tokenType != UA_USERTOKENTYPE_USERNAME)
  366. continue;
  367. }
  368. tokenFound = true;
  369. UA_UserTokenPolicy_copy(userToken, &client->token);
  370. break;
  371. }
  372. }
  373. UA_Array_delete(endpointArray, endpointArraySize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  374. if(!endpointFound) {
  375. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT, "No suitable endpoint found");
  376. return UA_STATUSCODE_BADINTERNALERROR;
  377. }
  378. if(!tokenFound) {
  379. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT, "No anonymous token found");
  380. return UA_STATUSCODE_BADINTERNALERROR;
  381. }
  382. return retval;
  383. }
  384. static UA_StatusCode SessionHandshake(UA_Client *client) {
  385. UA_CreateSessionRequest request;
  386. UA_CreateSessionRequest_init(&request);
  387. // todo: is this needed for all requests?
  388. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  389. request.requestHeader.timestamp = UA_DateTime_now();
  390. request.requestHeader.timeoutHint = 10000;
  391. UA_ByteString_copy(&client->channel.clientNonce, &request.clientNonce);
  392. request.requestedSessionTimeout = 1200000;
  393. request.maxResponseMessageSize = UA_INT32_MAX;
  394. UA_CreateSessionResponse response;
  395. UA_CreateSessionResponse_init(&response);
  396. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  397. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  398. UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  399. UA_CreateSessionRequest_deleteMembers(&request);
  400. UA_CreateSessionResponse_deleteMembers(&response);
  401. return response.responseHeader.serviceResult; // not deleted
  402. }
  403. static UA_StatusCode CloseSession(UA_Client *client) {
  404. UA_CloseSessionRequest request;
  405. UA_CloseSessionRequest_init(&request);
  406. request.requestHeader.timestamp = UA_DateTime_now();
  407. request.requestHeader.timeoutHint = 10000;
  408. request.deleteSubscriptions = true;
  409. UA_NodeId_copy(&client->authenticationToken, &request.requestHeader.authenticationToken);
  410. UA_CloseSessionResponse response;
  411. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  412. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  413. UA_CloseSessionRequest_deleteMembers(&request);
  414. UA_CloseSessionResponse_deleteMembers(&response);
  415. return response.responseHeader.serviceResult; // not deleted
  416. }
  417. static UA_StatusCode CloseSecureChannel(UA_Client *client) {
  418. UA_SecureChannel *channel = &client->channel;
  419. UA_CloseSecureChannelRequest request;
  420. UA_CloseSecureChannelRequest_init(&request);
  421. request.requestHeader.requestHandle = 1; //TODO: magic number?
  422. request.requestHeader.timestamp = UA_DateTime_now();
  423. request.requestHeader.timeoutHint = 10000;
  424. request.requestHeader.authenticationToken = client->authenticationToken;
  425. UA_SecureConversationMessageHeader msgHeader;
  426. msgHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_CLOF;
  427. msgHeader.secureChannelId = client->channel.securityToken.channelId;
  428. UA_SymmetricAlgorithmSecurityHeader symHeader;
  429. symHeader.tokenId = channel->securityToken.tokenId;
  430. UA_SequenceHeader seqHeader;
  431. seqHeader.sequenceNumber = ++channel->sequenceNumber;
  432. seqHeader.requestId = ++client->requestId;
  433. UA_NodeId typeId = UA_NODEID_NUMERIC(0, UA_NS0ID_CLOSESECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  434. UA_ByteString message;
  435. UA_Connection *c = &client->connection;
  436. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  437. if(retval != UA_STATUSCODE_GOOD)
  438. return retval;
  439. size_t offset = 12;
  440. retval |= UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symHeader, &message, &offset);
  441. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  442. retval |= UA_NodeId_encodeBinary(&typeId, &message, &offset);
  443. retval |= UA_encodeBinary(&request, &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST], &message, &offset);
  444. msgHeader.messageHeader.messageSize = (UA_UInt32)offset;
  445. offset = 0;
  446. retval |= UA_SecureConversationMessageHeader_encodeBinary(&msgHeader, &message, &offset);
  447. if(retval != UA_STATUSCODE_GOOD) {
  448. client->connection.releaseSendBuffer(&client->connection, &message);
  449. return retval;
  450. }
  451. message.length = msgHeader.messageHeader.messageSize;
  452. retval = client->connection.send(&client->connection, &message);
  453. return retval;
  454. }
  455. UA_StatusCode
  456. UA_Client_getEndpoints(UA_Client *client, const char *serverUrl,
  457. size_t* endpointDescriptionsSize,
  458. UA_EndpointDescription** endpointDescriptions) {
  459. if(client->state == UA_CLIENTSTATE_CONNECTED)
  460. return UA_STATUSCODE_GOOD;
  461. if(client->state == UA_CLIENTSTATE_ERRORED)
  462. UA_Client_reset(client);
  463. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  464. client->connection = client->config.connectionFunc(UA_ConnectionConfig_standard, serverUrl, client->config.logger);
  465. if(client->connection.state != UA_CONNECTION_OPENING) {
  466. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  467. goto cleanup;
  468. }
  469. client->endpointUrl = UA_STRING_ALLOC(serverUrl);
  470. if(!client->endpointUrl.data) {
  471. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  472. goto cleanup;
  473. }
  474. client->connection.localConf = client->config.localConnectionConfig;
  475. retval = HelAckHandshake(client);
  476. if(retval == UA_STATUSCODE_GOOD)
  477. retval = SecureChannelHandshake(client, false);
  478. if(retval == UA_STATUSCODE_GOOD)
  479. retval = GetEndpoints(client, endpointDescriptionsSize, endpointDescriptions);
  480. /* always cleanup */
  481. cleanup:
  482. UA_Client_reset(client);
  483. return retval;
  484. }
  485. UA_StatusCode
  486. UA_Client_connect_username(UA_Client *client, const char *endpointUrl,
  487. const char *username, const char *password){
  488. client->authenticationMethod=UA_CLIENTAUTHENTICATION_USERNAME;
  489. client->username = UA_STRING_ALLOC(username);
  490. client->password = UA_STRING_ALLOC(password);
  491. return UA_Client_connect(client, endpointUrl);
  492. }
  493. UA_StatusCode
  494. UA_Client_connect(UA_Client *client, const char *endpointUrl) {
  495. if(client->state == UA_CLIENTSTATE_CONNECTED)
  496. return UA_STATUSCODE_GOOD;
  497. if(client->state == UA_CLIENTSTATE_ERRORED) {
  498. UA_Client_reset(client);
  499. }
  500. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  501. client->connection = client->config.connectionFunc(UA_ConnectionConfig_standard, endpointUrl, client->config.logger);
  502. if(client->connection.state != UA_CONNECTION_OPENING) {
  503. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  504. goto cleanup;
  505. }
  506. client->endpointUrl = UA_STRING_ALLOC(endpointUrl);
  507. if(!client->endpointUrl.data) {
  508. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  509. goto cleanup;
  510. }
  511. client->connection.localConf = client->config.localConnectionConfig;
  512. retval = HelAckHandshake(client);
  513. if(retval == UA_STATUSCODE_GOOD)
  514. retval = SecureChannelHandshake(client, false);
  515. if(retval == UA_STATUSCODE_GOOD)
  516. retval = EndpointsHandshake(client);
  517. if(retval == UA_STATUSCODE_GOOD)
  518. retval = SessionHandshake(client);
  519. if(retval == UA_STATUSCODE_GOOD)
  520. retval = ActivateSession(client);
  521. if(retval == UA_STATUSCODE_GOOD) {
  522. client->connection.state = UA_CONNECTION_ESTABLISHED;
  523. client->state = UA_CLIENTSTATE_CONNECTED;
  524. } else {
  525. goto cleanup;
  526. }
  527. return retval;
  528. cleanup:
  529. UA_Client_reset(client);
  530. return retval;
  531. }
  532. UA_StatusCode UA_Client_disconnect(UA_Client *client) {
  533. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  534. //is a session established?
  535. if(client->state == UA_CLIENTSTATE_CONNECTED && client->channel.connection->state == UA_CONNECTION_ESTABLISHED)
  536. retval = CloseSession(client);
  537. //is a secure channel established?
  538. if(retval == UA_STATUSCODE_GOOD && client->channel.connection->state == UA_CONNECTION_ESTABLISHED)
  539. retval = CloseSecureChannel(client);
  540. return retval;
  541. }
  542. UA_StatusCode UA_Client_manuallyRenewSecureChannel(UA_Client *client) {
  543. UA_StatusCode retval = SecureChannelHandshake(client, true);
  544. if(retval == UA_STATUSCODE_GOOD)
  545. client->state = UA_CLIENTSTATE_CONNECTED;
  546. return retval;
  547. }
  548. /****************/
  549. /* Raw Services */
  550. /****************/
  551. void __UA_Client_Service(UA_Client *client, const void *r, const UA_DataType *requestType,
  552. void *response, const UA_DataType *responseType) {
  553. /* Requests always begin witih a RequestHeader, therefore we can cast. */
  554. UA_RequestHeader *request = (void*)(uintptr_t)r;
  555. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  556. UA_init(response, responseType);
  557. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  558. /* make sure we have a valid session */
  559. retval = UA_Client_manuallyRenewSecureChannel(client);
  560. if(retval != UA_STATUSCODE_GOOD) {
  561. respHeader->serviceResult = retval;
  562. client->state = UA_CLIENTSTATE_ERRORED;
  563. return;
  564. }
  565. /* handling request parameters */
  566. UA_NodeId_copy(&client->authenticationToken, &request->authenticationToken);
  567. request->timestamp = UA_DateTime_now();
  568. request->requestHandle = ++client->requestHandle;
  569. /* Send the request */
  570. UA_UInt32 requestId = ++client->requestId;
  571. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  572. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  573. retval = UA_SecureChannel_sendBinaryMessage(&client->channel, requestId, request, requestType);
  574. if(retval != UA_STATUSCODE_GOOD) {
  575. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  576. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  577. else
  578. respHeader->serviceResult = retval;
  579. client->state = UA_CLIENTSTATE_ERRORED;
  580. return;
  581. }
  582. /* Retrieve the response */
  583. // Todo: push this into the generic securechannel implementation for client and server
  584. UA_ByteString reply;
  585. UA_ByteString_init(&reply);
  586. UA_Boolean realloced = false;
  587. do {
  588. retval = client->connection.recv(&client->connection, &reply, client->config.timeout);
  589. retval |= UA_Connection_completeMessages(&client->connection, &reply, &realloced);
  590. if(retval != UA_STATUSCODE_GOOD) {
  591. respHeader->serviceResult = retval;
  592. client->state = UA_CLIENTSTATE_ERRORED;
  593. return;
  594. }
  595. } while(!reply.data);
  596. size_t offset = 0;
  597. UA_SecureConversationMessageHeader msgHeader;
  598. retval |= UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &msgHeader);
  599. UA_SymmetricAlgorithmSecurityHeader symHeader;
  600. retval |= UA_SymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &symHeader);
  601. UA_SequenceHeader seqHeader;
  602. retval |= UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  603. UA_NodeId responseId;
  604. retval |= UA_NodeId_decodeBinary(&reply, &offset, &responseId);
  605. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, responseType->typeId.identifier.numeric +
  606. UA_ENCODINGOFFSET_BINARY);
  607. if(retval != UA_STATUSCODE_GOOD)
  608. goto finish;
  609. /* Todo: we need to demux responses since a publish responses may come at any time */
  610. if(!UA_NodeId_equal(&responseId, &expectedNodeId) || seqHeader.requestId != requestId) {
  611. if(responseId.identifier.numeric != UA_NS0ID_SERVICEFAULT + UA_ENCODINGOFFSET_BINARY) {
  612. UA_LOG_ERROR(client->config.logger, UA_LOGCATEGORY_CLIENT,
  613. "Reply answers the wrong request. Expected ns=%i,i=%i. But retrieved ns=%i,i=%i",
  614. expectedNodeId.namespaceIndex, expectedNodeId.identifier.numeric,
  615. responseId.namespaceIndex, responseId.identifier.numeric);
  616. respHeader->serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  617. } else
  618. retval = UA_decodeBinary(&reply, &offset, respHeader, &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  619. goto finish;
  620. }
  621. retval = UA_decodeBinary(&reply, &offset, response, responseType);
  622. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  623. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  624. finish:
  625. UA_SymmetricAlgorithmSecurityHeader_deleteMembers(&symHeader);
  626. if(!realloced)
  627. client->connection.releaseRecvBuffer(&client->connection, &reply);
  628. else
  629. UA_ByteString_deleteMembers(&reply);
  630. if(retval != UA_STATUSCODE_GOOD){
  631. UA_LOG_INFO(client->config.logger, UA_LOGCATEGORY_CLIENT, "Error receiving the response");
  632. client->state = UA_CLIENTSTATE_FAULTED;
  633. respHeader->serviceResult = retval;
  634. } else {
  635. client->state = UA_CLIENTSTATE_CONNECTED;
  636. }
  637. UA_LOG_DEBUG(client->config.logger, UA_LOGCATEGORY_CLIENT,
  638. "Received a response of type %i", responseId.identifier.numeric);
  639. }