ua_client.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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_types_generated.h"
  6. #include "ua_nodeids.h"
  7. #include "ua_types_encoding_binary.h"
  8. #include "ua_transport_generated.h"
  9. #include "ua_types_generated_encoding_binary.h"
  10. #include "ua_transport_generated_encoding_binary.h"
  11. const UA_EXPORT UA_ClientConfig UA_ClientConfig_standard =
  12. { .timeout = 5000 /* ms receive timout */, .secureChannelLifeTime = 600000,
  13. {.protocolVersion = 0, .sendBufferSize = 65536, .recvBufferSize = 65536,
  14. .maxMessageSize = 65536, .maxChunkCount = 1}};
  15. /*********************/
  16. /* Create and Delete */
  17. /*********************/
  18. static void UA_Client_init(UA_Client* client, UA_ClientConfig config, UA_Logger logger) {
  19. client->state = UA_CLIENTSTATE_READY;
  20. UA_Connection_init(&client->connection);
  21. UA_SecureChannel_init(&client->channel);
  22. client->channel.connection = &client->connection;
  23. UA_String_init(&client->endpointUrl);
  24. client->requestId = 0;
  25. client->authenticationMethod = UA_CLIENTAUTHENTICATION_NONE;
  26. UA_String_init(&client->username);
  27. UA_String_init(&client->password);
  28. UA_NodeId_init(&client->authenticationToken);
  29. client->requestHandle = 0;
  30. client->logger = logger;
  31. client->config = config;
  32. client->scRenewAt = 0;
  33. #ifdef UA_ENABLE_SUBSCRIPTIONS
  34. client->monitoredItemHandles = 0;
  35. LIST_INIT(&client->pendingNotificationsAcks);
  36. LIST_INIT(&client->subscriptions);
  37. #endif
  38. }
  39. UA_Client * UA_Client_new(UA_ClientConfig config, UA_Logger logger) {
  40. UA_Client *client = UA_calloc(1, sizeof(UA_Client));
  41. if(!client)
  42. return NULL;
  43. UA_Client_init(client, config, logger);
  44. return client;
  45. }
  46. static void UA_Client_deleteMembers(UA_Client* client) {
  47. UA_Client_disconnect(client);
  48. UA_Connection_deleteMembers(&client->connection);
  49. UA_SecureChannel_deleteMembersCleanup(&client->channel);
  50. if(client->endpointUrl.data)
  51. UA_String_deleteMembers(&client->endpointUrl);
  52. UA_UserTokenPolicy_deleteMembers(&client->token);
  53. if(client->username.data)
  54. UA_String_deleteMembers(&client->username);
  55. if(client->password.data)
  56. UA_String_deleteMembers(&client->password);
  57. #ifdef UA_ENABLE_SUBSCRIPTIONS
  58. UA_Client_NotificationsAckNumber *n, *tmp;
  59. LIST_FOREACH_SAFE(n, &client->pendingNotificationsAcks, listEntry, tmp) {
  60. LIST_REMOVE(n, listEntry);
  61. free(n);
  62. }
  63. UA_Client_Subscription *sub, *tmps;
  64. LIST_FOREACH_SAFE(sub, &client->subscriptions, listEntry, tmps) {
  65. LIST_REMOVE(sub, listEntry);
  66. UA_Client_MonitoredItem *mon, *tmpmon;
  67. LIST_FOREACH_SAFE(mon, &sub->MonitoredItems, listEntry, tmpmon) {
  68. UA_Client_Subscriptions_removeMonitoredItem(client, sub->SubscriptionID,
  69. mon->MonitoredItemId);
  70. }
  71. free(sub);
  72. }
  73. #endif
  74. }
  75. void UA_Client_reset(UA_Client* client){
  76. UA_Client_deleteMembers(client);
  77. UA_Client_init(client, client->config, client->logger);
  78. }
  79. void UA_Client_delete(UA_Client* client){
  80. if(client->state != UA_CLIENTSTATE_READY)
  81. UA_Client_deleteMembers(client);
  82. UA_free(client);
  83. }
  84. /*************************/
  85. /* Manage the Connection */
  86. /*************************/
  87. static UA_StatusCode HelAckHandshake(UA_Client *c) {
  88. UA_TcpMessageHeader messageHeader;
  89. messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_HELF;
  90. UA_TcpHelloMessage hello;
  91. UA_String_copy(&c->endpointUrl, &hello.endpointUrl); /* must be less than 4096 bytes */
  92. UA_Connection *conn = &c->connection;
  93. hello.maxChunkCount = conn->localConf.maxChunkCount;
  94. hello.maxMessageSize = conn->localConf.maxMessageSize;
  95. hello.protocolVersion = conn->localConf.protocolVersion;
  96. hello.receiveBufferSize = conn->localConf.recvBufferSize;
  97. hello.sendBufferSize = conn->localConf.sendBufferSize;
  98. UA_ByteString message;
  99. UA_StatusCode retval;
  100. retval = c->connection.getSendBuffer(&c->connection, c->connection.remoteConf.recvBufferSize, &message);
  101. if(retval != UA_STATUSCODE_GOOD)
  102. return retval;
  103. size_t offset = 8;
  104. retval |= UA_TcpHelloMessage_encodeBinary(&hello, &message, &offset);
  105. messageHeader.messageSize = (UA_UInt32)offset;
  106. offset = 0;
  107. retval |= UA_TcpMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  108. UA_TcpHelloMessage_deleteMembers(&hello);
  109. if(retval != UA_STATUSCODE_GOOD) {
  110. c->connection.releaseSendBuffer(&c->connection, &message);
  111. return retval;
  112. }
  113. message.length = messageHeader.messageSize;
  114. retval = c->connection.send(&c->connection, &message);
  115. if(retval != UA_STATUSCODE_GOOD) {
  116. UA_LOG_INFO(c->logger, UA_LOGCATEGORY_NETWORK, "Sending HEL failed");
  117. return retval;
  118. }
  119. UA_LOG_DEBUG(c->logger, UA_LOGCATEGORY_NETWORK, "Sent HEL message");
  120. UA_ByteString reply;
  121. UA_ByteString_init(&reply);
  122. UA_Boolean realloced = false;
  123. do {
  124. retval = c->connection.recv(&c->connection, &reply, c->config.timeout);
  125. retval |= UA_Connection_completeMessages(&c->connection, &reply, &realloced);
  126. if(retval != UA_STATUSCODE_GOOD) {
  127. UA_LOG_INFO(c->logger, UA_LOGCATEGORY_NETWORK, "Receiving ACK message failed");
  128. return retval;
  129. }
  130. } while(reply.length == 0);
  131. offset = 0;
  132. UA_TcpMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  133. UA_TcpAcknowledgeMessage ackMessage;
  134. retval = UA_TcpAcknowledgeMessage_decodeBinary(&reply, &offset, &ackMessage);
  135. if(!realloced)
  136. c->connection.releaseRecvBuffer(&c->connection, &reply);
  137. else
  138. UA_ByteString_deleteMembers(&reply);
  139. if(retval != UA_STATUSCODE_GOOD) {
  140. UA_LOG_INFO(c->logger, UA_LOGCATEGORY_NETWORK, "Decoding ACK message failed");
  141. return retval;
  142. }
  143. UA_LOG_DEBUG(c->logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  144. conn->remoteConf.maxChunkCount = ackMessage.maxChunkCount;
  145. conn->remoteConf.maxMessageSize = ackMessage.maxMessageSize;
  146. conn->remoteConf.protocolVersion = ackMessage.protocolVersion;
  147. conn->remoteConf.recvBufferSize = ackMessage.receiveBufferSize;
  148. conn->remoteConf.sendBufferSize = ackMessage.sendBufferSize;
  149. conn->state = UA_CONNECTION_ESTABLISHED;
  150. return UA_STATUSCODE_GOOD;
  151. }
  152. static UA_StatusCode SecureChannelHandshake(UA_Client *client, UA_Boolean renew) {
  153. /* Check if sc is still valid */
  154. if(renew && client->scRenewAt - UA_DateTime_now() > 0)
  155. return UA_STATUSCODE_GOOD;
  156. UA_Connection *c = &client->connection;
  157. if(c->state != UA_CONNECTION_ESTABLISHED)
  158. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  159. UA_SecureConversationMessageHeader messageHeader;
  160. messageHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_OPNF;
  161. if(renew)
  162. messageHeader.secureChannelId = client->channel.securityToken.channelId;
  163. else
  164. messageHeader.secureChannelId = 0;
  165. UA_SequenceHeader seqHeader;
  166. seqHeader.sequenceNumber = ++client->channel.sequenceNumber;
  167. seqHeader.requestId = ++client->requestId;
  168. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  169. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  170. asymHeader.securityPolicyUri = UA_STRING_ALLOC("http://opcfoundation.org/UA/SecurityPolicy#None");
  171. /* id of opensecurechannelrequest */
  172. UA_NodeId requestType = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELREQUEST + UA_ENCODINGOFFSET_BINARY);
  173. UA_OpenSecureChannelRequest opnSecRq;
  174. UA_OpenSecureChannelRequest_init(&opnSecRq);
  175. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  176. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  177. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  178. if(renew) {
  179. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  180. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to renew the SecureChannel");
  181. } else {
  182. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  183. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Requesting to open a SecureChannel");
  184. }
  185. UA_ByteString_copy(&client->channel.clientNonce, &opnSecRq.clientNonce);
  186. opnSecRq.securityMode = UA_MESSAGESECURITYMODE_NONE;
  187. UA_ByteString message;
  188. UA_StatusCode retval = c->getSendBuffer(c, c->remoteConf.recvBufferSize, &message);
  189. if(retval != UA_STATUSCODE_GOOD) {
  190. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  191. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  192. return retval;
  193. }
  194. size_t offset = 12;
  195. retval = UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &message, &offset);
  196. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &message, &offset);
  197. retval |= UA_NodeId_encodeBinary(&requestType, &message, &offset);
  198. retval |= UA_OpenSecureChannelRequest_encodeBinary(&opnSecRq, &message, &offset);
  199. messageHeader.messageHeader.messageSize = (UA_UInt32)offset;
  200. offset = 0;
  201. retval |= UA_SecureConversationMessageHeader_encodeBinary(&messageHeader, &message, &offset);
  202. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  203. UA_OpenSecureChannelRequest_deleteMembers(&opnSecRq);
  204. if(retval != UA_STATUSCODE_GOOD) {
  205. client->connection.releaseSendBuffer(&client->connection, &message);
  206. return retval;
  207. }
  208. message.length = messageHeader.messageHeader.messageSize;
  209. retval = client->connection.send(&client->connection, &message);
  210. if(retval != UA_STATUSCODE_GOOD)
  211. return retval;
  212. UA_ByteString reply;
  213. UA_ByteString_init(&reply);
  214. UA_Boolean realloced = false;
  215. do {
  216. retval = c->recv(c, &reply, client->config.timeout);
  217. retval |= UA_Connection_completeMessages(c, &reply, &realloced);
  218. if(retval != UA_STATUSCODE_GOOD) {
  219. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL,
  220. "Receiving OpenSecureChannelResponse failed");
  221. return retval;
  222. }
  223. } while(reply.length == 0);
  224. offset = 0;
  225. UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &messageHeader);
  226. UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &asymHeader);
  227. UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  228. UA_NodeId_decodeBinary(&reply, &offset, &requestType);
  229. UA_NodeId expectedRequest = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE +
  230. UA_ENCODINGOFFSET_BINARY);
  231. if(!UA_NodeId_equal(&requestType, &expectedRequest)) {
  232. UA_ByteString_deleteMembers(&reply);
  233. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  234. UA_NodeId_deleteMembers(&requestType);
  235. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  236. "Reply answers the wrong request. Expected OpenSecureChannelResponse.");
  237. return UA_STATUSCODE_BADINTERNALERROR;
  238. }
  239. UA_OpenSecureChannelResponse response;
  240. UA_OpenSecureChannelResponse_init(&response);
  241. retval = UA_OpenSecureChannelResponse_decodeBinary(&reply, &offset, &response);
  242. if(!realloced)
  243. c->releaseRecvBuffer(c, &reply);
  244. else
  245. UA_ByteString_deleteMembers(&reply);
  246. if(retval != UA_STATUSCODE_GOOD) {
  247. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "Decoding OpenSecureChannelResponse failed");
  248. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  249. UA_OpenSecureChannelResponse_init(&response);
  250. response.responseHeader.serviceResult = retval;
  251. return retval;
  252. }
  253. //response.securityToken.revisedLifetime is UInt32 we need to cast it to DateTime=Int64
  254. //we take 75% of lifetime to start renewing as described in standard
  255. client->scRenewAt = UA_DateTime_now() +
  256. (UA_DateTime)(response.securityToken.revisedLifetime * (UA_Double)UA_MSEC_TO_DATETIME * 0.75);
  257. retval = response.responseHeader.serviceResult;
  258. if(retval != UA_STATUSCODE_GOOD)
  259. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel could not be opened / renewed");
  260. else {
  261. UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
  262. UA_ChannelSecurityToken_copy(&response.securityToken, &client->channel.securityToken);
  263. /* if the handshake is repeated, replace the old nonce */
  264. UA_ByteString_deleteMembers(&client->channel.serverNonce);
  265. UA_ByteString_copy(&response.serverNonce, &client->channel.serverNonce);
  266. if(renew)
  267. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel renewed");
  268. else
  269. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel opened");
  270. }
  271. UA_OpenSecureChannelResponse_deleteMembers(&response);
  272. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  273. return retval;
  274. }
  275. static UA_StatusCode ActivateSession(UA_Client *client) {
  276. UA_ActivateSessionRequest request;
  277. UA_ActivateSessionRequest_init(&request);
  278. request.requestHeader.requestHandle = 2; //TODO: is it a magic number?
  279. request.requestHeader.authenticationToken = client->authenticationToken;
  280. request.requestHeader.timestamp = UA_DateTime_now();
  281. request.requestHeader.timeoutHint = 600000;
  282. //manual ExtensionObject encoding of the identityToken
  283. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE){
  284. UA_AnonymousIdentityToken* identityToken = UA_malloc(sizeof(UA_AnonymousIdentityToken));
  285. UA_AnonymousIdentityToken_init(identityToken);
  286. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  287. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  288. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  289. request.userIdentityToken.content.decoded.data = identityToken;
  290. }else{
  291. UA_UserNameIdentityToken* identityToken = UA_malloc(sizeof(UA_UserNameIdentityToken));
  292. UA_UserNameIdentityToken_init(identityToken);
  293. UA_String_copy(&client->token.policyId, &identityToken->policyId);
  294. UA_String_copy(&client->username, &identityToken->userName);
  295. UA_String_copy(&client->password, &identityToken->password);
  296. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  297. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  298. request.userIdentityToken.content.decoded.data = identityToken;
  299. }
  300. UA_ActivateSessionResponse response;
  301. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  302. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  303. UA_ActivateSessionRequest_deleteMembers(&request);
  304. UA_ActivateSessionResponse_deleteMembers(&response);
  305. return response.responseHeader.serviceResult; // not deleted
  306. }
  307. /**
  308. * Gets a list of endpoints
  309. * Memory is allocated for endpointDescription array
  310. */
  311. static UA_StatusCode
  312. GetEndpoints(UA_Client *client, size_t* endpointDescriptionsSize, UA_EndpointDescription** endpointDescriptions) {
  313. UA_GetEndpointsRequest request;
  314. UA_GetEndpointsRequest_init(&request);
  315. request.requestHeader.authenticationToken = client->authenticationToken;
  316. request.requestHeader.timestamp = UA_DateTime_now();
  317. request.requestHeader.timeoutHint = 10000;
  318. request.endpointUrl = client->endpointUrl; // assume the endpointurl outlives the service call
  319. UA_GetEndpointsResponse response;
  320. UA_GetEndpointsResponse_init(&response);
  321. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  322. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  323. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  324. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "GetEndpointRequest failed");
  325. UA_GetEndpointsResponse_deleteMembers(&response);
  326. return response.responseHeader.serviceResult;
  327. }
  328. *endpointDescriptionsSize = response.endpointsSize;
  329. *endpointDescriptions = UA_Array_new(response.endpointsSize, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  330. for(size_t i=0;i<response.endpointsSize;i++)
  331. UA_EndpointDescription_copy(&response.endpoints[i], &(*endpointDescriptions)[i]);
  332. UA_GetEndpointsResponse_deleteMembers(&response);
  333. return UA_STATUSCODE_GOOD;
  334. }
  335. static UA_StatusCode EndpointsHandshake(UA_Client *client) {
  336. UA_EndpointDescription* endpointArray = NULL;
  337. size_t endpointArraySize = 0;
  338. UA_StatusCode retval = GetEndpoints(client, &endpointArraySize, &endpointArray);
  339. UA_Boolean endpointFound = false;
  340. UA_Boolean tokenFound = false;
  341. UA_String securityNone = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  342. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");
  343. //TODO: compare endpoint information with client->endpointUri
  344. for(size_t i = 0; i < endpointArraySize; i++) {
  345. UA_EndpointDescription* endpoint = &endpointArray[i];
  346. /* look out for binary transport endpoints */
  347. //NODE: Siemens returns empty ProfileUrl, we will accept it as binary
  348. if(endpoint->transportProfileUri.length!=0 && !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  349. continue;
  350. /* look out for an endpoint without security */
  351. if(!UA_String_equal(&endpoint->securityPolicyUri, &securityNone))
  352. continue;
  353. endpointFound = true;
  354. /* endpoint with no security found */
  355. /* look for a user token policy with an anonymous token */
  356. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  357. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  358. //anonymous authentication
  359. if(client->authenticationMethod == UA_CLIENTAUTHENTICATION_NONE){
  360. if(userToken->tokenType != UA_USERTOKENTYPE_ANONYMOUS)
  361. continue;
  362. }else{
  363. //username authentication
  364. if(userToken->tokenType != UA_USERTOKENTYPE_USERNAME)
  365. continue;
  366. }
  367. tokenFound = true;
  368. UA_UserTokenPolicy_copy(userToken, &client->token);
  369. break;
  370. }
  371. }
  372. //cleanup array
  373. UA_Array_delete(endpointArray,endpointArraySize,&UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  374. if(!endpointFound) {
  375. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT, "No suitable endpoint found");
  376. return UA_STATUSCODE_BADINTERNALERROR;
  377. }
  378. if(!tokenFound) {
  379. UA_LOG_ERROR(client->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, UA_ConnectClientConnection connectFunc,
  457. const char *serverUrl, 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. }
  464. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  465. client->connection = connectFunc(UA_ConnectionConfig_standard, serverUrl, client->logger);
  466. if(client->connection.state != UA_CONNECTION_OPENING) {
  467. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  468. goto cleanup;
  469. }
  470. client->endpointUrl = UA_STRING_ALLOC(serverUrl);
  471. if(!client->endpointUrl.data) {
  472. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  473. goto cleanup;
  474. }
  475. client->connection.localConf = client->config.localConnectionConfig;
  476. retval = HelAckHandshake(client);
  477. if(retval == UA_STATUSCODE_GOOD)
  478. retval = SecureChannelHandshake(client, false);
  479. if(retval == UA_STATUSCODE_GOOD)
  480. retval = GetEndpoints(client, endpointDescriptionsSize, endpointDescriptions);
  481. //we always cleanup
  482. cleanup:
  483. UA_Client_reset(client);
  484. return retval;
  485. }
  486. UA_StatusCode UA_Client_connect_username(UA_Client *client, UA_ConnectClientConnection connFunc,
  487. const char *endpointUrl, 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, connFunc, endpointUrl);
  492. }
  493. UA_StatusCode UA_Client_connect(UA_Client *client, UA_ConnectClientConnection connectFunc,
  494. 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 = connectFunc(UA_ConnectionConfig_standard, endpointUrl, client->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. }
  538. //is a secure channel established?
  539. if(retval == UA_STATUSCODE_GOOD && client->channel.connection->state == UA_CONNECTION_ESTABLISHED){
  540. retval = CloseSecureChannel(client);
  541. }
  542. return retval;
  543. }
  544. UA_StatusCode UA_Client_manuallyRenewSecureChannel(UA_Client *client) {
  545. return SecureChannelHandshake(client, true);
  546. }
  547. /****************/
  548. /* Raw Services */
  549. /****************/
  550. void __UA_Client_Service(UA_Client *client, const void *r, const UA_DataType *requestType,
  551. void *response, const UA_DataType *responseType) {
  552. /* Requests always begin witih a RequestHeader, therefore we can cast. */
  553. UA_RequestHeader *request = (void*)(uintptr_t)r;
  554. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  555. UA_init(response, responseType);
  556. UA_ResponseHeader *respHeader = (UA_ResponseHeader*)response;
  557. /* make sure we have a valid session */
  558. retval = UA_Client_manuallyRenewSecureChannel(client);
  559. if(retval != UA_STATUSCODE_GOOD) {
  560. respHeader->serviceResult = retval;
  561. client->state = UA_CLIENTSTATE_ERRORED;
  562. return;
  563. }
  564. /* handling request parameters */
  565. UA_NodeId_copy(&client->authenticationToken, &request->authenticationToken);
  566. request->timestamp = UA_DateTime_now();
  567. request->requestHandle = ++client->requestHandle;
  568. /* Send the request */
  569. UA_UInt32 requestId = ++client->requestId;
  570. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT,
  571. "Sending a request of type %i", requestType->typeId.identifier.numeric);
  572. retval = UA_SecureChannel_sendBinaryMessage(&client->channel, requestId, request, requestType);
  573. if(retval != UA_STATUSCODE_GOOD) {
  574. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  575. respHeader->serviceResult = UA_STATUSCODE_BADREQUESTTOOLARGE;
  576. else
  577. respHeader->serviceResult = retval;
  578. client->state = UA_CLIENTSTATE_ERRORED;
  579. return;
  580. }
  581. /* Retrieve the response */
  582. // Todo: push this into the generic securechannel implementation for client and server
  583. UA_ByteString reply;
  584. UA_ByteString_init(&reply);
  585. UA_Boolean realloced = false;
  586. do {
  587. retval = client->connection.recv(&client->connection, &reply, client->config.timeout);
  588. retval |= UA_Connection_completeMessages(&client->connection, &reply, &realloced);
  589. if(retval != UA_STATUSCODE_GOOD) {
  590. respHeader->serviceResult = retval;
  591. client->state = UA_CLIENTSTATE_ERRORED;
  592. return;
  593. }
  594. } while(!reply.data);
  595. size_t offset = 0;
  596. UA_SecureConversationMessageHeader msgHeader;
  597. retval |= UA_SecureConversationMessageHeader_decodeBinary(&reply, &offset, &msgHeader);
  598. UA_SymmetricAlgorithmSecurityHeader symHeader;
  599. retval |= UA_SymmetricAlgorithmSecurityHeader_decodeBinary(&reply, &offset, &symHeader);
  600. UA_SequenceHeader seqHeader;
  601. retval |= UA_SequenceHeader_decodeBinary(&reply, &offset, &seqHeader);
  602. UA_NodeId responseId;
  603. retval |= UA_NodeId_decodeBinary(&reply, &offset, &responseId);
  604. UA_NodeId expectedNodeId = UA_NODEID_NUMERIC(0, responseType->typeId.identifier.numeric +
  605. UA_ENCODINGOFFSET_BINARY);
  606. if(retval != UA_STATUSCODE_GOOD)
  607. goto finish;
  608. /* Todo: we need to demux responses since a publish responses may come at any time */
  609. if(!UA_NodeId_equal(&responseId, &expectedNodeId) || seqHeader.requestId != requestId) {
  610. if(responseId.identifier.numeric != UA_NS0ID_SERVICEFAULT + UA_ENCODINGOFFSET_BINARY) {
  611. UA_LOG_ERROR(client->logger, UA_LOGCATEGORY_CLIENT,
  612. "Reply answers the wrong request. Expected ns=%i,i=%i. But retrieved ns=%i,i=%i",
  613. expectedNodeId.namespaceIndex, expectedNodeId.identifier.numeric,
  614. responseId.namespaceIndex, responseId.identifier.numeric);
  615. respHeader->serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  616. } else
  617. retval = UA_decodeBinary(&reply, &offset, respHeader, &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  618. goto finish;
  619. }
  620. retval = UA_decodeBinary(&reply, &offset, response, responseType);
  621. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED)
  622. retval = UA_STATUSCODE_BADRESPONSETOOLARGE;
  623. finish:
  624. UA_SymmetricAlgorithmSecurityHeader_deleteMembers(&symHeader);
  625. if(!realloced)
  626. client->connection.releaseRecvBuffer(&client->connection, &reply);
  627. else
  628. UA_ByteString_deleteMembers(&reply);
  629. if(retval != UA_STATUSCODE_GOOD){
  630. UA_LOG_INFO(client->logger, UA_LOGCATEGORY_CLIENT, "Error receiving the response");
  631. client->state = UA_CLIENTSTATE_ERRORED;
  632. respHeader->serviceResult = retval;
  633. }
  634. UA_LOG_DEBUG(client->logger, UA_LOGCATEGORY_CLIENT, "Received a response of type %i", responseId.identifier.numeric);
  635. }