ua_server_binary.c 18 KB

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