ua_connection.c 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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_connection_internal.h"
  6. #include "ua_types_encoding_binary.h"
  7. #include "ua_types_generated_encoding_binary.h"
  8. #include "ua_types_generated_handling.h"
  9. #include "ua_transport_generated_encoding_binary.h"
  10. #include "ua_securechannel.h"
  11. void UA_Connection_deleteMembers(UA_Connection *connection) {
  12. UA_ByteString_deleteMembers(&connection->incompleteMessage);
  13. }
  14. /* Hides somme errors before sending them to a client according to the
  15. * standard. */
  16. static void
  17. hideErrors(UA_TcpErrorMessage *const error) {
  18. switch(error->error) {
  19. case UA_STATUSCODE_BADCERTIFICATEUNTRUSTED:
  20. error->error = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  21. error->reason = UA_STRING_NULL;
  22. break;
  23. // TODO: Check if these are all cases that need to be covered.
  24. default:
  25. break;
  26. }
  27. }
  28. void
  29. UA_Connection_sendError(UA_Connection *connection, UA_TcpErrorMessage *error) {
  30. hideErrors(error);
  31. UA_TcpMessageHeader header;
  32. header.messageTypeAndChunkType = UA_MESSAGETYPE_ERR + UA_CHUNKTYPE_FINAL;
  33. // Header + ErrorMessage (error + reasonLength_field + length)
  34. header.messageSize = 8 + (4 + 4 + (UA_UInt32)error->reason.length);
  35. /* Get the send buffer from the network layer */
  36. UA_ByteString msg = UA_BYTESTRING_NULL;
  37. UA_StatusCode retval = connection->getSendBuffer(connection, header.messageSize, &msg);
  38. if(retval != UA_STATUSCODE_GOOD)
  39. return;
  40. /* Encode and send the response */
  41. UA_Byte *bufPos = msg.data;
  42. const UA_Byte *bufEnd = &msg.data[msg.length];
  43. UA_TcpMessageHeader_encodeBinary(&header, &bufPos, &bufEnd);
  44. UA_TcpErrorMessage_encodeBinary(error, &bufPos, &bufEnd);
  45. msg.length = header.messageSize;
  46. connection->send(connection, &msg);
  47. }
  48. static UA_StatusCode
  49. prependIncompleteChunk(UA_Connection *connection, UA_ByteString *message) {
  50. /* Allocate the new message buffer */
  51. size_t length = connection->incompleteMessage.length + message->length;
  52. UA_Byte *data = (UA_Byte*)UA_realloc(connection->incompleteMessage.data, length);
  53. if(!data) {
  54. UA_ByteString_deleteMembers(&connection->incompleteMessage);
  55. return UA_STATUSCODE_BADOUTOFMEMORY;
  56. }
  57. /* Copy / release the current message buffer */
  58. memcpy(&data[connection->incompleteMessage.length], message->data, message->length);
  59. message->length = length;
  60. message->data = data;
  61. connection->incompleteMessage = UA_BYTESTRING_NULL;
  62. return UA_STATUSCODE_GOOD;
  63. }
  64. static UA_StatusCode
  65. bufferIncompleteChunk(UA_Connection *connection, const UA_Byte *pos, const UA_Byte *end) {
  66. size_t length = (uintptr_t)end - (uintptr_t)pos;
  67. UA_StatusCode retval = UA_ByteString_allocBuffer(&connection->incompleteMessage, length);
  68. if(retval != UA_STATUSCODE_GOOD)
  69. return retval;
  70. memcpy(connection->incompleteMessage.data, pos, length);
  71. return UA_STATUSCODE_GOOD;
  72. }
  73. static UA_StatusCode
  74. processChunk(UA_Connection *connection, void *application,
  75. UA_Connection_processChunk processCallback,
  76. const UA_Byte **posp, const UA_Byte *end, UA_Boolean *done) {
  77. const UA_Byte *pos = *posp;
  78. size_t length = (uintptr_t)end - (uintptr_t)pos;
  79. /* At least 8 byte needed for the header. Wait for the next chunk. */
  80. if(length < 8) {
  81. bufferIncompleteChunk(connection, pos, end);
  82. *done = true;
  83. return UA_STATUSCODE_GOOD;
  84. }
  85. /* Check the message type */
  86. UA_MessageType msgtype = (UA_MessageType)((UA_UInt32)pos[0] + ((UA_UInt32)pos[1] << 8) +
  87. ((UA_UInt32)pos[2] << 16));
  88. if(msgtype != UA_MESSAGETYPE_MSG && msgtype != UA_MESSAGETYPE_ERR &&
  89. msgtype != UA_MESSAGETYPE_OPN && msgtype != UA_MESSAGETYPE_HEL &&
  90. msgtype != UA_MESSAGETYPE_ACK && msgtype != UA_MESSAGETYPE_CLO) {
  91. /* The message type is not recognized */
  92. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  93. }
  94. UA_Byte isFinal = pos[3];
  95. if(isFinal != 'C' && isFinal != 'F' && isFinal != 'A') {
  96. /* The message type is not recognized */
  97. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  98. }
  99. UA_UInt32 chunk_length = 0;
  100. UA_ByteString temp = { 8, (UA_Byte*)(uintptr_t)pos }; /* At least 8 byte left */
  101. size_t temp_offset = 4;
  102. /* Decoding the UInt32 cannot fail */
  103. UA_UInt32_decodeBinary(&temp, &temp_offset, &chunk_length);
  104. /* The message size is not allowed */
  105. if(chunk_length < 16 || chunk_length > connection->localConf.recvBufferSize)
  106. return UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
  107. /* Wait for the next packet to process the complete chunk */
  108. if(chunk_length > length) {
  109. bufferIncompleteChunk(connection, pos, end);
  110. *done = true;
  111. return UA_STATUSCODE_GOOD;
  112. }
  113. /* Process the chunk; forward the position pointer */
  114. temp.length = chunk_length;
  115. *posp += chunk_length;
  116. *done = false;
  117. return processCallback(application, connection, &temp);
  118. }
  119. UA_StatusCode
  120. UA_Connection_processChunks(UA_Connection *connection, void *application,
  121. UA_Connection_processChunk processCallback,
  122. const UA_ByteString *packet) {
  123. /* If we have stored an incomplete chunk, prefix to the received message.
  124. * After this block, connection->incompleteMessage is always empty. The
  125. * message and the buffer is released if allocating the memory fails. */
  126. UA_Boolean realloced = false;
  127. UA_ByteString message = *packet;
  128. UA_StatusCode retval;
  129. if(connection->incompleteMessage.length > 0) {
  130. retval = prependIncompleteChunk(connection, &message);
  131. if(retval != UA_STATUSCODE_GOOD)
  132. return retval;
  133. realloced = true;
  134. }
  135. /* Loop over the received chunks. pos is increased with each chunk. */
  136. const UA_Byte *pos = message.data;
  137. const UA_Byte *end = &message.data[message.length];
  138. UA_Boolean done = true;
  139. do {
  140. retval = processChunk(connection, application, processCallback,
  141. &pos, end, &done);
  142. } while(!done && retval == UA_STATUSCODE_GOOD);
  143. if(realloced)
  144. UA_ByteString_deleteMembers(&message);
  145. return retval;
  146. }
  147. /* In order to know whether a chunk was processed, we insert an indirection into
  148. * the callback. */
  149. struct completeChunkTrampolineData {
  150. UA_Boolean called;
  151. void *application;
  152. UA_Connection_processChunk processCallback;
  153. };
  154. static UA_StatusCode
  155. completeChunkTrampoline(void *application, UA_Connection *connection,
  156. UA_ByteString *chunk) {
  157. struct completeChunkTrampolineData *data =
  158. (struct completeChunkTrampolineData*)application;
  159. data->called = true;
  160. return data->processCallback(data->application, connection, chunk);
  161. }
  162. UA_StatusCode
  163. UA_Connection_receiveChunksBlocking(UA_Connection *connection, void *application,
  164. UA_Connection_processChunk processCallback,
  165. UA_UInt32 timeout) {
  166. UA_DateTime now = UA_DateTime_nowMonotonic();
  167. UA_DateTime maxDate = now + (timeout * UA_DATETIME_MSEC);
  168. struct completeChunkTrampolineData data;
  169. data.called = false;
  170. data.application = application;
  171. data.processCallback = processCallback;
  172. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  173. while(true) {
  174. /* Listen for messages to arrive */
  175. UA_ByteString packet = UA_BYTESTRING_NULL;
  176. retval = connection->recv(connection, &packet, timeout);
  177. if(retval != UA_STATUSCODE_GOOD)
  178. break;
  179. /* Try to process one complete chunk */
  180. retval = UA_Connection_processChunks(connection, &data,
  181. completeChunkTrampoline, &packet);
  182. connection->releaseRecvBuffer(connection, &packet);
  183. if(data.called)
  184. break;
  185. /* We received a message. But the chunk is incomplete. Compute the
  186. * remaining timeout. */
  187. now = UA_DateTime_nowMonotonic();
  188. /* >= avoid timeout to be set to 0 */
  189. if(now >= maxDate)
  190. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  191. /* round always to upper value to avoid timeout to be set to 0
  192. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  193. timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  194. }
  195. return retval;
  196. }
  197. void UA_Connection_detachSecureChannel(UA_Connection *connection) {
  198. UA_SecureChannel *channel = connection->channel;
  199. if(channel)
  200. /* only replace when the channel points to this connection */
  201. UA_atomic_cmpxchg((void**)&channel->connection, connection, NULL);
  202. UA_atomic_xchg((void**)&connection->channel, NULL);
  203. }
  204. // TODO: Return an error code
  205. void
  206. UA_Connection_attachSecureChannel(UA_Connection *connection, UA_SecureChannel *channel) {
  207. if(UA_atomic_cmpxchg((void**)&channel->connection, NULL, connection) == NULL)
  208. UA_atomic_xchg((void**)&connection->channel, (void*)channel);
  209. }