ua_server_binary.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #include <stdio.h>
  2. #include "ua_server_internal.h"
  3. #include "ua_services.h"
  4. #include "ua_statuscodes.h"
  5. #include "ua_namespace_0.h"
  6. #include "ua_securechannel_manager.h"
  7. #include "ua_session_manager.h"
  8. #include "ua_util.h"
  9. /** Max size of messages that are allocated on the stack */
  10. #define MAX_STACK_MESSAGE 65536
  11. static UA_StatusCode UA_ByteStringArray_deleteMembers(UA_ByteStringArray *stringarray) {
  12. if(!stringarray)
  13. return UA_STATUSCODE_BADINTERNALERROR;
  14. for(UA_UInt32 i = 0;i < stringarray->stringsSize;i++)
  15. UA_String_deleteMembers(&stringarray->strings[i]);
  16. return UA_STATUSCODE_GOOD;
  17. }
  18. static void processHEL(UA_Connection *connection, const UA_ByteString *msg, UA_UInt32 *pos) {
  19. UA_TcpHelloMessage helloMessage;
  20. if(UA_TcpHelloMessage_decodeBinary(msg, pos, &helloMessage) != UA_STATUSCODE_GOOD) {
  21. connection->close(connection);
  22. return;
  23. }
  24. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount;
  25. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize;
  26. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  27. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  28. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  29. connection->state = UA_CONNECTION_ESTABLISHED;
  30. // build acknowledge response
  31. UA_TcpAcknowledgeMessage ackMessage;
  32. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  33. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  34. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  35. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  36. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  37. UA_TcpMessageHeader ackHeader;
  38. ackHeader.messageType = UA_MESSAGETYPE_ACK;
  39. ackHeader.isFinal = 'F';
  40. ackHeader.messageSize = UA_TcpAcknowledgeMessage_calcSizeBinary(&ackMessage) +
  41. UA_TcpMessageHeader_calcSizeBinary(&ackHeader);
  42. // The message is on the stack. That's ok since ack is very small.
  43. UA_ByteString ack_msg = (UA_ByteString){ .length = ackHeader.messageSize,
  44. .data = UA_alloca(ackHeader.messageSize) };
  45. UA_UInt32 tmpPos = 0;
  46. UA_TcpMessageHeader_encodeBinary(&ackHeader, &ack_msg, &tmpPos);
  47. UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &ack_msg, &tmpPos);
  48. UA_ByteStringArray answer_buf = { .stringsSize = 1, .strings = &ack_msg };
  49. // the string is freed internall in the (asynchronous) write
  50. connection->write(connection, answer_buf);
  51. UA_TcpHelloMessage_deleteMembers(&helloMessage);
  52. }
  53. static void processOPN(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg,
  54. UA_UInt32 *pos) {
  55. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  56. connection->close(connection);
  57. return;
  58. }
  59. UA_UInt32 secureChannelId;
  60. UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  61. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  62. UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg, pos, &asymHeader);
  63. UA_SequenceHeader seqHeader;
  64. UA_SequenceHeader_decodeBinary(msg, pos, &seqHeader);
  65. UA_NodeId requestType;
  66. UA_NodeId_decodeBinary(msg, pos, &requestType);
  67. if(requestType.identifier.numeric != 446) {
  68. connection->close(connection);
  69. return;
  70. }
  71. UA_OpenSecureChannelRequest r;
  72. UA_OpenSecureChannelResponse p;
  73. UA_OpenSecureChannelRequest_decodeBinary(msg, pos, &r);
  74. UA_OpenSecureChannelResponse_init(&p);
  75. Service_OpenSecureChannel(server, connection, &r, &p);
  76. /* Response */
  77. UA_SecureConversationMessageHeader respHeader;
  78. respHeader.messageHeader.messageType = UA_MESSAGETYPE_OPN;
  79. respHeader.messageHeader.isFinal = 'F';
  80. respHeader.messageHeader.messageSize = 0;
  81. respHeader.secureChannelId = p.securityToken.channelId;
  82. UA_NodeId responseType = UA_NODEIDS[UA_OPENSECURECHANNELRESPONSE];
  83. responseType.identifier.numeric += UA_ENCODINGOFFSET_BINARY;
  84. respHeader.messageHeader.messageSize =
  85. UA_SecureConversationMessageHeader_calcSizeBinary(&respHeader)
  86. + UA_AsymmetricAlgorithmSecurityHeader_calcSizeBinary(&asymHeader)
  87. + UA_SequenceHeader_calcSizeBinary(&seqHeader)
  88. + UA_NodeId_calcSizeBinary(&responseType)
  89. + UA_OpenSecureChannelResponse_calcSizeBinary(&p);
  90. UA_ByteString resp_msg = (UA_ByteString){ .length = respHeader.messageHeader.messageSize,
  91. .data = UA_alloca(respHeader.messageHeader.messageSize) };
  92. UA_UInt32 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_OpenSecureChannelRequest_deleteMembers(&r);
  99. UA_OpenSecureChannelResponse_deleteMembers(&p);
  100. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  101. connection->write(connection, (UA_ByteStringArray){ .stringsSize = 1, .strings = &resp_msg });
  102. }
  103. static void init_response_header(const UA_RequestHeader *p, UA_ResponseHeader *r) {
  104. r->requestHandle = p->requestHandle;
  105. r->serviceResult = UA_STATUSCODE_GOOD;
  106. r->stringTableSize = 0;
  107. r->timestamp = UA_DateTime_now();
  108. }
  109. #define CHECK_PROCESS(CODE, CLEANUP) \
  110. do { if(CODE != UA_STATUSCODE_GOOD) { \
  111. CLEANUP; \
  112. return; \
  113. } } while(0)
  114. // if the message is small enough, we allocate it on the stack and save a malloc
  115. #define ALLOC_MESSAGE(MESSAGE, SIZE) do { \
  116. UA_UInt32 messageSize = SIZE; \
  117. if(messageSize <= MAX_STACK_MESSAGE) { \
  118. messageOnStack = UA_TRUE; \
  119. *MESSAGE = (UA_ByteString){.length = messageSize, \
  120. .data = UA_alloca(messageSize)}; \
  121. } else \
  122. UA_ByteString_newMembers(MESSAGE, messageSize); \
  123. } while(0)
  124. #define INVOKE_SERVICE(TYPE) do { \
  125. UA_##TYPE##Request p; \
  126. UA_##TYPE##Response r; \
  127. CHECK_PROCESS(UA_##TYPE##Request_decodeBinary(msg, pos, &p),;); \
  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, UA_UInt32 *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_Session *clientSession = UA_NULL;
  143. #ifdef EXTENSION_STATELESS
  144. UA_SecureChannel dummyChannel;
  145. UA_SecureChannel_init(&dummyChannel);
  146. //fixme: why are the following two lines not initialized by the _init function
  147. dummyChannel.securityToken.channelId = 0;
  148. dummyChannel.securityToken.tokenId = 0;
  149. if(secureChannelId == 0 || !clientChannel){
  150. clientChannel = &dummyChannel;
  151. clientSession = &anonymousSession;
  152. }
  153. #endif
  154. if(!clientSession && clientChannel)
  155. clientSession = clientChannel->session;
  156. // 2) Read the security header
  157. UA_UInt32 tokenId;
  158. UA_UInt32_decodeBinary(msg, pos, &tokenId);
  159. UA_SequenceHeader sequenceHeader;
  160. CHECK_PROCESS(UA_SequenceHeader_decodeBinary(msg, pos, &sequenceHeader),; );
  161. clientChannel->sequenceNumber = sequenceHeader.sequenceNumber;
  162. clientChannel->requestId = sequenceHeader.requestId;
  163. // todo
  164. //UA_SecureChannel_checkSequenceNumber(channel,sequenceHeader.sequenceNumber);
  165. //UA_SecureChannel_checkRequestId(channel,sequenceHeader.requestId);
  166. // 3) Read the nodeid of the request
  167. UA_NodeId requestType;
  168. CHECK_PROCESS(UA_NodeId_decodeBinary(msg, pos, &requestType),; );
  169. if(requestType.identifierType != UA_NODEIDTYPE_NUMERIC) {
  170. // if the nodeidtype is numeric, we do not have to free anything
  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. UA_UInt32 sendOffset = 0;
  181. #ifdef EXTENSION_STATELESS
  182. //only some calls allow to be stateless
  183. if(clientSession == &anonymousSession) {
  184. //subtract UA_ENCODINGOFFSET_BINARY for binary encoding
  185. switch(requestType.identifier.numeric - UA_ENCODINGOFFSET_BINARY) {
  186. case UA_READREQUEST_NS0:
  187. INVOKE_SERVICE(Read);
  188. break;
  189. case UA_WRITEREQUEST_NS0:
  190. INVOKE_SERVICE(Write);
  191. break;
  192. case UA_BROWSEREQUEST_NS0:
  193. INVOKE_SERVICE(Browse);
  194. break;
  195. default: {
  196. printf("SL_processMessage - stateless call for an unknown or not allowed request, namespace=%d, request=%d\n",
  197. requestType.namespaceIndex, requestType.identifier.numeric);
  198. UA_RequestHeader p;
  199. UA_ResponseHeader r;
  200. CHECK_PROCESS(UA_RequestHeader_decodeBinary(msg, pos, &p),; );
  201. UA_ResponseHeader_init(&r);
  202. init_response_header(&p, &r);
  203. r.serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
  204. ALLOC_MESSAGE(message, UA_ResponseHeader_calcSizeBinary(&r));
  205. UA_ResponseHeader_encodeBinary(&r, message, &sendOffset);
  206. UA_RequestHeader_deleteMembers(&p);
  207. UA_ResponseHeader_deleteMembers(&r);
  208. responseType = UA_NODEIDS[UA_RESPONSEHEADER].identifier.numeric + UA_ENCODINGOFFSET_BINARY; }
  209. break;
  210. }
  211. } else {
  212. #endif
  213. //non-stateless service calls
  214. //subtract UA_ENCODINGOFFSET_BINARY for binary encoding
  215. switch(requestType.identifier.numeric - UA_ENCODINGOFFSET_BINARY) {
  216. case UA_GETENDPOINTSREQUEST_NS0: {
  217. UA_GetEndpointsRequest p;
  218. UA_GetEndpointsResponse r;
  219. CHECK_PROCESS(UA_GetEndpointsRequest_decodeBinary(msg, pos, &p),; );
  220. UA_GetEndpointsResponse_init(&r);
  221. init_response_header(&p.requestHeader, &r.responseHeader);
  222. Service_GetEndpoints(server, &p, &r);
  223. ALLOC_MESSAGE(message, UA_GetEndpointsResponse_calcSizeBinary(&r));
  224. UA_GetEndpointsResponse_encodeBinary(&r, message, &sendOffset);
  225. UA_GetEndpointsRequest_deleteMembers(&p);
  226. UA_GetEndpointsResponse_deleteMembers(&r);
  227. responseType = requestType.identifier.numeric + 3;
  228. break;
  229. }
  230. case UA_CREATESESSIONREQUEST_NS0: {
  231. UA_CreateSessionRequest p;
  232. UA_CreateSessionResponse r;
  233. CHECK_PROCESS(UA_CreateSessionRequest_decodeBinary(msg, pos, &p),; );
  234. UA_CreateSessionResponse_init(&r);
  235. init_response_header(&p.requestHeader, &r.responseHeader);
  236. Service_CreateSession(server, clientChannel, &p, &r);
  237. ALLOC_MESSAGE(message, UA_CreateSessionResponse_calcSizeBinary(&r));
  238. UA_CreateSessionResponse_encodeBinary(&r, message, &sendOffset);
  239. UA_CreateSessionRequest_deleteMembers(&p);
  240. UA_CreateSessionResponse_deleteMembers(&r);
  241. responseType = requestType.identifier.numeric + 3;
  242. break;
  243. }
  244. case UA_ACTIVATESESSIONREQUEST_NS0: {
  245. UA_ActivateSessionRequest p;
  246. UA_ActivateSessionResponse r;
  247. CHECK_PROCESS(UA_ActivateSessionRequest_decodeBinary(msg, pos, &p),; );
  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_CLOSESESSIONREQUEST_NS0: {
  259. UA_CloseSessionRequest p;
  260. UA_CloseSessionResponse r;
  261. CHECK_PROCESS(UA_CloseSessionRequest_decodeBinary(msg, pos, &p),; );
  262. UA_CloseSessionResponse_init(&r);
  263. init_response_header(&p.requestHeader, &r.responseHeader);
  264. Service_CloseSession(server, &p, &r);
  265. ALLOC_MESSAGE(message, UA_CloseSessionResponse_calcSizeBinary(&r));
  266. UA_CloseSessionResponse_encodeBinary(&r, message, &sendOffset);
  267. UA_CloseSessionRequest_deleteMembers(&p);
  268. UA_CloseSessionResponse_deleteMembers(&r);
  269. responseType = requestType.identifier.numeric + 3;
  270. break;
  271. }
  272. case UA_READREQUEST_NS0:
  273. INVOKE_SERVICE(Read);
  274. break;
  275. case UA_WRITEREQUEST_NS0:
  276. INVOKE_SERVICE(Write);
  277. break;
  278. case UA_BROWSEREQUEST_NS0:
  279. INVOKE_SERVICE(Browse);
  280. break;
  281. case UA_ADDREFERENCESREQUEST_NS0:
  282. INVOKE_SERVICE(AddReferences);
  283. break;
  284. case UA_TRANSLATEBROWSEPATHSTONODEIDSREQUEST_NS0:
  285. INVOKE_SERVICE(TranslateBrowsePathsToNodeIds);
  286. break;
  287. default: {
  288. printf("SL_processMessage - unknown request, namespace=%d, request=%d\n",
  289. requestType.namespaceIndex, requestType.identifier.numeric);
  290. UA_RequestHeader p;
  291. UA_ResponseHeader r;
  292. CHECK_PROCESS(UA_RequestHeader_decodeBinary(msg, pos, &p),; );
  293. UA_ResponseHeader_init(&r);
  294. init_response_header(&p, &r);
  295. r.serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
  296. ALLOC_MESSAGE(message, UA_ResponseHeader_calcSizeBinary(&r));
  297. UA_ResponseHeader_encodeBinary(&r, message, &sendOffset);
  298. UA_RequestHeader_deleteMembers(&p);
  299. UA_ResponseHeader_deleteMembers(&r);
  300. responseType = UA_NODEIDS[UA_RESPONSEHEADER].identifier.numeric + UA_ENCODINGOFFSET_BINARY;
  301. }
  302. break;
  303. }
  304. #ifdef EXTENSION_STATELESS
  305. }
  306. #endif
  307. // 5) Build the header
  308. UA_SecureConversationMessageHeader respHeader;
  309. respHeader.messageHeader.messageType = UA_MESSAGETYPE_MSG;
  310. respHeader.messageHeader.isFinal = 'F';
  311. respHeader.messageHeader.messageSize = 0;
  312. respHeader.secureChannelId = clientChannel->securityToken.channelId;
  313. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  314. symSecHeader.tokenId = clientChannel->securityToken.tokenId;
  315. UA_SequenceHeader seqHeader;
  316. seqHeader.sequenceNumber = clientChannel->sequenceNumber;
  317. seqHeader.requestId = clientChannel->requestId;
  318. UA_NodeId response_nodeid = { .namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC,
  319. .identifier.numeric = responseType };
  320. UA_UInt32 headerSize =
  321. UA_SecureConversationMessageHeader_calcSizeBinary(&respHeader)
  322. + UA_SymmetricAlgorithmSecurityHeader_calcSizeBinary(&symSecHeader)
  323. + UA_SequenceHeader_calcSizeBinary(&seqHeader)
  324. + UA_NodeId_calcSizeBinary(&response_nodeid);
  325. *header = (UA_ByteString){ .length = headerSize, .data = UA_alloca(headerSize) };
  326. respHeader.messageHeader.messageSize = header->length + message->length;
  327. UA_UInt32 rpos = 0;
  328. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, header, &rpos);
  329. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, header, &rpos);
  330. UA_SequenceHeader_encodeBinary(&seqHeader, header, &rpos);
  331. UA_NodeId_encodeBinary(&response_nodeid, header, &rpos);
  332. // todo: sign & encrypt
  333. // 6) Send it over the wire.
  334. UA_ByteStringArray responseBufArray;
  335. responseBufArray.strings = responseBufs;
  336. responseBufArray.stringsSize = 2;
  337. connection->write(connection, responseBufArray);
  338. if(!messageOnStack)
  339. UA_free(message->data);
  340. }
  341. static void processCLO(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg,
  342. UA_UInt32 *pos) {
  343. UA_UInt32 secureChannelId;
  344. UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  345. if(!connection->channel || connection->channel->securityToken.channelId != secureChannelId)
  346. return;
  347. Service_CloseSecureChannel(server, secureChannelId);
  348. }
  349. void UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection, const UA_ByteString *msg) {
  350. UA_UInt32 pos = 0;
  351. UA_TcpMessageHeader tcpMessageHeader;
  352. do {
  353. if(UA_TcpMessageHeader_decodeBinary(msg, &pos, &tcpMessageHeader) != UA_STATUSCODE_GOOD) {
  354. printf("ERROR: decoding of header failed \n");
  355. connection->close(connection);
  356. break;
  357. }
  358. UA_UInt32 targetpos = pos - 8 + tcpMessageHeader.messageSize;
  359. switch(tcpMessageHeader.messageType) {
  360. case UA_MESSAGETYPE_HEL:
  361. processHEL(connection, msg, &pos);
  362. break;
  363. case UA_MESSAGETYPE_OPN:
  364. processOPN(connection, server, msg, &pos);
  365. break;
  366. case UA_MESSAGETYPE_MSG:
  367. #ifndef EXTENSION_STATELESS
  368. if(connection->state == UA_CONNECTION_ESTABLISHED && connection->channel != UA_NULL)
  369. processMSG(connection, server, msg, &pos);
  370. else
  371. connection->close(connection);
  372. #else
  373. processMSG(connection, server, msg, &pos);
  374. #endif
  375. break;
  376. case UA_MESSAGETYPE_CLO:
  377. processCLO(connection, server, msg, &pos);
  378. connection->close(connection);
  379. return;
  380. }
  381. UA_TcpMessageHeader_deleteMembers(&tcpMessageHeader);
  382. if(pos != targetpos) {
  383. printf("The message size was not as announced or the message could not be processed, skipping to the end of the message.\n");
  384. pos = targetpos;
  385. }
  386. } while(msg->length > (UA_Int32)pos);
  387. }