ua_server_binary.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #include <stdio.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_util.h"
  10. #include "ua_nodeids.h"
  11. /** Max size of messages that are allocated on the stack */
  12. #define MAX_STACK_MESSAGE 65536
  13. static UA_StatusCode UA_ByteStringArray_deleteMembers(UA_ByteStringArray *stringarray) {
  14. if(!stringarray)
  15. return UA_STATUSCODE_BADINTERNALERROR;
  16. for(UA_UInt32 i = 0; i < stringarray->stringsSize; i++)
  17. UA_String_deleteMembers(&stringarray->strings[i]);
  18. return UA_STATUSCODE_GOOD;
  19. }
  20. static void processHEL(UA_Connection *connection, const UA_ByteString *msg, size_t *pos) {
  21. UA_TcpHelloMessage helloMessage;
  22. if(UA_TcpHelloMessage_decodeBinary(msg, pos, &helloMessage) != UA_STATUSCODE_GOOD) {
  23. connection->close(connection);
  24. return;
  25. }
  26. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount;
  27. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize;
  28. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  29. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  30. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  31. connection->state = UA_CONNECTION_ESTABLISHED;
  32. // build acknowledge response
  33. UA_TcpAcknowledgeMessage ackMessage;
  34. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  35. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  36. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  37. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  38. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  39. UA_TcpMessageHeader ackHeader;
  40. ackHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_ACKF;
  41. ackHeader.messageSize = UA_TcpAcknowledgeMessage_calcSizeBinary(&ackMessage) +
  42. UA_TcpMessageHeader_calcSizeBinary(&ackHeader);
  43. // The message is on the stack. That's ok since ack is very small.
  44. UA_ByteString ack_msg = (UA_ByteString){
  45. .length = ackHeader.messageSize,
  46. .data = UA_alloca(ackHeader.messageSize)
  47. };
  48. size_t tmpPos = 0;
  49. UA_TcpMessageHeader_encodeBinary(&ackHeader, &ack_msg, &tmpPos);
  50. UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &ack_msg, &tmpPos);
  51. UA_ByteStringArray answer_buf = { .stringsSize = 1, .strings = &ack_msg };
  52. // the string is freed internall in the (asynchronous) write
  53. connection->write(connection, answer_buf);
  54. UA_TcpHelloMessage_deleteMembers(&helloMessage);
  55. }
  56. static void processOPN(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg,
  57. size_t *pos) {
  58. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  59. connection->close(connection);
  60. return;
  61. }
  62. UA_UInt32 secureChannelId;
  63. UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  64. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  65. UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg, pos, &asymHeader);
  66. UA_SequenceHeader seqHeader;
  67. UA_SequenceHeader_decodeBinary(msg, pos, &seqHeader);
  68. UA_NodeId requestType;
  69. UA_NodeId_decodeBinary(msg, pos, &requestType);
  70. if(requestType.identifier.numeric != 446) {
  71. connection->close(connection);
  72. return;
  73. }
  74. UA_OpenSecureChannelRequest r;
  75. UA_OpenSecureChannelResponse p;
  76. UA_OpenSecureChannelRequest_decodeBinary(msg, pos, &r);
  77. UA_OpenSecureChannelResponse_init(&p);
  78. Service_OpenSecureChannel(server, connection, &r, &p);
  79. /* Response */
  80. UA_SecureConversationMessageHeader respHeader;
  81. respHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_OPNF;
  82. respHeader.messageHeader.messageSize = 0;
  83. respHeader.secureChannelId = p.securityToken.channelId;
  84. UA_NodeId responseType = UA_NODEID_STATIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE);
  85. responseType.identifier.numeric += UA_ENCODINGOFFSET_BINARY;
  86. respHeader.messageHeader.messageSize =
  87. UA_SecureConversationMessageHeader_calcSizeBinary(&respHeader)
  88. + UA_AsymmetricAlgorithmSecurityHeader_calcSizeBinary(&asymHeader)
  89. + UA_SequenceHeader_calcSizeBinary(&seqHeader)
  90. + UA_NodeId_calcSizeBinary(&responseType)
  91. + UA_OpenSecureChannelResponse_calcSizeBinary(&p);
  92. UA_ByteString resp_msg = (UA_ByteString){
  93. .length = respHeader.messageHeader.messageSize,
  94. .data = UA_alloca(respHeader.messageHeader.messageSize)
  95. };
  96. size_t tmpPos = 0;
  97. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &resp_msg, &tmpPos);
  98. UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &resp_msg, &tmpPos); // just mirror back
  99. UA_SequenceHeader_encodeBinary(&seqHeader, &resp_msg, &tmpPos); // just mirror back
  100. UA_NodeId_encodeBinary(&responseType, &resp_msg, &tmpPos);
  101. UA_OpenSecureChannelResponse_encodeBinary(&p, &resp_msg, &tmpPos);
  102. UA_OpenSecureChannelRequest_deleteMembers(&r);
  103. UA_OpenSecureChannelResponse_deleteMembers(&p);
  104. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  105. connection->write(connection, (UA_ByteStringArray){ .stringsSize = 1, .strings = &resp_msg });
  106. }
  107. static void init_response_header(const UA_RequestHeader *p, UA_ResponseHeader *r) {
  108. r->requestHandle = p->requestHandle;
  109. r->serviceResult = UA_STATUSCODE_GOOD;
  110. r->stringTableSize = 0;
  111. r->timestamp = UA_DateTime_now();
  112. }
  113. // if the message is small enough, we allocate it on the stack and save a malloc
  114. #define ALLOC_MESSAGE(MESSAGE, SIZE) do { \
  115. UA_UInt32 messageSize = SIZE; \
  116. if(messageSize <= MAX_STACK_MESSAGE) { \
  117. messageOnStack = UA_TRUE; \
  118. *MESSAGE = (UA_ByteString){.length = messageSize, \
  119. .data = UA_alloca(messageSize)}; \
  120. } else \
  121. UA_ByteString_newMembers(MESSAGE, messageSize); \
  122. } while(0)
  123. #define INVOKE_SERVICE(TYPE) do { \
  124. UA_##TYPE##Request p; \
  125. UA_##TYPE##Response r; \
  126. if(UA_##TYPE##Request_decodeBinary(msg, pos, &p)) \
  127. return; \
  128. UA_##TYPE##Response_init(&r); \
  129. init_response_header(&p.requestHeader, &r.responseHeader); \
  130. Service_##TYPE(server, clientSession, &p, &r); \
  131. ALLOC_MESSAGE(message, UA_##TYPE##Response_calcSizeBinary(&r)); \
  132. UA_##TYPE##Response_encodeBinary(&r, message, &sendOffset); \
  133. UA_##TYPE##Request_deleteMembers(&p); \
  134. UA_##TYPE##Response_deleteMembers(&r); \
  135. responseType = requestType.identifier.numeric + 3; \
  136. } while(0)
  137. static void processMSG(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg, size_t *pos) {
  138. // 1) Read in the securechannel
  139. UA_UInt32 secureChannelId;
  140. UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  141. UA_SecureChannel *clientChannel = connection->channel;
  142. UA_SecureChannel anonymousChannel;
  143. if(!clientChannel) {
  144. UA_SecureChannel_init(&anonymousChannel);
  145. clientChannel = &anonymousChannel;
  146. }
  147. UA_Session *clientSession = clientChannel->session;
  148. #ifdef EXTENSION_STATELESS
  149. if(secureChannelId == 0)
  150. clientSession = &anonymousSession;
  151. #endif
  152. // 2) Read the security header
  153. UA_UInt32 tokenId;
  154. UA_SequenceHeader sequenceHeader;
  155. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &tokenId);
  156. retval |= UA_SequenceHeader_decodeBinary(msg, pos, &sequenceHeader);
  157. if(retval != UA_STATUSCODE_GOOD)
  158. return;
  159. //UA_SecureChannel_checkSequenceNumber(channel,sequenceHeader.sequenceNumber);
  160. //UA_SecureChannel_checkRequestId(channel,sequenceHeader.requestId);
  161. if(clientChannel) {
  162. clientChannel->sequenceNumber = sequenceHeader.sequenceNumber;
  163. clientChannel->requestId = sequenceHeader.requestId;
  164. }
  165. // 3) Read the nodeid of the request
  166. UA_NodeId requestType;
  167. if(UA_NodeId_decodeBinary(msg, pos, &requestType))
  168. return;
  169. if(requestType.identifierType != UA_NODEIDTYPE_NUMERIC) {
  170. // That must not happen. The requestType does not have to be deleted at the end.
  171. UA_NodeId_deleteMembers(&requestType);
  172. return;
  173. }
  174. // 4) process the request
  175. UA_ByteString responseBufs[2]; // 0->header, 1->response payload
  176. UA_UInt32 responseType;
  177. UA_ByteString *header = &responseBufs[0];
  178. UA_ByteString *message = &responseBufs[1];
  179. UA_Boolean messageOnStack = UA_FALSE;
  180. size_t sendOffset = 0;
  181. #ifdef EXTENSION_STATELESS
  182. switch(requestType.identifier.numeric - UA_ENCODINGOFFSET_BINARY) {
  183. case UA_NS0ID_READREQUEST:
  184. case UA_NS0ID_WRITEREQUEST:
  185. case UA_NS0ID_BROWSEREQUEST:
  186. break;
  187. default:
  188. if(clientSession != &anonymousSession)
  189. retval = UA_STATUSCODE_BADNOTCONNECTED;
  190. }
  191. #endif
  192. //subtract UA_ENCODINGOFFSET_BINARY for binary encoding, if retval is set, this forces the default path
  193. switch(requestType.identifier.numeric - UA_ENCODINGOFFSET_BINARY + retval) {
  194. case UA_NS0ID_GETENDPOINTSREQUEST: {
  195. UA_GetEndpointsRequest p;
  196. UA_GetEndpointsResponse r;
  197. if(UA_GetEndpointsRequest_decodeBinary(msg, pos, &p))
  198. return;
  199. UA_GetEndpointsResponse_init(&r);
  200. init_response_header(&p.requestHeader, &r.responseHeader);
  201. Service_GetEndpoints(server, &p, &r);
  202. ALLOC_MESSAGE(message, UA_GetEndpointsResponse_calcSizeBinary(&r));
  203. UA_GetEndpointsResponse_encodeBinary(&r, message, &sendOffset);
  204. UA_GetEndpointsRequest_deleteMembers(&p);
  205. UA_GetEndpointsResponse_deleteMembers(&r);
  206. responseType = requestType.identifier.numeric + 3;
  207. break;
  208. }
  209. case UA_NS0ID_CREATESESSIONREQUEST: {
  210. UA_CreateSessionRequest p;
  211. UA_CreateSessionResponse r;
  212. if(UA_CreateSessionRequest_decodeBinary(msg, pos, &p))
  213. return;
  214. UA_CreateSessionResponse_init(&r);
  215. init_response_header(&p.requestHeader, &r.responseHeader);
  216. Service_CreateSession(server, clientChannel, &p, &r);
  217. ALLOC_MESSAGE(message, UA_CreateSessionResponse_calcSizeBinary(&r));
  218. UA_CreateSessionResponse_encodeBinary(&r, message, &sendOffset);
  219. UA_CreateSessionRequest_deleteMembers(&p);
  220. UA_CreateSessionResponse_deleteMembers(&r);
  221. responseType = requestType.identifier.numeric + 3;
  222. break;
  223. }
  224. case UA_NS0ID_ACTIVATESESSIONREQUEST: {
  225. UA_ActivateSessionRequest p;
  226. UA_ActivateSessionResponse r;
  227. if(UA_ActivateSessionRequest_decodeBinary(msg, pos, &p))
  228. return;
  229. UA_ActivateSessionResponse_init(&r);
  230. init_response_header(&p.requestHeader, &r.responseHeader);
  231. Service_ActivateSession(server, clientChannel, &p, &r);
  232. ALLOC_MESSAGE(message, UA_ActivateSessionResponse_calcSizeBinary(&r));
  233. UA_ActivateSessionResponse_encodeBinary(&r, message, &sendOffset);
  234. UA_ActivateSessionRequest_deleteMembers(&p);
  235. UA_ActivateSessionResponse_deleteMembers(&r);
  236. responseType = requestType.identifier.numeric + 3;
  237. break;
  238. }
  239. case UA_NS0ID_CLOSESESSIONREQUEST: {
  240. UA_CloseSessionRequest p;
  241. UA_CloseSessionResponse r;
  242. if(UA_CloseSessionRequest_decodeBinary(msg, pos, &p))
  243. return;
  244. UA_CloseSessionResponse_init(&r);
  245. init_response_header(&p.requestHeader, &r.responseHeader);
  246. Service_CloseSession(server, &p, &r);
  247. ALLOC_MESSAGE(message, UA_CloseSessionResponse_calcSizeBinary(&r));
  248. UA_CloseSessionResponse_encodeBinary(&r, message, &sendOffset);
  249. UA_CloseSessionRequest_deleteMembers(&p);
  250. UA_CloseSessionResponse_deleteMembers(&r);
  251. responseType = requestType.identifier.numeric + 3;
  252. break;
  253. }
  254. case UA_NS0ID_READREQUEST:
  255. INVOKE_SERVICE(Read);
  256. break;
  257. case UA_NS0ID_WRITEREQUEST:
  258. INVOKE_SERVICE(Write);
  259. break;
  260. case UA_NS0ID_BROWSEREQUEST:
  261. INVOKE_SERVICE(Browse);
  262. break;
  263. case UA_NS0ID_ADDREFERENCESREQUEST:
  264. INVOKE_SERVICE(AddReferences);
  265. break;
  266. case UA_NS0ID_TRANSLATEBROWSEPATHSTONODEIDSREQUEST:
  267. INVOKE_SERVICE(TranslateBrowsePathsToNodeIds);
  268. break;
  269. default: {
  270. char logmsg[512];
  271. sprintf(logmsg, "SL_processMessage - unknown request, namespace=%d, request=%d\n",
  272. requestType.namespaceIndex, requestType.identifier.numeric);
  273. UA_LOG_INFO(server->logger, UA_LOGGERCATEGORY_CONNECTION, logmsg);
  274. UA_RequestHeader p;
  275. UA_ResponseHeader r;
  276. if(UA_RequestHeader_decodeBinary(msg, pos, &p))
  277. return;
  278. UA_ResponseHeader_init(&r);
  279. init_response_header(&p, &r);
  280. if(retval == UA_STATUSCODE_GOOD)
  281. r.serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
  282. else
  283. r.serviceResult = retval;
  284. ALLOC_MESSAGE(message, UA_ResponseHeader_calcSizeBinary(&r));
  285. UA_ResponseHeader_encodeBinary(&r, message, &sendOffset);
  286. UA_RequestHeader_deleteMembers(&p);
  287. UA_ResponseHeader_deleteMembers(&r);
  288. responseType = UA_NS0ID_RESPONSEHEADER + UA_ENCODINGOFFSET_BINARY;
  289. break;
  290. }
  291. }
  292. // 5) Build the header
  293. UA_SecureConversationMessageHeader respHeader;
  294. respHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_MSGF;
  295. respHeader.messageHeader.messageSize = 0;
  296. respHeader.secureChannelId = clientChannel->securityToken.channelId;
  297. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  298. symSecHeader.tokenId = clientChannel->securityToken.tokenId;
  299. UA_SequenceHeader seqHeader;
  300. seqHeader.sequenceNumber = clientChannel->sequenceNumber;
  301. seqHeader.requestId = clientChannel->requestId;
  302. UA_NodeId response_nodeid = { .namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC,
  303. .identifier.numeric = responseType };
  304. UA_UInt32 headerSize =
  305. UA_SecureConversationMessageHeader_calcSizeBinary(&respHeader)
  306. + UA_SymmetricAlgorithmSecurityHeader_calcSizeBinary(&symSecHeader)
  307. + UA_SequenceHeader_calcSizeBinary(&seqHeader)
  308. + UA_NodeId_calcSizeBinary(&response_nodeid);
  309. *header = (UA_ByteString){ .length = headerSize, .data = UA_alloca(headerSize) };
  310. respHeader.messageHeader.messageSize = header->length + message->length;
  311. size_t rpos = 0;
  312. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, header, &rpos);
  313. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, header, &rpos);
  314. UA_SequenceHeader_encodeBinary(&seqHeader, header, &rpos);
  315. UA_NodeId_encodeBinary(&response_nodeid, header, &rpos);
  316. // todo: sign & encrypt
  317. // 6) Send it over the wire.
  318. UA_ByteStringArray responseBufArray;
  319. responseBufArray.strings = responseBufs;
  320. responseBufArray.stringsSize = 2;
  321. connection->write(connection, responseBufArray);
  322. if(!messageOnStack)
  323. UA_free(message->data);
  324. }
  325. static void processCLO(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg,
  326. size_t *pos) {
  327. UA_UInt32 secureChannelId;
  328. UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  329. if(!connection->channel || connection->channel->securityToken.channelId != secureChannelId)
  330. return;
  331. Service_CloseSecureChannel(server, secureChannelId);
  332. }
  333. void UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection, const UA_ByteString *msg) {
  334. size_t pos = 0;
  335. UA_TcpMessageHeader tcpMessageHeader;
  336. do {
  337. if(UA_TcpMessageHeader_decodeBinary(msg, &pos, &tcpMessageHeader) != UA_STATUSCODE_GOOD) {
  338. printf("ERROR: decoding of header failed \n");
  339. connection->close(connection);
  340. break;
  341. }
  342. size_t targetpos = pos - 8 + tcpMessageHeader.messageSize;
  343. switch(tcpMessageHeader.messageTypeAndFinal & 0xffffff) {
  344. case UA_MESSAGETYPEANDFINAL_HELF & 0xffffff:
  345. processHEL(connection, msg, &pos);
  346. break;
  347. case UA_MESSAGETYPEANDFINAL_OPNF & 0xffffff:
  348. processOPN(connection, server, msg, &pos);
  349. break;
  350. case UA_MESSAGETYPEANDFINAL_MSGF & 0xffffff:
  351. #ifdef EXTENSION_STATELESS
  352. processMSG(connection, server, msg, &pos);
  353. break;
  354. #endif
  355. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  356. connection->close(connection);
  357. break;
  358. }
  359. processMSG(connection, server, msg, &pos);
  360. break;
  361. case UA_MESSAGETYPEANDFINAL_CLOF & 0xffffff:
  362. processCLO(connection, server, msg, &pos);
  363. connection->close(connection);
  364. return;
  365. }
  366. UA_TcpMessageHeader_deleteMembers(&tcpMessageHeader);
  367. if(pos != targetpos) {
  368. printf("The message size was not as announced or the message could not be processed, skipping to the end of the message.\n");
  369. pos = targetpos;
  370. }
  371. } while(msg->length > (UA_Int32)pos);
  372. }