ua_server_binary.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. #include "ua_util.h"
  5. #include "ua_server_internal.h"
  6. #include "ua_services.h"
  7. #include "ua_securechannel_manager.h"
  8. #include "ua_session_manager.h"
  9. #include "ua_types_generated_encoding_binary.h"
  10. #include "ua_transport_generated.h"
  11. #include "ua_transport_generated_handling.h"
  12. #include "ua_transport_generated_encoding_binary.h"
  13. /********************/
  14. /* Helper Functions */
  15. /********************/
  16. static void
  17. sendError(UA_SecureChannel *channel, const UA_ByteString *msg,
  18. size_t offset, const UA_DataType *responseType,
  19. UA_UInt32 requestId, UA_StatusCode error) {
  20. UA_RequestHeader requestHeader;
  21. UA_StatusCode retval = UA_RequestHeader_decodeBinary(msg, &offset, &requestHeader);
  22. if(retval != UA_STATUSCODE_GOOD)
  23. return;
  24. void *response = UA_alloca(responseType->memSize);
  25. UA_init(response, responseType);
  26. UA_ResponseHeader *responseHeader = (UA_ResponseHeader*)response;
  27. responseHeader->requestHandle = requestHeader.requestHandle;
  28. responseHeader->timestamp = UA_DateTime_now();
  29. responseHeader->serviceResult = error;
  30. UA_SecureChannel_sendBinaryMessage(channel, requestId, response, responseType);
  31. UA_RequestHeader_deleteMembers(&requestHeader);
  32. UA_ResponseHeader_deleteMembers(responseHeader);
  33. }
  34. static void
  35. getServicePointers(UA_UInt32 requestTypeId, const UA_DataType **requestType,
  36. const UA_DataType **responseType, UA_Service *service,
  37. UA_Boolean *requiresSession) {
  38. switch(requestTypeId) {
  39. case UA_NS0ID_GETENDPOINTSREQUEST_ENCODING_DEFAULTBINARY:
  40. *service = (UA_Service)Service_GetEndpoints;
  41. *requestType = &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST];
  42. *responseType = &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE];
  43. *requiresSession = false;
  44. break;
  45. case UA_NS0ID_FINDSERVERSREQUEST_ENCODING_DEFAULTBINARY:
  46. *service = (UA_Service)Service_FindServers;
  47. *requestType = &UA_TYPES[UA_TYPES_FINDSERVERSREQUEST];
  48. *responseType = &UA_TYPES[UA_TYPES_FINDSERVERSRESPONSE];
  49. *requiresSession = false;
  50. break;
  51. #ifdef UA_ENABLE_DISCOVERY
  52. # ifdef UA_ENABLE_DISCOVERY_MULTICAST
  53. case UA_NS0ID_FINDSERVERSONNETWORKREQUEST_ENCODING_DEFAULTBINARY:
  54. *service = (UA_Service)Service_FindServersOnNetwork;
  55. *requestType = &UA_TYPES[UA_TYPES_FINDSERVERSONNETWORKREQUEST];
  56. *responseType = &UA_TYPES[UA_TYPES_FINDSERVERSONNETWORKRESPONSE];
  57. *requiresSession = false;
  58. break;
  59. # endif
  60. case UA_NS0ID_REGISTERSERVERREQUEST_ENCODING_DEFAULTBINARY:
  61. *service = (UA_Service)Service_RegisterServer;
  62. *requestType = &UA_TYPES[UA_TYPES_REGISTERSERVERREQUEST];
  63. *responseType = &UA_TYPES[UA_TYPES_REGISTERSERVERRESPONSE];
  64. *requiresSession = false;
  65. break;
  66. case UA_NS0ID_REGISTERSERVER2REQUEST_ENCODING_DEFAULTBINARY:
  67. *service = (UA_Service)Service_RegisterServer2;
  68. *requestType = &UA_TYPES[UA_TYPES_REGISTERSERVER2REQUEST];
  69. *responseType = &UA_TYPES[UA_TYPES_REGISTERSERVER2RESPONSE];
  70. *requiresSession = false;
  71. break;
  72. #endif
  73. case UA_NS0ID_CREATESESSIONREQUEST_ENCODING_DEFAULTBINARY:
  74. *service = (UA_Service)Service_CreateSession;
  75. *requestType = &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST];
  76. *responseType = &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE];
  77. *requiresSession = false;
  78. break;
  79. case UA_NS0ID_ACTIVATESESSIONREQUEST_ENCODING_DEFAULTBINARY:
  80. *service = (UA_Service)Service_ActivateSession;
  81. *requestType = &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST];
  82. *responseType = &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE];
  83. break;
  84. case UA_NS0ID_CLOSESESSIONREQUEST_ENCODING_DEFAULTBINARY:
  85. *service = (UA_Service)Service_CloseSession;
  86. *requestType = &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST];
  87. *responseType = &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE];
  88. break;
  89. case UA_NS0ID_READREQUEST_ENCODING_DEFAULTBINARY:
  90. *service = (UA_Service)Service_Read;
  91. *requestType = &UA_TYPES[UA_TYPES_READREQUEST];
  92. *responseType = &UA_TYPES[UA_TYPES_READRESPONSE];
  93. break;
  94. case UA_NS0ID_WRITEREQUEST_ENCODING_DEFAULTBINARY:
  95. *service = (UA_Service)Service_Write;
  96. *requestType = &UA_TYPES[UA_TYPES_WRITEREQUEST];
  97. *responseType = &UA_TYPES[UA_TYPES_WRITERESPONSE];
  98. break;
  99. case UA_NS0ID_BROWSEREQUEST_ENCODING_DEFAULTBINARY:
  100. *service = (UA_Service)Service_Browse;
  101. *requestType = &UA_TYPES[UA_TYPES_BROWSEREQUEST];
  102. *responseType = &UA_TYPES[UA_TYPES_BROWSERESPONSE];
  103. break;
  104. case UA_NS0ID_BROWSENEXTREQUEST_ENCODING_DEFAULTBINARY:
  105. *service = (UA_Service)Service_BrowseNext;
  106. *requestType = &UA_TYPES[UA_TYPES_BROWSENEXTREQUEST];
  107. *responseType = &UA_TYPES[UA_TYPES_BROWSENEXTRESPONSE];
  108. break;
  109. case UA_NS0ID_REGISTERNODESREQUEST_ENCODING_DEFAULTBINARY:
  110. *service = (UA_Service)Service_RegisterNodes;
  111. *requestType = &UA_TYPES[UA_TYPES_REGISTERNODESREQUEST];
  112. *responseType = &UA_TYPES[UA_TYPES_REGISTERNODESRESPONSE];
  113. break;
  114. case UA_NS0ID_UNREGISTERNODESREQUEST_ENCODING_DEFAULTBINARY:
  115. *service = (UA_Service)Service_UnregisterNodes;
  116. *requestType = &UA_TYPES[UA_TYPES_UNREGISTERNODESREQUEST];
  117. *responseType = &UA_TYPES[UA_TYPES_UNREGISTERNODESRESPONSE];
  118. break;
  119. case UA_NS0ID_TRANSLATEBROWSEPATHSTONODEIDSREQUEST_ENCODING_DEFAULTBINARY:
  120. *service = (UA_Service)Service_TranslateBrowsePathsToNodeIds;
  121. *requestType = &UA_TYPES[UA_TYPES_TRANSLATEBROWSEPATHSTONODEIDSREQUEST];
  122. *responseType = &UA_TYPES[UA_TYPES_TRANSLATEBROWSEPATHSTONODEIDSRESPONSE];
  123. break;
  124. #ifdef UA_ENABLE_SUBSCRIPTIONS
  125. case UA_NS0ID_CREATESUBSCRIPTIONREQUEST_ENCODING_DEFAULTBINARY:
  126. *service = (UA_Service)Service_CreateSubscription;
  127. *requestType = &UA_TYPES[UA_TYPES_CREATESUBSCRIPTIONREQUEST];
  128. *responseType = &UA_TYPES[UA_TYPES_CREATESUBSCRIPTIONRESPONSE];
  129. break;
  130. case UA_NS0ID_PUBLISHREQUEST_ENCODING_DEFAULTBINARY:
  131. *requestType = &UA_TYPES[UA_TYPES_PUBLISHREQUEST];
  132. *responseType = &UA_TYPES[UA_TYPES_PUBLISHRESPONSE];
  133. break;
  134. case UA_NS0ID_REPUBLISHREQUEST_ENCODING_DEFAULTBINARY:
  135. *service = (UA_Service)Service_Republish;
  136. *requestType = &UA_TYPES[UA_TYPES_REPUBLISHREQUEST];
  137. *responseType = &UA_TYPES[UA_TYPES_REPUBLISHRESPONSE];
  138. break;
  139. case UA_NS0ID_MODIFYSUBSCRIPTIONREQUEST_ENCODING_DEFAULTBINARY:
  140. *service = (UA_Service)Service_ModifySubscription;
  141. *requestType = &UA_TYPES[UA_TYPES_MODIFYSUBSCRIPTIONREQUEST];
  142. *responseType = &UA_TYPES[UA_TYPES_MODIFYSUBSCRIPTIONRESPONSE];
  143. break;
  144. case UA_NS0ID_SETPUBLISHINGMODEREQUEST_ENCODING_DEFAULTBINARY:
  145. *service = (UA_Service)Service_SetPublishingMode;
  146. *requestType = &UA_TYPES[UA_TYPES_SETPUBLISHINGMODEREQUEST];
  147. *responseType = &UA_TYPES[UA_TYPES_SETPUBLISHINGMODERESPONSE];
  148. break;
  149. case UA_NS0ID_DELETESUBSCRIPTIONSREQUEST_ENCODING_DEFAULTBINARY:
  150. *service = (UA_Service)Service_DeleteSubscriptions;
  151. *requestType = &UA_TYPES[UA_TYPES_DELETESUBSCRIPTIONSREQUEST];
  152. *responseType = &UA_TYPES[UA_TYPES_DELETESUBSCRIPTIONSRESPONSE];
  153. break;
  154. case UA_NS0ID_CREATEMONITOREDITEMSREQUEST_ENCODING_DEFAULTBINARY:
  155. *service = (UA_Service)Service_CreateMonitoredItems;
  156. *requestType = &UA_TYPES[UA_TYPES_CREATEMONITOREDITEMSREQUEST];
  157. *responseType = &UA_TYPES[UA_TYPES_CREATEMONITOREDITEMSRESPONSE];
  158. break;
  159. case UA_NS0ID_DELETEMONITOREDITEMSREQUEST_ENCODING_DEFAULTBINARY:
  160. *service = (UA_Service)Service_DeleteMonitoredItems;
  161. *requestType = &UA_TYPES[UA_TYPES_DELETEMONITOREDITEMSREQUEST];
  162. *responseType = &UA_TYPES[UA_TYPES_DELETEMONITOREDITEMSRESPONSE];
  163. break;
  164. case UA_NS0ID_MODIFYMONITOREDITEMSREQUEST_ENCODING_DEFAULTBINARY:
  165. *service = (UA_Service)Service_ModifyMonitoredItems;
  166. *requestType = &UA_TYPES[UA_TYPES_MODIFYMONITOREDITEMSREQUEST];
  167. *responseType = &UA_TYPES[UA_TYPES_MODIFYMONITOREDITEMSRESPONSE];
  168. break;
  169. case UA_NS0ID_SETMONITORINGMODEREQUEST_ENCODING_DEFAULTBINARY:
  170. *service = (UA_Service)Service_SetMonitoringMode;
  171. *requestType = &UA_TYPES[UA_TYPES_SETMONITORINGMODEREQUEST];
  172. *responseType = &UA_TYPES[UA_TYPES_SETMONITORINGMODERESPONSE];
  173. break;
  174. #endif
  175. #ifdef UA_ENABLE_METHODCALLS
  176. case UA_NS0ID_CALLREQUEST_ENCODING_DEFAULTBINARY:
  177. *service = (UA_Service)Service_Call;
  178. *requestType = &UA_TYPES[UA_TYPES_CALLREQUEST];
  179. *responseType = &UA_TYPES[UA_TYPES_CALLRESPONSE];
  180. break;
  181. #endif
  182. #ifdef UA_ENABLE_NODEMANAGEMENT
  183. case UA_NS0ID_ADDNODESREQUEST_ENCODING_DEFAULTBINARY:
  184. *service = (UA_Service)Service_AddNodes;
  185. *requestType = &UA_TYPES[UA_TYPES_ADDNODESREQUEST];
  186. *responseType = &UA_TYPES[UA_TYPES_ADDNODESRESPONSE];
  187. break;
  188. case UA_NS0ID_ADDREFERENCESREQUEST_ENCODING_DEFAULTBINARY:
  189. *service = (UA_Service)Service_AddReferences;
  190. *requestType = &UA_TYPES[UA_TYPES_ADDREFERENCESREQUEST];
  191. *responseType = &UA_TYPES[UA_TYPES_ADDREFERENCESRESPONSE];
  192. break;
  193. case UA_NS0ID_DELETENODESREQUEST_ENCODING_DEFAULTBINARY:
  194. *service = (UA_Service)Service_DeleteNodes;
  195. *requestType = &UA_TYPES[UA_TYPES_DELETENODESREQUEST];
  196. *responseType = &UA_TYPES[UA_TYPES_DELETENODESRESPONSE];
  197. break;
  198. case UA_NS0ID_DELETEREFERENCESREQUEST_ENCODING_DEFAULTBINARY:
  199. *service = (UA_Service)Service_DeleteReferences;
  200. *requestType = &UA_TYPES[UA_TYPES_DELETEREFERENCESREQUEST];
  201. *responseType = &UA_TYPES[UA_TYPES_DELETEREFERENCESRESPONSE];
  202. break;
  203. #endif
  204. default:
  205. break;
  206. }
  207. }
  208. /*************************/
  209. /* Process Message Types */
  210. /*************************/
  211. /* HEL -> Open up the connection */
  212. static void processHEL(UA_Connection *connection, const UA_ByteString *msg, size_t *offset) {
  213. UA_TcpHelloMessage helloMessage;
  214. if(UA_TcpHelloMessage_decodeBinary(msg, offset, &helloMessage) != UA_STATUSCODE_GOOD) {
  215. connection->close(connection);
  216. return;
  217. }
  218. /* Parameterize the connection */
  219. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount; /* zero -> unlimited */
  220. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize; /* zero -> unlimited */
  221. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  222. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  223. if(connection->localConf.sendBufferSize > helloMessage.receiveBufferSize)
  224. connection->localConf.sendBufferSize = helloMessage.receiveBufferSize;
  225. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  226. if(connection->localConf.recvBufferSize > helloMessage.sendBufferSize)
  227. connection->localConf.recvBufferSize = helloMessage.sendBufferSize;
  228. connection->state = UA_CONNECTION_ESTABLISHED;
  229. UA_TcpHelloMessage_deleteMembers(&helloMessage);
  230. /* Build acknowledge response */
  231. UA_TcpAcknowledgeMessage ackMessage;
  232. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  233. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  234. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  235. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  236. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  237. UA_TcpMessageHeader ackHeader;
  238. ackHeader.messageTypeAndChunkType = UA_MESSAGETYPE_ACK + UA_CHUNKTYPE_FINAL;
  239. ackHeader.messageSize = 8 + 20; /* ackHeader + ackMessage */
  240. /* Get the send buffer from the network layer */
  241. UA_ByteString ack_msg;
  242. UA_ByteString_init(&ack_msg);
  243. UA_StatusCode retval =
  244. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &ack_msg);
  245. if(retval != UA_STATUSCODE_GOOD)
  246. return;
  247. /* Encode and send the response */
  248. size_t tmpPos = 0;
  249. UA_TcpMessageHeader_encodeBinary(&ackHeader, &ack_msg, &tmpPos);
  250. UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &ack_msg, &tmpPos);
  251. ack_msg.length = ackHeader.messageSize;
  252. connection->send(connection, &ack_msg);
  253. }
  254. /* OPN -> Open up/renew the securechannel */
  255. static void
  256. processOPN(UA_Server *server, UA_Connection *connection,
  257. UA_UInt32 channelId, const UA_ByteString *msg) {
  258. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  259. /* Called before HEL */
  260. if(connection->state != UA_CONNECTION_ESTABLISHED)
  261. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  262. /* Opening up a channel with a channelid already set */
  263. if(!connection->channel && channelId != 0)
  264. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  265. /* Renew a channel with the wrong channelid */
  266. if(connection->channel && channelId != connection->channel->securityToken.channelId)
  267. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  268. /* Decode the request */
  269. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  270. UA_SequenceHeader seqHeader;
  271. UA_NodeId requestType;
  272. UA_OpenSecureChannelRequest r;
  273. size_t offset = 0;
  274. retval |= UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg, &offset, &asymHeader);
  275. retval |= UA_SequenceHeader_decodeBinary(msg, &offset, &seqHeader);
  276. retval |= UA_NodeId_decodeBinary(msg, &offset, &requestType);
  277. retval |= UA_OpenSecureChannelRequest_decodeBinary(msg, &offset, &r);
  278. /* Error occured */
  279. if(retval != UA_STATUSCODE_GOOD || requestType.identifier.numeric != 446) {
  280. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  281. UA_NodeId_deleteMembers(&requestType);
  282. UA_OpenSecureChannelRequest_deleteMembers(&r);
  283. connection->close(connection);
  284. return;
  285. }
  286. /* Call the service */
  287. UA_OpenSecureChannelResponse p;
  288. UA_OpenSecureChannelResponse_init(&p);
  289. Service_OpenSecureChannel(server, connection, &r, &p);
  290. UA_OpenSecureChannelRequest_deleteMembers(&r);
  291. /* Opening the channel failed */
  292. UA_SecureChannel *channel = connection->channel;
  293. if(!channel) {
  294. UA_OpenSecureChannelResponse_deleteMembers(&p);
  295. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  296. connection->close(connection);
  297. return;
  298. }
  299. /* Set the starting sequence number */
  300. channel->receiveSequenceNumber = seqHeader.sequenceNumber;
  301. /* Allocate the return message */
  302. UA_ByteString resp_msg;
  303. UA_ByteString_init(&resp_msg);
  304. retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &resp_msg);
  305. if(retval != UA_STATUSCODE_GOOD) {
  306. UA_OpenSecureChannelResponse_deleteMembers(&p);
  307. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  308. connection->close(connection);
  309. return;
  310. }
  311. /* Encode the message after the secureconversationmessageheader */
  312. size_t tmpPos = 12; /* skip the header */
  313. seqHeader.sequenceNumber = UA_atomic_add(&channel->sendSequenceNumber, 1);
  314. retval |= UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &resp_msg, &tmpPos); // just mirror back
  315. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &resp_msg, &tmpPos);
  316. UA_NodeId responseType = UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE].binaryEncodingId);
  317. retval |= UA_NodeId_encodeBinary(&responseType, &resp_msg, &tmpPos);
  318. retval |= UA_OpenSecureChannelResponse_encodeBinary(&p, &resp_msg, &tmpPos);
  319. if(retval != UA_STATUSCODE_GOOD) {
  320. connection->releaseSendBuffer(connection, &resp_msg);
  321. UA_OpenSecureChannelResponse_deleteMembers(&p);
  322. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  323. connection->close(connection);
  324. return;
  325. }
  326. /* Encode the secureconversationmessageheader (cannot fail) and send */
  327. UA_SecureConversationMessageHeader respHeader;
  328. respHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  329. respHeader.messageHeader.messageSize = (UA_UInt32)tmpPos;
  330. respHeader.secureChannelId = p.securityToken.channelId;
  331. tmpPos = 0;
  332. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &resp_msg, &tmpPos);
  333. resp_msg.length = respHeader.messageHeader.messageSize;
  334. connection->send(connection, &resp_msg);
  335. /* Clean up */
  336. UA_OpenSecureChannelResponse_deleteMembers(&p);
  337. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  338. }
  339. static void
  340. processMSG(UA_Server *server, UA_SecureChannel *channel,
  341. UA_UInt32 requestId, const UA_ByteString *msg) {
  342. /* At 0, the nodeid starts... */
  343. size_t ppos = 0;
  344. size_t *offset = &ppos;
  345. /* Decode the nodeid */
  346. UA_NodeId requestTypeId;
  347. UA_StatusCode retval = UA_NodeId_decodeBinary(msg, offset, &requestTypeId);
  348. if(retval != UA_STATUSCODE_GOOD)
  349. return;
  350. if(requestTypeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  351. UA_NodeId_deleteMembers(&requestTypeId); /* leads to badserviceunsupported */
  352. /* Store the start-position of the request */
  353. size_t requestPos = *offset;
  354. /* Get the service pointers */
  355. UA_Service service = NULL;
  356. const UA_DataType *requestType = NULL;
  357. const UA_DataType *responseType = NULL;
  358. UA_Boolean sessionRequired = true;
  359. getServicePointers(requestTypeId.identifier.numeric, &requestType,
  360. &responseType, &service, &sessionRequired);
  361. if(!requestType) {
  362. if(requestTypeId.identifier.numeric == 787) {
  363. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  364. "Client requested a subscription, " \
  365. "but those are not enabled in the build");
  366. } else {
  367. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  368. "Unknown request with type identifier %i",
  369. requestTypeId.identifier.numeric);
  370. }
  371. sendError(channel, msg, requestPos, &UA_TYPES[UA_TYPES_SERVICEFAULT],
  372. requestId, UA_STATUSCODE_BADSERVICEUNSUPPORTED);
  373. return;
  374. }
  375. UA_assert(responseType);
  376. #ifdef UA_ENABLE_NONSTANDARD_STATELESS
  377. /* Stateless extension: Sessions are optional */
  378. sessionRequired = false;
  379. #endif
  380. /* Decode the request */
  381. void *request = UA_alloca(requestType->memSize);
  382. UA_RequestHeader *requestHeader = (UA_RequestHeader*)request;
  383. retval = UA_decodeBinary(msg, offset, request, requestType,
  384. server->config.customDataTypesSize,
  385. server->config.customDataTypes);
  386. if(retval != UA_STATUSCODE_GOOD) {
  387. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  388. "Could not decode the request");
  389. sendError(channel, msg, requestPos, responseType, requestId, retval);
  390. return;
  391. }
  392. /* Prepare the respone */
  393. void *response = UA_alloca(responseType->memSize);
  394. UA_init(response, responseType);
  395. UA_Session *session = NULL; /* must be initialized before goto send_response */
  396. /* CreateSession doesn't need a session */
  397. if(requestType == &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST]) {
  398. Service_CreateSession(server, channel,
  399. (const UA_CreateSessionRequest *)request,
  400. (UA_CreateSessionResponse *)response);
  401. goto send_response;
  402. }
  403. /* Find the matching session */
  404. session = UA_SecureChannel_getSession(channel, &requestHeader->authenticationToken);
  405. if(!session)
  406. session = UA_SessionManager_getSession(&server->sessionManager,
  407. &requestHeader->authenticationToken);
  408. if(requestType == &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST]) {
  409. if(!session) {
  410. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  411. "Trying to activate a session that is " \
  412. "not known in the server");
  413. sendError(channel, msg, requestPos, responseType,
  414. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  415. UA_deleteMembers(request, requestType);
  416. return;
  417. }
  418. Service_ActivateSession(server, channel, session,
  419. (const UA_ActivateSessionRequest*)request,
  420. (UA_ActivateSessionResponse*)response);
  421. goto send_response;
  422. }
  423. /* Set an anonymous, inactive session for services that need no session */
  424. UA_Session anonymousSession;
  425. if(!session) {
  426. if(sessionRequired) {
  427. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  428. "Service request %i without a valid session",
  429. requestType->binaryEncodingId);
  430. sendError(channel, msg, requestPos, responseType,
  431. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  432. UA_deleteMembers(request, requestType);
  433. return;
  434. }
  435. UA_Session_init(&anonymousSession);
  436. anonymousSession.sessionId = UA_NODEID_GUID(0, UA_GUID_NULL);
  437. anonymousSession.channel = channel;
  438. session = &anonymousSession;
  439. }
  440. /* Trying to use a non-activated session? */
  441. if(sessionRequired && !session->activated) {
  442. UA_LOG_INFO_SESSION(server->config.logger, session,
  443. "Calling service %i on a non-activated session",
  444. requestType->binaryEncodingId);
  445. sendError(channel, msg, requestPos, responseType,
  446. requestId, UA_STATUSCODE_BADSESSIONNOTACTIVATED);
  447. UA_SessionManager_removeSession(&server->sessionManager,
  448. &session->authenticationToken);
  449. UA_deleteMembers(request, requestType);
  450. return;
  451. }
  452. /* The session is bound to another channel */
  453. if(session->channel != channel) {
  454. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  455. "Client tries to use an obsolete securechannel");
  456. sendError(channel, msg, requestPos, responseType,
  457. requestId, UA_STATUSCODE_BADSECURECHANNELIDINVALID);
  458. UA_deleteMembers(request, requestType);
  459. return;
  460. }
  461. /* Update the session lifetime */
  462. UA_Session_updateLifetime(session);
  463. #ifdef UA_ENABLE_SUBSCRIPTIONS
  464. /* The publish request is not answered immediately */
  465. if(requestType == &UA_TYPES[UA_TYPES_PUBLISHREQUEST]) {
  466. Service_Publish(server, session,
  467. (const UA_PublishRequest*)request, requestId);
  468. UA_deleteMembers(request, requestType);
  469. return;
  470. }
  471. #endif
  472. /* Call the service */
  473. UA_assert(service); /* For all services besides publish, the service pointer is non-NULL*/
  474. service(server, session, request, response);
  475. send_response:
  476. /* Send the response */
  477. ((UA_ResponseHeader*)response)->requestHandle = requestHeader->requestHandle;
  478. ((UA_ResponseHeader*)response)->timestamp = UA_DateTime_now();
  479. retval = UA_SecureChannel_sendBinaryMessage(channel, requestId, response, responseType);
  480. if(retval != UA_STATUSCODE_GOOD)
  481. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  482. "Could not send the message over the SecureChannel "
  483. "with StatusCode %s", UA_StatusCode_name(retval));
  484. /* Clean up */
  485. UA_deleteMembers(request, requestType);
  486. UA_deleteMembers(response, responseType);
  487. }
  488. /* ERR -> Error from the remote connection */
  489. static void processERR(UA_Server *server, UA_Connection *connection, const UA_ByteString *msg, size_t *offset) {
  490. UA_TcpErrorMessage errorMessage;
  491. if (UA_TcpErrorMessage_decodeBinary(msg, offset, &errorMessage) != UA_STATUSCODE_GOOD) {
  492. connection->close(connection);
  493. return;
  494. }
  495. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_NETWORK,
  496. "Client replied with an error message: %s %.*s",
  497. UA_StatusCode_name(errorMessage.error), errorMessage.reason.length, errorMessage.reason.data);
  498. }
  499. /* Takes decoded messages starting at the nodeid of the content type. Only OPN
  500. * messages start at the asymmetricalgorithmsecurityheader and are not
  501. * decoded. */
  502. static void
  503. UA_Server_processSecureChannelMessage(UA_Server *server, UA_SecureChannel *channel,
  504. UA_MessageType messagetype, UA_UInt32 requestId,
  505. const UA_ByteString *message) {
  506. UA_assert(channel);
  507. UA_assert(channel->connection);
  508. switch(messagetype) {
  509. case UA_MESSAGETYPE_ERR: {
  510. const UA_TcpErrorMessage *msg = (const UA_TcpErrorMessage *) message;
  511. UA_LOG_ERROR_CHANNEL(server->config.logger, channel,
  512. "Client replied with an error message: %s %.*s",
  513. UA_StatusCode_name(msg->error), msg->reason.length, msg->reason.data);
  514. break;
  515. }
  516. case UA_MESSAGETYPE_HEL:
  517. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  518. "Cannot process a HEL on an open channel");
  519. break;
  520. case UA_MESSAGETYPE_OPN:
  521. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  522. "Process an OPN on an open channel");
  523. processOPN(server, channel->connection, channel->securityToken.channelId, message);
  524. break;
  525. case UA_MESSAGETYPE_MSG:
  526. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  527. "Process a MSG", channel->connection->sockfd);
  528. processMSG(server, channel, requestId, message);
  529. break;
  530. case UA_MESSAGETYPE_CLO:
  531. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  532. "Process a CLO", channel->connection->sockfd);
  533. Service_CloseSecureChannel(server, channel);
  534. break;
  535. default:
  536. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  537. "Unknown message type");
  538. }
  539. }
  540. /* Takes the raw message from the network layer */
  541. void
  542. UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
  543. const UA_ByteString *message) {
  544. UA_SecureChannel *channel = connection->channel;
  545. if(channel) {
  546. /* Assemble chunks in the securechannel and process complete messages */
  547. UA_StatusCode retval =
  548. UA_SecureChannel_processChunks(channel, message,
  549. (UA_ProcessMessageCallback*)UA_Server_processSecureChannelMessage, server);
  550. if(retval != UA_STATUSCODE_GOOD)
  551. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Procesing chunks "
  552. "resulted in error code %s", UA_StatusCode_name(retval));
  553. } else {
  554. /* Process messages without a channel and no chunking */
  555. size_t offset = 0;
  556. UA_TcpMessageHeader tcpMessageHeader;
  557. UA_StatusCode retval = UA_TcpMessageHeader_decodeBinary(message, &offset, &tcpMessageHeader);
  558. if(retval != UA_STATUSCODE_GOOD) {
  559. connection->close(connection);
  560. return;
  561. }
  562. /* Dispatch according to the message type */
  563. switch(tcpMessageHeader.messageTypeAndChunkType & 0x00ffffff) {
  564. case UA_MESSAGETYPE_ERR:
  565. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  566. "Connection %i | Process ERR message", connection->sockfd);
  567. processERR(server, connection, message, &offset);
  568. break;
  569. case UA_MESSAGETYPE_HEL:
  570. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  571. "Connection %i | Process HEL message", connection->sockfd);
  572. processHEL(connection, message, &offset);
  573. break;
  574. case UA_MESSAGETYPE_OPN: {
  575. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  576. "Connection %i | Process OPN message", connection->sockfd);
  577. UA_UInt32 channelId = 0;
  578. retval = UA_UInt32_decodeBinary(message, &offset, &channelId);
  579. if(retval != UA_STATUSCODE_GOOD)
  580. connection->close(connection);
  581. UA_ByteString offsetMessage;
  582. offsetMessage.data = message->data + 12;
  583. offsetMessage.length = message->length - 12;
  584. processOPN(server, connection, channelId, &offsetMessage);
  585. break; }
  586. case UA_MESSAGETYPE_MSG:
  587. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  588. "Connection %i | Processing a MSG message not possible "
  589. "without a SecureChannel", connection->sockfd);
  590. connection->close(connection);
  591. break;
  592. case UA_MESSAGETYPE_CLO:
  593. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  594. "Connection %i | Processing a CLO message not possible "
  595. "without a SecureChannel", connection->sockfd);
  596. connection->close(connection);
  597. break;
  598. default:
  599. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  600. "Connection %i | Unknown message type", connection->sockfd);
  601. connection->close(connection);
  602. }
  603. }
  604. }