ua_connection.c 9.3 KB

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