ua_server_binary.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. #include "ua_util.h"
  2. #include "ua_server_internal.h"
  3. #include "ua_services.h"
  4. #include "ua_securechannel_manager.h"
  5. #include "ua_session_manager.h"
  6. #include "ua_types_generated_encoding_binary.h"
  7. #include "ua_transport_generated.h"
  8. #include "ua_transport_generated_encoding_binary.h"
  9. /** Max size of messages that are allocated on the stack */
  10. #define MAX_STACK_MESSAGE 65536
  11. static void processHEL(UA_Connection *connection, const UA_ByteString *msg, size_t *pos) {
  12. UA_TcpHelloMessage helloMessage;
  13. if(UA_TcpHelloMessage_decodeBinary(msg, pos, &helloMessage) != UA_STATUSCODE_GOOD) {
  14. connection->close(connection);
  15. return;
  16. }
  17. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount;
  18. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize;
  19. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  20. if(connection->remoteConf.recvBufferSize > helloMessage.receiveBufferSize)
  21. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  22. if(connection->remoteConf.sendBufferSize > helloMessage.sendBufferSize)
  23. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  24. if(connection->localConf.sendBufferSize > helloMessage.receiveBufferSize)
  25. connection->localConf.sendBufferSize = helloMessage.receiveBufferSize;
  26. connection->state = UA_CONNECTION_ESTABLISHED;
  27. UA_TcpHelloMessage_deleteMembers(&helloMessage);
  28. // build acknowledge response
  29. UA_TcpAcknowledgeMessage ackMessage;
  30. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  31. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  32. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  33. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  34. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  35. UA_TcpMessageHeader ackHeader;
  36. ackHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_ACKF;
  37. ackHeader.messageSize = 8 + 20; /* ackHeader + ackMessage */
  38. UA_ByteString ack_msg;
  39. if(connection->getSendBuffer(connection, connection->remoteConf.recvBufferSize,
  40. &ack_msg) != UA_STATUSCODE_GOOD)
  41. return;
  42. size_t tmpPos = 0;
  43. UA_TcpMessageHeader_encodeBinary(&ackHeader, &ack_msg, &tmpPos);
  44. UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &ack_msg, &tmpPos);
  45. ack_msg.length = ackHeader.messageSize;
  46. connection->send(connection, &ack_msg);
  47. }
  48. static void processOPN(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg, size_t *pos) {
  49. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  50. connection->close(connection);
  51. return;
  52. }
  53. UA_UInt32 secureChannelId;
  54. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  55. //we can check secureChannelId also here -> if we are asked to isse a token it is 0, otherwise we have to renew
  56. //issue
  57. if(connection->channel == NULL && secureChannelId != 0){
  58. retval |= UA_STATUSCODE_BADREQUESTTYPEINVALID;
  59. }
  60. //renew
  61. if(connection->channel != NULL && secureChannelId != connection->channel->securityToken.channelId){
  62. retval |= UA_STATUSCODE_BADREQUESTTYPEINVALID;
  63. }
  64. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  65. retval |= UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(msg, pos, &asymHeader);
  66. UA_SequenceHeader seqHeader;
  67. retval |= UA_SequenceHeader_decodeBinary(msg, pos, &seqHeader);
  68. UA_NodeId requestType;
  69. retval |= UA_NodeId_decodeBinary(msg, pos, &requestType);
  70. UA_OpenSecureChannelRequest r;
  71. retval |= UA_OpenSecureChannelRequest_decodeBinary(msg, pos, &r);
  72. if(retval != UA_STATUSCODE_GOOD || requestType.identifier.numeric != 446) {
  73. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  74. UA_SequenceHeader_deleteMembers(&seqHeader);
  75. UA_NodeId_deleteMembers(&requestType);
  76. UA_OpenSecureChannelRequest_deleteMembers(&r);
  77. connection->close(connection);
  78. return;
  79. }
  80. UA_OpenSecureChannelResponse p;
  81. UA_OpenSecureChannelResponse_init(&p);
  82. Service_OpenSecureChannel(server, connection, &r, &p);
  83. UA_OpenSecureChannelRequest_deleteMembers(&r);
  84. UA_SecureChannel *channel = connection->channel;
  85. if(!channel) {
  86. connection->close(connection);
  87. UA_OpenSecureChannelResponse_deleteMembers(&p);
  88. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  89. return;
  90. }
  91. /* send the response with an asymmetric security header */
  92. #ifndef UA_ENABLE_MULTITHREADING
  93. seqHeader.sequenceNumber = ++channel->sequenceNumber;
  94. #else
  95. seqHeader.sequenceNumber = uatomic_add_return(&channel->sequenceNumber, 1);
  96. #endif
  97. UA_SecureConversationMessageHeader respHeader;
  98. respHeader.messageHeader.messageTypeAndFinal = UA_MESSAGETYPEANDFINAL_OPNF;
  99. respHeader.messageHeader.messageSize = 0;
  100. respHeader.secureChannelId = p.securityToken.channelId;
  101. UA_NodeId responseType = UA_NODEID_NUMERIC(0, UA_NS0ID_OPENSECURECHANNELRESPONSE +
  102. UA_ENCODINGOFFSET_BINARY);
  103. UA_ByteString resp_msg;
  104. retval = connection->getSendBuffer(connection, connection->remoteConf.recvBufferSize, &resp_msg);
  105. if(retval != UA_STATUSCODE_GOOD) {
  106. UA_OpenSecureChannelResponse_deleteMembers(&p);
  107. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  108. return;
  109. }
  110. size_t tmpPos = 12; /* skip the secureconversationmessageheader for now */
  111. retval |= UA_AsymmetricAlgorithmSecurityHeader_encodeBinary(&asymHeader, &resp_msg, &tmpPos); // just mirror back
  112. retval |= UA_SequenceHeader_encodeBinary(&seqHeader, &resp_msg, &tmpPos); // just mirror back
  113. retval |= UA_NodeId_encodeBinary(&responseType, &resp_msg, &tmpPos);
  114. retval |= UA_OpenSecureChannelResponse_encodeBinary(&p, &resp_msg, &tmpPos);
  115. if(retval != UA_STATUSCODE_GOOD) {
  116. connection->releaseSendBuffer(connection, &resp_msg);
  117. connection->close(connection);
  118. } else {
  119. respHeader.messageHeader.messageSize = (UA_UInt32)tmpPos;
  120. tmpPos = 0;
  121. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &resp_msg, &tmpPos);
  122. resp_msg.length = respHeader.messageHeader.messageSize;
  123. connection->send(connection, &resp_msg);
  124. }
  125. UA_OpenSecureChannelResponse_deleteMembers(&p);
  126. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  127. }
  128. static void init_response_header(const UA_RequestHeader *p, UA_ResponseHeader *r) {
  129. r->requestHandle = p->requestHandle;
  130. r->timestamp = UA_DateTime_now();
  131. }
  132. static void
  133. getServicePointers(UA_UInt32 requestTypeId, const UA_DataType **requestType,
  134. const UA_DataType **responseType, UA_Service *service) {
  135. switch(requestTypeId - UA_ENCODINGOFFSET_BINARY) {
  136. case UA_NS0ID_GETENDPOINTSREQUEST:
  137. *service = (UA_Service)Service_GetEndpoints;
  138. *requestType = &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST];
  139. *responseType = &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE];
  140. break;
  141. case UA_NS0ID_FINDSERVERSREQUEST:
  142. *service = (UA_Service)Service_FindServers;
  143. *requestType = &UA_TYPES[UA_TYPES_FINDSERVERSREQUEST];
  144. *responseType = &UA_TYPES[UA_TYPES_FINDSERVERSRESPONSE];
  145. break;
  146. case UA_NS0ID_CREATESESSIONREQUEST:
  147. *service = (UA_Service)Service_CreateSession;
  148. *requestType = &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST];
  149. *responseType = &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE];
  150. break;
  151. case UA_NS0ID_ACTIVATESESSIONREQUEST:
  152. *service = (UA_Service)Service_ActivateSession;
  153. *requestType = &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST];
  154. *responseType = &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE];
  155. break;
  156. case UA_NS0ID_CLOSESESSIONREQUEST:
  157. *service = (UA_Service)Service_CloseSession;
  158. *requestType = &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST];
  159. *responseType = &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE];
  160. break;
  161. case UA_NS0ID_READREQUEST:
  162. *service = (UA_Service)Service_Read;
  163. *requestType = &UA_TYPES[UA_TYPES_READREQUEST];
  164. *responseType = &UA_TYPES[UA_TYPES_READRESPONSE];
  165. break;
  166. case UA_NS0ID_WRITEREQUEST:
  167. *service = (UA_Service)Service_Write;
  168. *requestType = &UA_TYPES[UA_TYPES_WRITEREQUEST];
  169. *responseType = &UA_TYPES[UA_TYPES_WRITERESPONSE];
  170. break;
  171. case UA_NS0ID_BROWSEREQUEST:
  172. *service = (UA_Service)Service_Browse;
  173. *requestType = &UA_TYPES[UA_TYPES_BROWSEREQUEST];
  174. *responseType = &UA_TYPES[UA_TYPES_BROWSERESPONSE];
  175. break;
  176. case UA_NS0ID_BROWSENEXTREQUEST:
  177. *service = (UA_Service)Service_BrowseNext;
  178. *requestType = &UA_TYPES[UA_TYPES_BROWSENEXTREQUEST];
  179. *responseType = &UA_TYPES[UA_TYPES_BROWSENEXTRESPONSE];
  180. break;
  181. case UA_NS0ID_REGISTERNODESREQUEST:
  182. *service = (UA_Service)Service_RegisterNodes;
  183. *requestType = &UA_TYPES[UA_TYPES_REGISTERNODESREQUEST];
  184. *responseType = &UA_TYPES[UA_TYPES_REGISTERNODESRESPONSE];
  185. break;
  186. case UA_NS0ID_UNREGISTERNODESREQUEST:
  187. *service = (UA_Service)Service_UnregisterNodes;
  188. *requestType = &UA_TYPES[UA_TYPES_UNREGISTERNODESREQUEST];
  189. *responseType = &UA_TYPES[UA_TYPES_UNREGISTERNODESRESPONSE];
  190. break;
  191. case UA_NS0ID_TRANSLATEBROWSEPATHSTONODEIDSREQUEST:
  192. *service = (UA_Service)Service_TranslateBrowsePathsToNodeIds;
  193. *requestType = &UA_TYPES[UA_TYPES_TRANSLATEBROWSEPATHSTONODEIDSREQUEST];
  194. *responseType = &UA_TYPES[UA_TYPES_TRANSLATEBROWSEPATHSTONODEIDSRESPONSE];
  195. break;
  196. #ifdef UA_ENABLE_SUBSCRIPTIONS
  197. case UA_NS0ID_CREATESUBSCRIPTIONREQUEST:
  198. *service = (UA_Service)Service_CreateSubscription;
  199. *requestType = &UA_TYPES[UA_TYPES_CREATESUBSCRIPTIONREQUEST];
  200. *responseType = &UA_TYPES[UA_TYPES_CREATESUBSCRIPTIONRESPONSE];
  201. break;
  202. case UA_NS0ID_PUBLISHREQUEST:
  203. *requestType = &UA_TYPES[UA_TYPES_PUBLISHREQUEST];
  204. *responseType = &UA_TYPES[UA_TYPES_PUBLISHRESPONSE];
  205. break;
  206. case UA_NS0ID_REPUBLISHREQUEST:
  207. *service = (UA_Service)Service_Republish;
  208. *requestType = &UA_TYPES[UA_TYPES_REPUBLISHREQUEST];
  209. *responseType = &UA_TYPES[UA_TYPES_REPUBLISHRESPONSE];
  210. break;
  211. case UA_NS0ID_MODIFYSUBSCRIPTIONREQUEST:
  212. *service = (UA_Service)Service_ModifySubscription;
  213. *requestType = &UA_TYPES[UA_TYPES_MODIFYSUBSCRIPTIONREQUEST];
  214. *responseType = &UA_TYPES[UA_TYPES_MODIFYSUBSCRIPTIONRESPONSE];
  215. break;
  216. case UA_NS0ID_DELETESUBSCRIPTIONSREQUEST:
  217. *service = (UA_Service)Service_DeleteSubscriptions;
  218. *requestType = &UA_TYPES[UA_TYPES_DELETESUBSCRIPTIONSREQUEST];
  219. *responseType = &UA_TYPES[UA_TYPES_DELETESUBSCRIPTIONSRESPONSE];
  220. break;
  221. case UA_NS0ID_CREATEMONITOREDITEMSREQUEST:
  222. *service = (UA_Service)Service_CreateMonitoredItems;
  223. *requestType = &UA_TYPES[UA_TYPES_CREATEMONITOREDITEMSREQUEST];
  224. *responseType = &UA_TYPES[UA_TYPES_CREATEMONITOREDITEMSRESPONSE];
  225. break;
  226. case UA_NS0ID_DELETEMONITOREDITEMSREQUEST:
  227. *service = (UA_Service)Service_DeleteMonitoredItems;
  228. *requestType = &UA_TYPES[UA_TYPES_DELETEMONITOREDITEMSREQUEST];
  229. *responseType = &UA_TYPES[UA_TYPES_DELETEMONITOREDITEMSRESPONSE];
  230. break;
  231. #endif
  232. #ifdef UA_ENABLE_METHODCALLS
  233. case UA_NS0ID_CALLREQUEST:
  234. *service = (UA_Service)Service_Call;
  235. *requestType = &UA_TYPES[UA_TYPES_CALLREQUEST];
  236. *responseType = &UA_TYPES[UA_TYPES_CALLRESPONSE];
  237. break;
  238. #endif
  239. #ifdef UA_ENABLE_NODEMANAGEMENT
  240. case UA_NS0ID_ADDNODESREQUEST:
  241. *service = (UA_Service)Service_AddNodes;
  242. *requestType = &UA_TYPES[UA_TYPES_ADDNODESREQUEST];
  243. *responseType = &UA_TYPES[UA_TYPES_ADDNODESRESPONSE];
  244. break;
  245. case UA_NS0ID_ADDREFERENCESREQUEST:
  246. *service = (UA_Service)Service_AddReferences;
  247. *requestType = &UA_TYPES[UA_TYPES_ADDREFERENCESREQUEST];
  248. *responseType = &UA_TYPES[UA_TYPES_ADDREFERENCESRESPONSE];
  249. break;
  250. case UA_NS0ID_DELETENODESREQUEST:
  251. *service = (UA_Service)Service_DeleteNodes;
  252. *requestType = &UA_TYPES[UA_TYPES_DELETENODESREQUEST];
  253. *responseType = &UA_TYPES[UA_TYPES_DELETENODESRESPONSE];
  254. break;
  255. case UA_NS0ID_DELETEREFERENCESREQUEST:
  256. *service = (UA_Service)Service_DeleteReferences;
  257. *requestType = &UA_TYPES[UA_TYPES_DELETEREFERENCESREQUEST];
  258. *responseType = &UA_TYPES[UA_TYPES_DELETEREFERENCESRESPONSE];
  259. break;
  260. #endif
  261. default:
  262. break;
  263. }
  264. }
  265. static void
  266. sendError(UA_SecureChannel *channel, const UA_ByteString *msg, size_t pos,
  267. UA_UInt32 requestId, UA_StatusCode error) {
  268. UA_RequestHeader p;
  269. if(UA_RequestHeader_decodeBinary(msg, &pos, &p) != UA_STATUSCODE_GOOD)
  270. return;
  271. UA_ResponseHeader r;
  272. UA_ResponseHeader_init(&r);
  273. init_response_header(&p, &r);
  274. r.serviceResult = error;
  275. UA_SecureChannel_sendBinaryMessage(channel, requestId, &r,
  276. &UA_TYPES[UA_TYPES_SERVICEFAULT]);
  277. UA_RequestHeader_deleteMembers(&p);
  278. UA_ResponseHeader_deleteMembers(&r);
  279. }
  280. static void
  281. appendChunkedMessage(struct ChunkEntry *ch, const UA_ByteString *msg, size_t *pos) {
  282. if (ch->invalid_message) {
  283. return;
  284. }
  285. UA_UInt32 len;
  286. *pos -= 20;
  287. UA_UInt32_decodeBinary(msg, pos, &len);
  288. if (len > msg->length) {
  289. UA_ByteString_deleteMembers(&ch->bytes);
  290. ch->invalid_message = UA_TRUE;
  291. return;
  292. }
  293. len -= 24;
  294. *pos += 16; // 4 bytes consumed by decode above
  295. UA_Byte* new_bytes = UA_realloc(ch->bytes.data, ch->bytes.length + len);
  296. if (! new_bytes) {
  297. UA_ByteString_deleteMembers(&ch->bytes);
  298. ch->invalid_message = UA_TRUE;
  299. return;
  300. }
  301. ch->bytes.data = new_bytes;
  302. memcpy(&ch->bytes.data[ch->bytes.length], &msg->data[*pos], len);
  303. ch->bytes.length += len;
  304. *pos += len;
  305. }
  306. static struct ChunkEntry*
  307. chunkEntryFromRequestId(UA_SecureChannel *channel, UA_UInt32 requestId) {
  308. struct ChunkEntry *ch;
  309. LIST_FOREACH(ch, &channel->chunks, pointers) {
  310. if (ch->requestId == requestId) {
  311. return ch;
  312. }
  313. }
  314. return NULL;
  315. }
  316. static void
  317. processMSG(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg, size_t *pos) {
  318. /* If we cannot decode these, don't respond */
  319. UA_UInt32 secureChannelId = 0;
  320. UA_UInt32 tokenId = 0;
  321. UA_SequenceHeader sequenceHeader;
  322. UA_NodeId requestTypeId;
  323. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  324. retval |= UA_UInt32_decodeBinary(msg, pos, &tokenId);
  325. retval |= UA_SequenceHeader_decodeBinary(msg, pos, &sequenceHeader);
  326. if(retval != UA_STATUSCODE_GOOD)
  327. return;
  328. UA_SecureChannel *channel = connection->channel;
  329. UA_SecureChannel anonymousChannel;
  330. if(!channel) {
  331. UA_SecureChannel_init(&anonymousChannel);
  332. anonymousChannel.connection = connection;
  333. channel = &anonymousChannel;
  334. }
  335. /* Test if the secure channel is ok */
  336. if(secureChannelId != channel->securityToken.channelId)
  337. return;
  338. if(tokenId != channel->securityToken.tokenId) {
  339. if(tokenId != channel->nextSecurityToken.tokenId) {
  340. /* close the securechannel but keep the connection open */
  341. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  342. "Request with a wrong security token. Closing the SecureChannel %i.",
  343. channel->securityToken.channelId);
  344. Service_CloseSecureChannel(server, channel->securityToken.channelId);
  345. return;
  346. }
  347. UA_SecureChannel_revolveTokens(channel);
  348. }
  349. size_t final_chunked_pos = 0;
  350. UA_ByteString bytes;
  351. struct ChunkEntry *ch;
  352. switch (msg->data[*pos - 24 + 3]) {
  353. case 'C':
  354. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "Chunk message");
  355. ch = chunkEntryFromRequestId(channel, sequenceHeader.requestId);
  356. if (! ch) {
  357. ch = UA_calloc(1, sizeof(struct ChunkEntry));
  358. ch->invalid_message = UA_FALSE;
  359. ch->requestId = sequenceHeader.requestId;
  360. UA_ByteString_init(&ch->bytes);
  361. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  362. }
  363. appendChunkedMessage(ch, msg, pos);
  364. return;
  365. case 'F':
  366. ch = chunkEntryFromRequestId(channel, sequenceHeader.requestId);
  367. if (ch) {
  368. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "Final chunk message");
  369. appendChunkedMessage(ch, msg, pos);
  370. bytes = ch->bytes;
  371. LIST_REMOVE(ch, pointers);
  372. UA_free(ch);
  373. final_chunked_pos = *pos;
  374. *pos = 0;
  375. // if the chunks have failed decoding
  376. // message is invalid => return early
  377. if (bytes.length == 0) {
  378. *pos = final_chunked_pos;
  379. return;
  380. }
  381. } else {
  382. bytes = *msg;
  383. }
  384. break;
  385. case 'A':
  386. ch = chunkEntryFromRequestId(channel, sequenceHeader.requestId);
  387. if (ch) {
  388. UA_ByteString_deleteMembers(&ch->bytes);
  389. LIST_REMOVE(ch, pointers);
  390. UA_free(ch);
  391. } else {
  392. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "Received MSGA on an unknown request");
  393. }
  394. return;
  395. }
  396. retval |= UA_NodeId_decodeBinary(&bytes, pos, &requestTypeId);
  397. if(retval != UA_STATUSCODE_GOOD)
  398. return;
  399. /* Test if the service type nodeid has the right format */
  400. if(requestTypeId.identifierType != UA_NODEIDTYPE_NUMERIC ||
  401. requestTypeId.namespaceIndex != 0) {
  402. UA_NodeId_deleteMembers(&requestTypeId);
  403. sendError(channel, &bytes, *pos, sequenceHeader.requestId, UA_STATUSCODE_BADSERVICEUNSUPPORTED);
  404. return;
  405. }
  406. /* Get the service pointers */
  407. UA_Service service = NULL;
  408. const UA_DataType *requestType = NULL;
  409. const UA_DataType *responseType = NULL;
  410. getServicePointers(requestTypeId.identifier.numeric, &requestType, &responseType, &service);
  411. if(!requestType) {
  412. /* The service is not supported */
  413. if(requestTypeId.identifier.numeric==787)
  414. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  415. "Client requested a subscription, but those are not enabled "
  416. "in the build. The message will be skipped");
  417. else
  418. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  419. "Unknown request: NodeId(ns=%d, i=%d)",
  420. requestTypeId.namespaceIndex, requestTypeId.identifier.numeric);
  421. sendError(channel, &bytes, *pos, sequenceHeader.requestId, UA_STATUSCODE_BADSERVICEUNSUPPORTED);
  422. return;
  423. }
  424. /* Most services can only be called with a valid securechannel */
  425. #ifndef UA_ENABLE_NONSTANDARD_STATELESS
  426. if(channel == &anonymousChannel &&
  427. requestType->typeIndex > UA_TYPES_OPENSECURECHANNELREQUEST) {
  428. sendError(channel, &bytes, *pos, sequenceHeader.requestId, UA_STATUSCODE_BADSECURECHANNELIDINVALID);
  429. return;
  430. }
  431. #endif
  432. /* Decode the request */
  433. void *request = UA_alloca(requestType->memSize);
  434. size_t oldpos = *pos;
  435. retval = UA_decodeBinary(&bytes, pos, request, requestType);
  436. if(retval != UA_STATUSCODE_GOOD) {
  437. sendError(channel, &bytes, oldpos, sequenceHeader.requestId, retval);
  438. return;
  439. }
  440. /* Find the matching session */
  441. UA_Session *session =
  442. UA_SecureChannel_getSession(channel, &((UA_RequestHeader*)request)->authenticationToken);
  443. UA_Session anonymousSession;
  444. if(!session) {
  445. /* session id 0 -> anonymous session */
  446. UA_Session_init(&anonymousSession);
  447. anonymousSession.channel = channel;
  448. anonymousSession.activated = UA_TRUE;
  449. session = &anonymousSession;
  450. }
  451. /* Test if the session is valid */
  452. if(!session->activated && requestType->typeIndex != UA_TYPES_ACTIVATESESSIONREQUEST) {
  453. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  454. "Client tries to call a service with a non-activated session");
  455. sendError(channel, &bytes, *pos, sequenceHeader.requestId, UA_STATUSCODE_BADSESSIONNOTACTIVATED);
  456. return;
  457. }
  458. #ifndef UA_ENABLE_NONSTANDARD_STATELESS
  459. if(session == &anonymousSession &&
  460. requestType->typeIndex > UA_TYPES_ACTIVATESESSIONREQUEST) {
  461. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  462. "Client tries to call a service without a session");
  463. sendError(channel, &bytes, *pos, sequenceHeader.requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  464. return;
  465. }
  466. #endif
  467. UA_Session_updateLifetime(session);
  468. #ifdef UA_ENABLE_SUBSCRIPTIONS
  469. /* The publish request is answered with a delay */
  470. if(requestTypeId.identifier.numeric - UA_ENCODINGOFFSET_BINARY == UA_NS0ID_PUBLISHREQUEST) {
  471. Service_Publish(server, session, request, sequenceHeader.requestId);
  472. UA_deleteMembers(request, requestType);
  473. return;
  474. }
  475. #endif
  476. /* Call the service */
  477. void *response = UA_alloca(responseType->memSize);
  478. UA_init(response, responseType);
  479. init_response_header(request, response);
  480. service(server, session, request, response);
  481. /* Send the response */
  482. retval = UA_SecureChannel_sendBinaryMessage(channel, sequenceHeader.requestId,
  483. response, responseType);
  484. if(retval != UA_STATUSCODE_GOOD) {
  485. /* e.g. UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED */
  486. sendError(channel, &bytes, oldpos, sequenceHeader.requestId, retval);
  487. }
  488. /* Clean up */
  489. if (final_chunked_pos) {
  490. *pos = final_chunked_pos;
  491. UA_ByteString_deleteMembers(&bytes);
  492. }
  493. UA_deleteMembers(request, requestType);
  494. UA_deleteMembers(response, responseType);
  495. return;
  496. }
  497. static void
  498. processCLO(UA_Connection *connection, UA_Server *server, const UA_ByteString *msg, size_t *pos) {
  499. UA_UInt32 secureChannelId;
  500. UA_StatusCode retval = UA_UInt32_decodeBinary(msg, pos, &secureChannelId);
  501. if(retval != UA_STATUSCODE_GOOD || !connection->channel ||
  502. connection->channel->securityToken.channelId != secureChannelId)
  503. return;
  504. Service_CloseSecureChannel(server, secureChannelId);
  505. }
  506. /**
  507. * process binary message received from Connection
  508. * dose not modify UA_ByteString you have to free it youself.
  509. * use of connection->getSendBuffer() and connection->send() to answer Message
  510. */
  511. void UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection, const UA_ByteString *msg) {
  512. size_t pos = 0;
  513. UA_TcpMessageHeader tcpMessageHeader;
  514. do {
  515. if(UA_TcpMessageHeader_decodeBinary(msg, &pos, &tcpMessageHeader)) {
  516. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  517. "Decoding of message header failed on Connection %i", connection->sockfd);
  518. connection->close(connection);
  519. break;
  520. }
  521. if(tcpMessageHeader.messageSize < 16) {
  522. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  523. "The message is suspiciously small on Connection %i", connection->sockfd);
  524. connection->close(connection);
  525. break;
  526. }
  527. size_t targetpos = pos - 8 + tcpMessageHeader.messageSize;
  528. switch(tcpMessageHeader.messageTypeAndFinal & 0xffffff) {
  529. case UA_MESSAGETYPEANDFINAL_HELF & 0xffffff:
  530. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_NETWORK,
  531. "Process a HEL on Connection %i", connection->sockfd);
  532. processHEL(connection, msg, &pos);
  533. break;
  534. case UA_MESSAGETYPEANDFINAL_OPNF & 0xffffff:
  535. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_NETWORK,
  536. "Process a OPN on Connection %i", connection->sockfd);
  537. processOPN(connection, server, msg, &pos);
  538. break;
  539. case UA_MESSAGETYPEANDFINAL_MSGF & 0xffffff:
  540. #ifndef UA_ENABLE_NONSTANDARD_STATELESS
  541. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  542. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_NETWORK,
  543. "Received a MSG where the connection is not established on Connection %i",
  544. connection->sockfd);
  545. connection->close(connection);
  546. return;
  547. }
  548. #endif
  549. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_NETWORK,
  550. "Process a MSG on Connection %i", connection->sockfd);
  551. processMSG(connection, server, msg, &pos);
  552. break;
  553. case UA_MESSAGETYPEANDFINAL_CLOF & 0xffffff:
  554. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_NETWORK,
  555. "Process a CLO on Connection %i", connection->sockfd);
  556. processCLO(connection, server, msg, &pos);
  557. connection->close(connection);
  558. return;
  559. default:
  560. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  561. "Unknown request type on Connection %i", connection->sockfd);
  562. }
  563. UA_TcpMessageHeader_deleteMembers(&tcpMessageHeader);
  564. if(pos != targetpos) {
  565. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  566. "Message on Connection %i was not entirely processed. "
  567. "Arrived at position %i, skip after the announced length to position %i",
  568. connection->sockfd, pos, targetpos);
  569. pos = targetpos;
  570. }
  571. } while(msg->length > pos);
  572. }