ua_server_binary.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #include "ua_util.h"
  2. #include "ua_server_internal.h"
  3. #include "ua_types_encoding_binary.h"
  4. #include "ua_transport_generated.h"
  5. #include "ua_services.h"
  6. #include "ua_statuscodes.h"
  7. #include "ua_securechannel_manager.h"
  8. #include "ua_session_manager.h"
  9. #include "ua_nodeids.h"
  10. /** Max size of messages that are allocated on the stack */
  11. #define MAX_STACK_MESSAGE 65536
  12. static void processHEL(UA_Connection *connection, const UA_ByteString *msg, size_t *pos) {
  13. UA_TcpHelloMessage helloMessage;
  14. if(UA_TcpHelloMessage_decodeBinary(msg, pos, &helloMessage) != UA_STATUSCODE_GOOD) {
  15. connection->close(connection);
  16. return;
  17. }
  18. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount;
  19. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize;
  20. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  21. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  22. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  23. connection->state = UA_CONNECTION_ESTABLISHED;
  24. UA_TcpHelloMessage_deleteMembers(&helloMessage);
  25. // build acknowledge response
  26. UA_TcpAcknowledgeMessage ackMessage;
  27. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  28. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  29. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  30. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  31. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  32. UA_TcpMessageHeader ackHeader;
  33. ackHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_ACKF;
  34. ackHeader.messageSize = UA_TcpMessageHeader_calcSizeBinary(&ackHeader)
  35. + UA_TcpAcknowledgeMessage_calcSizeBinary(&ackMessage);
  36. UA_ByteString ack_msg;
  37. if(connection->getBuffer(connection, &ack_msg, ackHeader.messageSize) != UA_STATUSCODE_GOOD)
  38. return;
  39. size_t tmpPos = 0;
  40. UA_TcpMessageHeader_encodeBinary(&ackHeader, &ack_msg, &tmpPos);
  41. UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &ack_msg, &tmpPos);
  42. connection->write(connection, &ack_msg);
  43. connection->releaseBuffer(connection, &ack_msg);
  44. }
  45. static void processOPN(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg,
  46. size_t *pos) {
  47. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  48. connection->close(connection);
  49. return;
  50. }
  51. UA_UInt32 secureChannelId;
  52. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  53. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  54. retval |= UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg, pos, &asymHeader);
  55. UA_SequenceHeader seqHeader;
  56. retval |= UA_SequenceHeader_decodeBinary(msg, pos, &seqHeader);
  57. UA_NodeId requestType;
  58. retval |= UA_NodeId_decodeBinary(msg, pos, &requestType);
  59. UA_OpenSecureChannelRequest r;
  60. retval |= UA_OpenSecureChannelRequest_decodeBinary(msg, pos, &r);
  61. if(retval != UA_STATUSCODE_GOOD || requestType.identifier.numeric != 446) {
  62. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  63. UA_SequenceHeader_deleteMembers(&seqHeader);
  64. UA_NodeId_deleteMembers(&requestType);
  65. UA_OpenSecureChannelRequest_deleteMembers(&r);
  66. connection->close(connection);
  67. return;
  68. }
  69. UA_OpenSecureChannelResponse p;
  70. UA_OpenSecureChannelResponse_init(&p);
  71. Service_OpenSecureChannel(server, connection, &r, &p);
  72. UA_OpenSecureChannelRequest_deleteMembers(&r);
  73. UA_SecureConversationMessageHeader respHeader;
  74. respHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_OPNF;
  75. respHeader.messageHeader.messageSize = 0;
  76. respHeader.secureChannelId = p.securityToken.channelId;
  77. UA_NodeId responseType = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE +
  78. UA_ENCODINGOFFSET_BINARY);
  79. respHeader.messageHeader.messageSize =
  80. UA_SecureConversationMessageHeader_calcSizeBinary(&respHeader)
  81. + UA_AsymmetricAlgorithmSecurityHeader_calcSizeBinary(&asymHeader)
  82. + UA_SequenceHeader_calcSizeBinary(&seqHeader)
  83. + UA_NodeId_calcSizeBinary(&responseType)
  84. + UA_OpenSecureChannelResponse_calcSizeBinary(&p);
  85. UA_ByteString resp_msg;
  86. retval = connection->getBuffer(connection, &resp_msg, respHeader.messageHeader.messageSize);
  87. if(retval != UA_STATUSCODE_GOOD) {
  88. UA_OpenSecureChannelResponse_deleteMembers(&p);
  89. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  90. return;
  91. }
  92. size_t tmpPos = 0;
  93. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &resp_msg, &tmpPos);
  94. UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &resp_msg, &tmpPos); // just mirror back
  95. UA_SequenceHeader_encodeBinary(&seqHeader, &resp_msg, &tmpPos); // just mirror back
  96. UA_NodeId_encodeBinary(&responseType, &resp_msg, &tmpPos);
  97. UA_OpenSecureChannelResponse_encodeBinary(&p, &resp_msg, &tmpPos);
  98. UA_OpenSecureChannelResponse_deleteMembers(&p);
  99. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  100. connection->write(connection, &resp_msg);
  101. connection->releaseBuffer(connection, &resp_msg);
  102. }
  103. static void init_response_header(const UA_RequestHeader *p, UA_ResponseHeader *r) {
  104. r->requestHandle = p->requestHandle;
  105. r->stringTableSize = 0;
  106. r->timestamp = UA_DateTime_now();
  107. }
  108. /* The request/response are casted to the header (first element of their struct) */
  109. static void invoke_service(UA_Server *server, UA_SecureChannel *channel,
  110. UA_RequestHeader *request, UA_ResponseHeader *response,
  111. void (*service)(UA_Server*, UA_Session*, void*, void*)) {
  112. init_response_header(request, response);
  113. /* try to get the session from the securechannel first */
  114. UA_Session *session = UA_SecureChannel_getSession(channel, &request->authenticationToken);
  115. if(!session)
  116. session = UA_SessionManager_getSession(&server->sessionManager, &request->authenticationToken);
  117. if(!session)
  118. response->serviceResult = UA_STATUSCODE_BADSESSIONIDINVALID;
  119. else if(session->activated == UA_FALSE) {
  120. response->serviceResult = UA_STATUSCODE_BADSESSIONNOTACTIVATED;
  121. /* the session is invalidated */
  122. UA_SessionManager_removeSession(&server->sessionManager, &request->authenticationToken);
  123. }
  124. else if(session->channel != channel)
  125. response->serviceResult = UA_STATUSCODE_BADSESSIONIDINVALID;
  126. else {
  127. UA_Session_updateLifetime(session);
  128. service(server, session, request, response);
  129. }
  130. }
  131. #define INVOKE_SERVICE(TYPE) do { \
  132. UA_##TYPE##Request p; \
  133. UA_##TYPE##Response r; \
  134. if(UA_##TYPE##Request_decodeBinary(msg, pos, &p)) \
  135. return; \
  136. UA_##TYPE##Response_init(&r); \
  137. invoke_service(server, clientChannel, &p.requestHeader, \
  138. &r.responseHeader, \
  139. (void (*)(UA_Server*, UA_Session*, void*,void*))Service_##TYPE); \
  140. UA_##TYPE##Request_deleteMembers(&p); \
  141. retval = connection->getBuffer(connection, &message, \
  142. headerSize + UA_##TYPE##Response_calcSizeBinary(&r)); \
  143. if(retval != UA_STATUSCODE_GOOD) { \
  144. UA_##TYPE##Response_deleteMembers(&r); \
  145. return; \
  146. } \
  147. UA_##TYPE##Response_encodeBinary(&r, &message, &messagePos); \
  148. UA_##TYPE##Response_deleteMembers(&r); \
  149. } while(0)
  150. static void processMSG(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg, size_t *pos) {
  151. // 1) Read in the securechannel
  152. UA_UInt32 secureChannelId;
  153. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  154. if(retval != UA_STATUSCODE_GOOD)
  155. return;
  156. UA_SecureChannel *clientChannel = connection->channel;
  157. #ifdef EXTENSION_STATELESS
  158. UA_SecureChannel anonymousChannel;
  159. if(!clientChannel) {
  160. UA_SecureChannel_init(&anonymousChannel);
  161. anonymousChannel.session = &anonymousSession;
  162. clientChannel = &anonymousChannel;
  163. }
  164. #endif
  165. // 2) Read the security header
  166. UA_UInt32 tokenId;
  167. UA_SequenceHeader sequenceHeader;
  168. retval = UA_UInt32_decodeBinary(msg, pos, &tokenId);
  169. retval |= UA_SequenceHeader_decodeBinary(msg, pos, &sequenceHeader);
  170. if(retval != UA_STATUSCODE_GOOD)
  171. return;
  172. //UA_SecureChannel_checkSequenceNumber(channel,sequenceHeader.sequenceNumber);
  173. //UA_SecureChannel_checkRequestId(channel,sequenceHeader.requestId);
  174. clientChannel->sequenceNumber = sequenceHeader.sequenceNumber;
  175. clientChannel->requestId = sequenceHeader.requestId;
  176. // 3) Build the header and compute the header size
  177. UA_SecureConversationMessageHeader respHeader;
  178. respHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_MSGF;
  179. respHeader.messageHeader.messageSize = 0;
  180. respHeader.secureChannelId = clientChannel->securityToken.channelId;
  181. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  182. symSecHeader.tokenId = clientChannel->securityToken.tokenId;
  183. UA_SequenceHeader seqHeader;
  184. seqHeader.sequenceNumber = clientChannel->sequenceNumber;
  185. seqHeader.requestId = clientChannel->requestId;
  186. // 4) process the request
  187. UA_ByteString message;
  188. UA_NodeId requestType;
  189. if(UA_NodeId_decodeBinary(msg, pos, &requestType))
  190. return;
  191. if(requestType.identifierType != UA_NODEIDTYPE_NUMERIC) {
  192. UA_NodeId_deleteMembers(&requestType);
  193. return;
  194. }
  195. UA_NodeId response_nodeid = UA_NODEID_NUMERIC(0, requestType.identifier.numeric + 3);
  196. UA_UInt32 headerSize = UA_SecureConversationMessageHeader_calcSizeBinary(&respHeader)
  197. + UA_SymmetricAlgorithmSecurityHeader_calcSizeBinary(&symSecHeader)
  198. + UA_SequenceHeader_calcSizeBinary(&seqHeader)
  199. + UA_NodeId_calcSizeBinary(&response_nodeid);
  200. size_t messagePos = headerSize;
  201. //subtract UA_ENCODINGOFFSET_BINARY for binary encoding
  202. switch(requestType.identifier.numeric - UA_ENCODINGOFFSET_BINARY) {
  203. case UA_NS0ID_GETENDPOINTSREQUEST: {
  204. UA_GetEndpointsRequest p;
  205. UA_GetEndpointsResponse r;
  206. if(UA_GetEndpointsRequest_decodeBinary(msg, pos, &p))
  207. return;
  208. UA_GetEndpointsResponse_init(&r);
  209. init_response_header(&p.requestHeader, &r.responseHeader);
  210. Service_GetEndpoints(server, &p, &r);
  211. UA_GetEndpointsRequest_deleteMembers(&p);
  212. retval = connection->getBuffer(connection, &message, headerSize + UA_GetEndpointsResponse_calcSizeBinary(&r));
  213. if(retval != UA_STATUSCODE_GOOD) {
  214. UA_GetEndpointsResponse_deleteMembers(&r);
  215. return;
  216. }
  217. UA_GetEndpointsResponse_encodeBinary(&r, &message, &messagePos);
  218. UA_GetEndpointsResponse_deleteMembers(&r);
  219. break;
  220. }
  221. case UA_NS0ID_FINDSERVERSREQUEST: {
  222. UA_FindServersRequest p;
  223. UA_FindServersResponse r;
  224. if(UA_FindServersRequest_decodeBinary(msg, pos, &p))
  225. return;
  226. UA_FindServersResponse_init(&r);
  227. init_response_header(&p.requestHeader, &r.responseHeader);
  228. Service_FindServers(server, &p, &r);
  229. UA_FindServersRequest_deleteMembers(&p);
  230. retval = connection->getBuffer(connection, &message, headerSize + UA_FindServersResponse_calcSizeBinary(&r));
  231. if(retval != UA_STATUSCODE_GOOD) {
  232. UA_FindServersResponse_deleteMembers(&r);
  233. return;
  234. }
  235. UA_FindServersResponse_encodeBinary(&r, &message, &messagePos);
  236. UA_FindServersResponse_deleteMembers(&r);
  237. break;
  238. }
  239. case UA_NS0ID_CREATESESSIONREQUEST: {
  240. UA_CreateSessionRequest p;
  241. UA_CreateSessionResponse r;
  242. if(UA_CreateSessionRequest_decodeBinary(msg, pos, &p))
  243. return;
  244. UA_CreateSessionResponse_init(&r);
  245. init_response_header(&p.requestHeader, &r.responseHeader);
  246. Service_CreateSession(server, clientChannel, &p, &r);
  247. UA_CreateSessionRequest_deleteMembers(&p);
  248. retval = connection->getBuffer(connection, &message, headerSize + UA_CreateSessionResponse_calcSizeBinary(&r));
  249. if(retval != UA_STATUSCODE_GOOD) {
  250. UA_CreateSessionResponse_deleteMembers(&r);
  251. return;
  252. }
  253. UA_CreateSessionResponse_encodeBinary(&r, &message, &messagePos);
  254. UA_CreateSessionResponse_deleteMembers(&r);
  255. break;
  256. }
  257. case UA_NS0ID_ACTIVATESESSIONREQUEST: {
  258. UA_ActivateSessionRequest p;
  259. UA_ActivateSessionResponse r;
  260. if(UA_ActivateSessionRequest_decodeBinary(msg, pos, &p))
  261. return;
  262. UA_ActivateSessionResponse_init(&r);
  263. init_response_header(&p.requestHeader, &r.responseHeader);
  264. Service_ActivateSession(server, clientChannel, &p, &r);
  265. UA_ActivateSessionRequest_deleteMembers(&p);
  266. retval = connection->getBuffer(connection, &message, headerSize + UA_ActivateSessionResponse_calcSizeBinary(&r));
  267. if(retval != UA_STATUSCODE_GOOD) {
  268. UA_ActivateSessionResponse_deleteMembers(&r);
  269. return;
  270. }
  271. UA_ActivateSessionResponse_encodeBinary(&r, &message, &messagePos);
  272. UA_ActivateSessionResponse_deleteMembers(&r);
  273. break;
  274. }
  275. case UA_NS0ID_CLOSESESSIONREQUEST:
  276. INVOKE_SERVICE(CloseSession);
  277. break;
  278. case UA_NS0ID_READREQUEST:
  279. INVOKE_SERVICE(Read);
  280. break;
  281. case UA_NS0ID_WRITEREQUEST:
  282. INVOKE_SERVICE(Write);
  283. break;
  284. case UA_NS0ID_BROWSEREQUEST:
  285. INVOKE_SERVICE(Browse);
  286. break;
  287. case UA_NS0ID_BROWSENEXTREQUEST:
  288. INVOKE_SERVICE(BrowseNext);
  289. break;
  290. case UA_NS0ID_ADDREFERENCESREQUEST:
  291. INVOKE_SERVICE(AddReferences);
  292. break;
  293. case UA_NS0ID_REGISTERNODESREQUEST:
  294. INVOKE_SERVICE(RegisterNodes);
  295. break;
  296. case UA_NS0ID_UNREGISTERNODESREQUEST:
  297. INVOKE_SERVICE(UnregisterNodes);
  298. break;
  299. case UA_NS0ID_TRANSLATEBROWSEPATHSTONODEIDSREQUEST:
  300. INVOKE_SERVICE(TranslateBrowsePathsToNodeIds);
  301. break;
  302. default: {
  303. if(requestType.namespaceIndex == 0 && requestType.identifier.numeric==787){
  304. UA_LOG_INFO(server->logger, UA_LOGCATEGORY_COMMUNICATION,
  305. "Client requested a subscription that are not supported, the message will be skipped");
  306. }else{
  307. UA_LOG_INFO(server->logger, UA_LOGCATEGORY_COMMUNICATION, "Unknown request: NodeId(ns=%d, i=%d)",
  308. requestType.namespaceIndex, requestType.identifier.numeric);
  309. }
  310. UA_RequestHeader p;
  311. UA_ResponseHeader r;
  312. if(UA_RequestHeader_decodeBinary(msg, pos, &p) != UA_STATUSCODE_GOOD)
  313. return;
  314. UA_ResponseHeader_init(&r);
  315. init_response_header(&p, &r);
  316. r.serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
  317. #ifdef EXTENSION_STATELESS
  318. if(retval != UA_STATUSCODE_GOOD)
  319. r.serviceResult = retval;
  320. #endif
  321. UA_RequestHeader_deleteMembers(&p);
  322. retval = connection->getBuffer(connection, &message, headerSize + UA_ResponseHeader_calcSizeBinary(&r));
  323. if(retval != UA_STATUSCODE_GOOD) {
  324. UA_ResponseHeader_deleteMembers(&r);
  325. return;
  326. }
  327. UA_ResponseHeader_encodeBinary(&r, &message, &messagePos);
  328. UA_ResponseHeader_deleteMembers(&r);
  329. response_nodeid = UA_NODEID_NUMERIC(0, UA_NS0ID_RESPONSEHEADER + UA_ENCODINGOFFSET_BINARY);
  330. break;
  331. }
  332. }
  333. messagePos = 0;
  334. respHeader.messageHeader.messageSize = message.length;
  335. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &message, &messagePos);
  336. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, &message, &messagePos);
  337. UA_SequenceHeader_encodeBinary(&seqHeader, &message, &messagePos);
  338. UA_NodeId_encodeBinary(&response_nodeid, &message, &messagePos);
  339. // todo: sign & encrypt
  340. // 5) Send it over the wire.
  341. connection->write(connection, &message);
  342. connection->releaseBuffer(connection, &message);
  343. }
  344. static void processCLO(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg, size_t *pos) {
  345. UA_UInt32 secureChannelId;
  346. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  347. if(retval != UA_STATUSCODE_GOOD || !connection->channel ||
  348. connection->channel->securityToken.channelId != secureChannelId)
  349. return;
  350. Service_CloseSecureChannel(server, secureChannelId);
  351. }
  352. void UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection, UA_ByteString *msg) {
  353. if(msg->length <= 0)
  354. return;
  355. size_t pos = 0;
  356. UA_TcpMessageHeader tcpMessageHeader;
  357. do {
  358. if(UA_TcpMessageHeader_decodeBinary(msg, &pos, &tcpMessageHeader) != UA_STATUSCODE_GOOD) {
  359. UA_LOG_INFO(server->logger, UA_LOGCATEGORY_COMMUNICATION, "Decoding of message header failed");
  360. connection->close(connection);
  361. break;
  362. }
  363. size_t targetpos = pos - 8 + tcpMessageHeader.messageSize;
  364. switch(tcpMessageHeader.messageTypeAndFinal & 0xffffff) {
  365. case UA_MESSAGETYPEANDFINAL_HELF & 0xffffff:
  366. processHEL(connection, msg, &pos);
  367. break;
  368. case UA_MESSAGETYPEANDFINAL_OPNF & 0xffffff:
  369. processOPN(connection, server, msg, &pos);
  370. break;
  371. case UA_MESSAGETYPEANDFINAL_MSGF & 0xffffff:
  372. #ifdef EXTENSION_STATELESS
  373. processMSG(connection, server, msg, &pos);
  374. break;
  375. #endif
  376. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  377. connection->close(connection);
  378. break;
  379. }
  380. processMSG(connection, server, msg, &pos);
  381. break;
  382. case UA_MESSAGETYPEANDFINAL_CLOF & 0xffffff:
  383. processCLO(connection, server, msg, &pos);
  384. connection->close(connection);
  385. return;
  386. }
  387. UA_TcpMessageHeader_deleteMembers(&tcpMessageHeader);
  388. if(pos != targetpos) {
  389. UA_LOG_INFO(server->logger, UA_LOGCATEGORY_COMMUNICATION,
  390. "The message was not entirely processed, skipping to the end");
  391. pos = targetpos;
  392. }
  393. } while(msg->length > (UA_Int32)pos);
  394. }