ua_server_binary.c 35 KB

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