ua_server_binary.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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
  213. processHEL(UA_Server *server, UA_Connection *connection, const UA_ByteString *msg, size_t *offset) {
  214. UA_TcpHelloMessage helloMessage;
  215. if(UA_TcpHelloMessage_decodeBinary(msg, offset, &helloMessage) != UA_STATUSCODE_GOOD) {
  216. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  217. "Connection %i | Could not decode the HEL message. Closing the connection.",
  218. connection->sockfd);
  219. connection->close(connection);
  220. return;
  221. }
  222. /* Parameterize the connection */
  223. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount; /* zero -> unlimited */
  224. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize; /* zero -> unlimited */
  225. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  226. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  227. if(connection->localConf.sendBufferSize > helloMessage.receiveBufferSize)
  228. connection->localConf.sendBufferSize = helloMessage.receiveBufferSize;
  229. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  230. if(connection->localConf.recvBufferSize > helloMessage.sendBufferSize)
  231. connection->localConf.recvBufferSize = helloMessage.sendBufferSize;
  232. connection->state = UA_CONNECTION_ESTABLISHED;
  233. UA_TcpHelloMessage_deleteMembers(&helloMessage);
  234. /* Build acknowledge response */
  235. UA_TcpAcknowledgeMessage ackMessage;
  236. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  237. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  238. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  239. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  240. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  241. UA_TcpMessageHeader ackHeader;
  242. ackHeader.messageTypeAndChunkType = UA_MESSAGETYPE_ACK + UA_CHUNKTYPE_FINAL;
  243. ackHeader.messageSize = 8 + 20; /* ackHeader + ackMessage */
  244. /* Get the send buffer from the network layer */
  245. UA_ByteString ack_msg;
  246. UA_ByteString_init(&ack_msg);
  247. UA_StatusCode retval =
  248. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &ack_msg);
  249. if(retval != UA_STATUSCODE_GOOD)
  250. return;
  251. /* Encode and send the response */
  252. UA_Byte *bufPos = ack_msg.data;
  253. const UA_Byte *bufEnd = &ack_msg.data[ack_msg.length];
  254. UA_TcpMessageHeader_encodeBinary(&ackHeader, &bufPos, &bufEnd);
  255. UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &bufPos, &bufEnd);
  256. ack_msg.length = ackHeader.messageSize;
  257. connection->send(connection, &ack_msg);
  258. }
  259. /* OPN -> Open up/renew the securechannel */
  260. static void
  261. processOPN(UA_Server *server, UA_Connection *connection,
  262. UA_UInt32 channelId, const UA_ByteString *msg) {
  263. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  264. /* Called before HEL */
  265. if(connection->state != UA_CONNECTION_ESTABLISHED)
  266. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  267. /* Opening up a channel with a channelid already set */
  268. if(!connection->channel && channelId != 0)
  269. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  270. /* Renew a channel with the wrong channelid */
  271. if(connection->channel && channelId != connection->channel->securityToken.channelId)
  272. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  273. /* Decode the request */
  274. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  275. UA_SequenceHeader seqHeader;
  276. UA_NodeId requestType;
  277. UA_OpenSecureChannelRequest r;
  278. size_t offset = 0;
  279. retval |= UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg, &offset, &asymHeader);
  280. retval |= UA_SequenceHeader_decodeBinary(msg, &offset, &seqHeader);
  281. retval |= UA_NodeId_decodeBinary(msg, &offset, &requestType);
  282. retval |= UA_OpenSecureChannelRequest_decodeBinary(msg, &offset, &r);
  283. /* Error occured */
  284. if(retval != UA_STATUSCODE_GOOD || requestType.identifier.numeric != 446) {
  285. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  286. UA_NodeId_deleteMembers(&requestType);
  287. UA_OpenSecureChannelRequest_deleteMembers(&r);
  288. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  289. "Connection %i | Could not decode the OPN message. Closing the connection.",
  290. connection->sockfd);
  291. connection->close(connection);
  292. return;
  293. }
  294. /* Call the service */
  295. UA_OpenSecureChannelResponse p;
  296. UA_OpenSecureChannelResponse_init(&p);
  297. Service_OpenSecureChannel(server, connection, &r, &p);
  298. UA_OpenSecureChannelRequest_deleteMembers(&r);
  299. /* Opening the channel failed */
  300. UA_SecureChannel *channel = connection->channel;
  301. if(!channel) {
  302. UA_OpenSecureChannelResponse_deleteMembers(&p);
  303. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  304. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  305. "Connection %i | Could not open a SecureChannel. "
  306. "Closing the connection.", connection->sockfd);
  307. connection->close(connection);
  308. return;
  309. }
  310. /* Set the starting sequence number */
  311. channel->receiveSequenceNumber = seqHeader.sequenceNumber;
  312. /* Allocate the return message */
  313. UA_ByteString resp_msg;
  314. UA_ByteString_init(&resp_msg);
  315. retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &resp_msg);
  316. if(retval != UA_STATUSCODE_GOOD) {
  317. UA_OpenSecureChannelResponse_deleteMembers(&p);
  318. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  319. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  320. "Connection %i | Could not obtain a buffer to answer the OPN message. "
  321. "Closing the connection.", connection->sockfd);
  322. connection->close(connection);
  323. return;
  324. }
  325. /* Encode the message after the secureconversationmessageheader */
  326. UA_Byte *bufPos = &resp_msg.data[12]; /* skip the header */
  327. const UA_Byte *bufEnd = &resp_msg.data[resp_msg.length];
  328. seqHeader.sequenceNumber = UA_atomic_add(&channel->sendSequenceNumber, 1);
  329. retval |= UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &bufPos, &bufEnd); // just mirror back
  330. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &bufPos, &bufEnd);
  331. UA_NodeId responseType = UA_NODEID_NUMERIC(0, UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE].binaryEncodingId);
  332. retval |= UA_NodeId_encodeBinary(&responseType, &bufPos, &bufEnd);
  333. retval |= UA_OpenSecureChannelResponse_encodeBinary(&p, &bufPos, &bufEnd);
  334. if(retval != UA_STATUSCODE_GOOD) {
  335. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  336. "Connection %i | Could not encode the OPN message. "
  337. "Closing the connection.", connection->sockfd);
  338. connection->releaseSendBuffer(connection, &resp_msg);
  339. UA_OpenSecureChannelResponse_deleteMembers(&p);
  340. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  341. connection->close(connection);
  342. return;
  343. }
  344. /* Encode the secureconversationmessageheader (cannot fail) and send */
  345. UA_SecureConversationMessageHeader respHeader;
  346. respHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  347. respHeader.messageHeader.messageSize = (u32)((uintptr_t)bufPos - (uintptr_t)resp_msg.data);
  348. respHeader.secureChannelId = p.securityToken.channelId;
  349. bufPos = resp_msg.data;
  350. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &bufPos, &bufEnd);
  351. resp_msg.length = respHeader.messageHeader.messageSize;
  352. connection->send(connection, &resp_msg);
  353. /* Clean up */
  354. UA_OpenSecureChannelResponse_deleteMembers(&p);
  355. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  356. }
  357. static void
  358. processMSG(UA_Server *server, UA_SecureChannel *channel,
  359. UA_UInt32 requestId, const UA_ByteString *msg) {
  360. /* At 0, the nodeid starts... */
  361. size_t ppos = 0;
  362. size_t *offset = &ppos;
  363. /* Decode the nodeid */
  364. UA_NodeId requestTypeId;
  365. UA_StatusCode retval = UA_NodeId_decodeBinary(msg, offset, &requestTypeId);
  366. if(retval != UA_STATUSCODE_GOOD)
  367. return;
  368. if(requestTypeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  369. UA_NodeId_deleteMembers(&requestTypeId); /* leads to badserviceunsupported */
  370. /* Store the start-position of the request */
  371. size_t requestPos = *offset;
  372. /* Get the service pointers */
  373. UA_Service service = NULL;
  374. const UA_DataType *requestType = NULL;
  375. const UA_DataType *responseType = NULL;
  376. UA_Boolean sessionRequired = true;
  377. getServicePointers(requestTypeId.identifier.numeric, &requestType,
  378. &responseType, &service, &sessionRequired);
  379. if(!requestType) {
  380. if(requestTypeId.identifier.numeric == 787) {
  381. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  382. "Client requested a subscription, " \
  383. "but those are not enabled in the build", NULL);
  384. } else {
  385. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  386. "Unknown request with type identifier %i",
  387. requestTypeId.identifier.numeric);
  388. }
  389. sendError(channel, msg, requestPos, &UA_TYPES[UA_TYPES_SERVICEFAULT],
  390. requestId, UA_STATUSCODE_BADSERVICEUNSUPPORTED);
  391. return;
  392. }
  393. UA_assert(responseType);
  394. #ifdef UA_ENABLE_NONSTANDARD_STATELESS
  395. /* Stateless extension: Sessions are optional */
  396. sessionRequired = false;
  397. #endif
  398. /* Decode the request */
  399. void *request = UA_alloca(requestType->memSize);
  400. UA_RequestHeader *requestHeader = (UA_RequestHeader*)request;
  401. retval = UA_decodeBinary(msg, offset, request, requestType,
  402. server->config.customDataTypesSize,
  403. server->config.customDataTypes);
  404. if(retval != UA_STATUSCODE_GOOD) {
  405. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  406. "Could not decode the request", NULL);
  407. sendError(channel, msg, requestPos, responseType, requestId, retval);
  408. return;
  409. }
  410. /* Prepare the respone */
  411. void *response = UA_alloca(responseType->memSize);
  412. UA_init(response, responseType);
  413. UA_Session *session = NULL; /* must be initialized before goto send_response */
  414. /* CreateSession doesn't need a session */
  415. if(requestType == &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST]) {
  416. Service_CreateSession(server, channel,
  417. (const UA_CreateSessionRequest *)request,
  418. (UA_CreateSessionResponse *)response);
  419. goto send_response;
  420. }
  421. /* Find the matching session */
  422. session = UA_SecureChannel_getSession(channel, &requestHeader->authenticationToken);
  423. if(!session)
  424. session = UA_SessionManager_getSession(&server->sessionManager,
  425. &requestHeader->authenticationToken);
  426. if(requestType == &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST]) {
  427. if(!session) {
  428. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  429. "Trying to activate a session that is " \
  430. "not known in the server", NULL);
  431. sendError(channel, msg, requestPos, responseType,
  432. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  433. UA_deleteMembers(request, requestType);
  434. return;
  435. }
  436. Service_ActivateSession(server, channel, session,
  437. (const UA_ActivateSessionRequest*)request,
  438. (UA_ActivateSessionResponse*)response);
  439. goto send_response;
  440. }
  441. /* Set an anonymous, inactive session for services that need no session */
  442. UA_Session anonymousSession;
  443. if(!session) {
  444. if(sessionRequired) {
  445. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  446. "Service request %i without a valid session",
  447. requestType->binaryEncodingId);
  448. sendError(channel, msg, requestPos, responseType,
  449. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  450. UA_deleteMembers(request, requestType);
  451. return;
  452. }
  453. UA_Session_init(&anonymousSession);
  454. anonymousSession.sessionId = UA_NODEID_GUID(0, UA_GUID_NULL);
  455. anonymousSession.channel = channel;
  456. session = &anonymousSession;
  457. }
  458. /* Trying to use a non-activated session? */
  459. if(sessionRequired && !session->activated) {
  460. UA_LOG_INFO_SESSION(server->config.logger, session,
  461. "Calling service %i on a non-activated session",
  462. requestType->binaryEncodingId);
  463. sendError(channel, msg, requestPos, responseType,
  464. requestId, UA_STATUSCODE_BADSESSIONNOTACTIVATED);
  465. UA_SessionManager_removeSession(&server->sessionManager,
  466. &session->authenticationToken);
  467. UA_deleteMembers(request, requestType);
  468. return;
  469. }
  470. /* The session is bound to another channel */
  471. if(session->channel != channel) {
  472. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  473. "Client tries to use an obsolete securechannel", NULL);
  474. sendError(channel, msg, requestPos, responseType,
  475. requestId, UA_STATUSCODE_BADSECURECHANNELIDINVALID);
  476. UA_deleteMembers(request, requestType);
  477. return;
  478. }
  479. /* Update the session lifetime */
  480. UA_Session_updateLifetime(session);
  481. #ifdef UA_ENABLE_SUBSCRIPTIONS
  482. /* The publish request is not answered immediately */
  483. if(requestType == &UA_TYPES[UA_TYPES_PUBLISHREQUEST]) {
  484. Service_Publish(server, session,
  485. (const UA_PublishRequest*)request, requestId);
  486. UA_deleteMembers(request, requestType);
  487. return;
  488. }
  489. #endif
  490. /* Call the service */
  491. UA_assert(service); /* For all services besides publish, the service pointer is non-NULL*/
  492. service(server, session, request, response);
  493. send_response:
  494. /* Send the response */
  495. ((UA_ResponseHeader*)response)->requestHandle = requestHeader->requestHandle;
  496. ((UA_ResponseHeader*)response)->timestamp = UA_DateTime_now();
  497. retval = UA_SecureChannel_sendBinaryMessage(channel, requestId, response, responseType);
  498. if(retval != UA_STATUSCODE_GOOD)
  499. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  500. "Could not send the message over the SecureChannel "
  501. "with StatusCode %s", UA_StatusCode_name(retval));
  502. /* Clean up */
  503. UA_deleteMembers(request, requestType);
  504. UA_deleteMembers(response, responseType);
  505. }
  506. /* ERR -> Error from the remote connection */
  507. static void processERR(UA_Server *server, UA_Connection *connection, const UA_ByteString *msg, size_t *offset) {
  508. UA_TcpErrorMessage errorMessage;
  509. if (UA_TcpErrorMessage_decodeBinary(msg, offset, &errorMessage) != UA_STATUSCODE_GOOD) {
  510. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  511. "Connection %i | Could not decide the ERR message. "
  512. "Closing the connection.", connection->sockfd);
  513. connection->close(connection);
  514. return;
  515. }
  516. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_NETWORK,
  517. "Connection %i | Client replied with an error message: %s %.*s",
  518. connection->sockfd, UA_StatusCode_name(errorMessage.error),
  519. errorMessage.reason.length, errorMessage.reason.data);
  520. UA_TcpErrorMessage_deleteMembers(&errorMessage);
  521. }
  522. /* Takes decoded messages starting at the nodeid of the content type. Only OPN
  523. * messages start at the asymmetricalgorithmsecurityheader and are not
  524. * decoded. */
  525. static void
  526. UA_Server_processSecureChannelMessage(UA_Server *server, UA_SecureChannel *channel,
  527. UA_MessageType messagetype, UA_UInt32 requestId,
  528. const UA_ByteString *message) {
  529. UA_assert(channel);
  530. UA_assert(channel->connection);
  531. switch(messagetype) {
  532. case UA_MESSAGETYPE_ERR: {
  533. const UA_TcpErrorMessage *msg = (const UA_TcpErrorMessage *) message;
  534. UA_LOG_ERROR_CHANNEL(server->config.logger, channel,
  535. "Client replied with an error message: %s %.*s",
  536. UA_StatusCode_name(msg->error), msg->reason.length, msg->reason.data);
  537. break;
  538. }
  539. case UA_MESSAGETYPE_HEL:
  540. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  541. "Cannot process a HEL on an open channel", NULL);
  542. break;
  543. case UA_MESSAGETYPE_OPN:
  544. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  545. "Process an OPN on an open channel", NULL);
  546. processOPN(server, channel->connection, channel->securityToken.channelId, message);
  547. break;
  548. case UA_MESSAGETYPE_MSG:
  549. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Process a MSG", NULL);
  550. processMSG(server, channel, requestId, message);
  551. break;
  552. case UA_MESSAGETYPE_CLO:
  553. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Process a CLO", NULL);
  554. Service_CloseSecureChannel(server, channel);
  555. break;
  556. default:
  557. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  558. "Unknown message type", NULL);
  559. }
  560. }
  561. /* Takes the raw message from the network layer */
  562. static void
  563. processBinaryMessage(UA_Server *server, UA_Connection *connection,
  564. UA_ByteString *message) {
  565. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  566. "Connection %i | Received a packet.", connection->sockfd);
  567. UA_Boolean realloced = UA_FALSE;
  568. UA_StatusCode retval = UA_Connection_completeChunks(connection, message, &realloced);
  569. /* No failure, but no chunk ready */
  570. if(message->length == 0) {
  571. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  572. "Connection %i | Not a complete chunk yet.", connection->sockfd);
  573. return;
  574. }
  575. /* Failed to complete a chunk */
  576. if(retval != UA_STATUSCODE_GOOD) {
  577. if(!realloced)
  578. connection->releaseRecvBuffer(connection, message);
  579. else
  580. UA_ByteString_deleteMembers(message);
  581. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  582. "Connection %i | Failed to complete a chunk. "
  583. "Closing the connection.", connection->sockfd);
  584. connection->close(connection);
  585. return;
  586. }
  587. UA_SecureChannel *channel = connection->channel;
  588. if(channel) {
  589. /* Assemble chunks in the securechannel and process complete messages */
  590. retval = UA_SecureChannel_processChunks(channel, message,
  591. (UA_ProcessMessageCallback*)UA_Server_processSecureChannelMessage, server);
  592. if(retval != UA_STATUSCODE_GOOD)
  593. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Procesing chunks "
  594. "resulted in error code %s", UA_StatusCode_name(retval));
  595. } else {
  596. /* Process messages without a channel and no chunking */
  597. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  598. "Connection %i | No channel attached to the connection. "
  599. "Process the chunk directly", connection->sockfd);
  600. size_t offset = 0;
  601. UA_TcpMessageHeader tcpMessageHeader;
  602. retval = UA_TcpMessageHeader_decodeBinary(message, &offset, &tcpMessageHeader);
  603. if(retval != UA_STATUSCODE_GOOD) {
  604. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  605. "Connection %i | Could not decode the TCP message header. "
  606. "Closing the connection.", connection->sockfd);
  607. connection->close(connection);
  608. return;
  609. }
  610. /* Dispatch according to the message type */
  611. switch(tcpMessageHeader.messageTypeAndChunkType & 0x00ffffff) {
  612. case UA_MESSAGETYPE_ERR:
  613. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  614. "Connection %i | Process ERR message", connection->sockfd);
  615. processERR(server, connection, message, &offset);
  616. break;
  617. case UA_MESSAGETYPE_HEL:
  618. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  619. "Connection %i | Process HEL message", connection->sockfd);
  620. processHEL(server, connection, message, &offset);
  621. break;
  622. case UA_MESSAGETYPE_OPN: {
  623. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  624. "Connection %i | Process OPN message", connection->sockfd);
  625. UA_UInt32 channelId = 0;
  626. retval = UA_UInt32_decodeBinary(message, &offset, &channelId);
  627. if(retval != UA_STATUSCODE_GOOD) {
  628. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  629. "Connection %i | Could not decode the channel ID for an OPN call. "
  630. "Closing the connection.", connection->sockfd);
  631. connection->close(connection);
  632. break;
  633. }
  634. UA_ByteString offsetMessage;
  635. offsetMessage.data = message->data + 12;
  636. offsetMessage.length = message->length - 12;
  637. processOPN(server, connection, channelId, &offsetMessage);
  638. break; }
  639. case UA_MESSAGETYPE_MSG:
  640. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  641. "Connection %i | Processing a MSG message not possible "
  642. "without a SecureChannel", connection->sockfd);
  643. connection->close(connection);
  644. break;
  645. case UA_MESSAGETYPE_CLO:
  646. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  647. "Connection %i | Processing a CLO message not possible "
  648. "without a SecureChannel", connection->sockfd);
  649. connection->close(connection);
  650. break;
  651. default:
  652. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  653. "Connection %i | Unknown message type", connection->sockfd);
  654. connection->close(connection);
  655. }
  656. }
  657. if(!realloced)
  658. connection->releaseRecvBuffer(connection, message);
  659. else
  660. UA_ByteString_deleteMembers(message);
  661. }
  662. #ifndef UA_ENABLE_MULTITHREADING
  663. void
  664. UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
  665. UA_ByteString *message) {
  666. processBinaryMessage(server, connection, message);
  667. }
  668. #else
  669. typedef struct {
  670. UA_Connection *connection;
  671. UA_ByteString message;
  672. } ConnectionMessage;
  673. static void
  674. workerProcessBinaryMessage(UA_Server *server, ConnectionMessage *cm) {
  675. processBinaryMessage(server, cm->connection, &cm->message);
  676. UA_free(cm);
  677. }
  678. void
  679. UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
  680. UA_ByteString *message) {
  681. /* Allocate the memory for the callback data */
  682. ConnectionMessage *cm = (ConnectionMessage*)UA_malloc(sizeof(ConnectionMessage));
  683. /* If malloc failed, execute immediately */
  684. if(!cm) {
  685. processBinaryMessage(server, connection, message);
  686. return;
  687. }
  688. /* Dispatch to the workers */
  689. cm->connection = connection;
  690. cm->message = *message;
  691. UA_Server_workerCallback(server, (UA_ServerCallback)workerProcessBinaryMessage, cm);
  692. }
  693. #endif
  694. #ifdef UA_ENABLE_MULTITHREADING
  695. static void
  696. deleteConnectionTrampoline(UA_Server *server, void *data) {
  697. UA_Connection *connection = (UA_Connection*)data;
  698. connection->free(connection);
  699. }
  700. #endif
  701. void
  702. UA_Server_removeConnection(UA_Server *server, UA_Connection *connection) {
  703. UA_Connection_detachSecureChannel(connection);
  704. #ifndef UA_ENABLE_MULTITHREADING
  705. connection->free(connection);
  706. #else
  707. UA_Server_delayedCallback(server, deleteConnectionTrampoline, connection);
  708. #endif
  709. }