ua_connection.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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_internal.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->incompleteChunk);
  21. }
  22. UA_StatusCode
  23. UA_Connection_processHELACK(UA_Connection *connection,
  24. const UA_ConnectionConfig *localConfig,
  25. const UA_ConnectionConfig *remoteConfig) {
  26. connection->config = *remoteConfig;
  27. /* The lowest common version is used by both sides */
  28. if(connection->config.protocolVersion > localConfig->protocolVersion)
  29. connection->config.protocolVersion = localConfig->protocolVersion;
  30. /* Can we receive the max send size? */
  31. if(connection->config.sendBufferSize > localConfig->recvBufferSize)
  32. connection->config.sendBufferSize = localConfig->recvBufferSize;
  33. /* Can we send the max receive size? */
  34. if(connection->config.recvBufferSize > localConfig->sendBufferSize)
  35. connection->config.recvBufferSize = localConfig->sendBufferSize;
  36. /* Chunks of at least 8192 bytes must be permissible.
  37. * See Part 6, Clause 6.7.1 */
  38. if(connection->config.recvBufferSize < 8192 ||
  39. connection->config.sendBufferSize < 8192 ||
  40. (connection->config.maxMessageSize != 0 &&
  41. connection->config.maxMessageSize < 8192))
  42. return UA_STATUSCODE_BADINTERNALERROR;
  43. connection->state = UA_CONNECTION_ESTABLISHED;
  44. return UA_STATUSCODE_GOOD;
  45. }
  46. /* Hides somme errors before sending them to a client according to the
  47. * standard. */
  48. static void
  49. hideErrors(UA_TcpErrorMessage *const error) {
  50. switch(error->error) {
  51. case UA_STATUSCODE_BADCERTIFICATEUNTRUSTED:
  52. error->error = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  53. error->reason = UA_STRING_NULL;
  54. break;
  55. // TODO: Check if these are all cases that need to be covered.
  56. default:
  57. break;
  58. }
  59. }
  60. void
  61. UA_Connection_sendError(UA_Connection *connection, UA_TcpErrorMessage *error) {
  62. hideErrors(error);
  63. UA_TcpMessageHeader header;
  64. header.messageTypeAndChunkType = UA_MESSAGETYPE_ERR + UA_CHUNKTYPE_FINAL;
  65. // Header + ErrorMessage (error + reasonLength_field + length)
  66. header.messageSize = 8 + (4 + 4 + (UA_UInt32)error->reason.length);
  67. /* Get the send buffer from the network layer */
  68. UA_ByteString msg = UA_BYTESTRING_NULL;
  69. UA_StatusCode retval = connection->getSendBuffer(connection, header.messageSize, &msg);
  70. if(retval != UA_STATUSCODE_GOOD)
  71. return;
  72. /* Encode and send the response */
  73. UA_Byte *bufPos = msg.data;
  74. const UA_Byte *bufEnd = &msg.data[msg.length];
  75. UA_TcpMessageHeader_encodeBinary(&header, &bufPos, bufEnd);
  76. UA_TcpErrorMessage_encodeBinary(error, &bufPos, bufEnd);
  77. msg.length = header.messageSize;
  78. connection->send(connection, &msg);
  79. }
  80. static UA_StatusCode
  81. bufferIncompleteChunk(UA_Connection *connection, const UA_Byte *pos,
  82. const UA_Byte *end) {
  83. UA_assert(pos < end);
  84. size_t length = (uintptr_t)end - (uintptr_t)pos;
  85. UA_StatusCode retval = UA_ByteString_allocBuffer(&connection->incompleteChunk, length);
  86. if(retval != UA_STATUSCODE_GOOD)
  87. return retval;
  88. memcpy(connection->incompleteChunk.data, pos, length);
  89. return UA_STATUSCODE_GOOD;
  90. }
  91. static UA_StatusCode
  92. processChunk(UA_Connection *connection, void *application,
  93. UA_Connection_processChunk processCallback,
  94. const UA_Byte **posp, const UA_Byte *end, UA_Boolean *done) {
  95. const UA_Byte *pos = *posp;
  96. const size_t remaining = (uintptr_t)end - (uintptr_t)pos;
  97. /* At least 8 byte needed for the header. Wait for the next chunk. */
  98. if(remaining < 8) {
  99. *done = true;
  100. return UA_STATUSCODE_GOOD;
  101. }
  102. /* Check the message type */
  103. UA_MessageType msgtype = (UA_MessageType)
  104. ((UA_UInt32)pos[0] + ((UA_UInt32)pos[1] << 8) + ((UA_UInt32)pos[2] << 16));
  105. if(msgtype != UA_MESSAGETYPE_MSG && msgtype != UA_MESSAGETYPE_ERR &&
  106. msgtype != UA_MESSAGETYPE_OPN && msgtype != UA_MESSAGETYPE_HEL &&
  107. msgtype != UA_MESSAGETYPE_ACK && msgtype != UA_MESSAGETYPE_CLO) {
  108. /* The message type is not recognized */
  109. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  110. }
  111. UA_Byte isFinal = pos[3];
  112. if(isFinal != 'C' && isFinal != 'F' && isFinal != 'A') {
  113. /* The message type is not recognized */
  114. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  115. }
  116. UA_UInt32 chunk_length = 0;
  117. UA_ByteString temp = { 8, (UA_Byte*)(uintptr_t)pos }; /* At least 8 byte left */
  118. size_t temp_offset = 4;
  119. /* Decoding the UInt32 cannot fail */
  120. UA_UInt32_decodeBinary(&temp, &temp_offset, &chunk_length);
  121. /* The message size is not allowed */
  122. if(chunk_length < 16 || chunk_length > connection->config.recvBufferSize)
  123. return UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
  124. /* Have an the complete chunk */
  125. if(chunk_length > remaining) {
  126. *done = true;
  127. return UA_STATUSCODE_GOOD;
  128. }
  129. /* Process the chunk; forward the position pointer */
  130. temp.length = chunk_length;
  131. *posp += chunk_length;
  132. *done = false;
  133. return processCallback(application, connection, &temp);
  134. }
  135. UA_StatusCode
  136. UA_Connection_processChunks(UA_Connection *connection, void *application,
  137. UA_Connection_processChunk processCallback,
  138. const UA_ByteString *packet) {
  139. /* The connection has already prepended any incomplete chunk during recv */
  140. UA_assert(connection->incompleteChunk.length == 0);
  141. /* Loop over the received chunks. pos is increased with each chunk. */
  142. const UA_Byte *pos = packet->data;
  143. const UA_Byte *end = &packet->data[packet->length];
  144. UA_Boolean done = false;
  145. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  146. while(!done) {
  147. retval = processChunk(connection, application, processCallback, &pos, end, &done);
  148. /* If an irrecoverable error happens: do not buffer incomplete chunk */
  149. if(retval != UA_STATUSCODE_GOOD)
  150. return retval;
  151. }
  152. if(end > pos)
  153. retval = bufferIncompleteChunk(connection, pos, end);
  154. return retval;
  155. }
  156. /* In order to know whether a chunk was processed, we insert an redirection into
  157. * the callback. */
  158. struct completeChunkTrampolineData {
  159. UA_Boolean called;
  160. void *application;
  161. UA_Connection_processChunk processCallback;
  162. };
  163. static UA_StatusCode
  164. completeChunkTrampoline(void *application, UA_Connection *connection,
  165. UA_ByteString *chunk) {
  166. struct completeChunkTrampolineData *data =
  167. (struct completeChunkTrampolineData*)application;
  168. data->called = true;
  169. return data->processCallback(data->application, connection, chunk);
  170. }
  171. UA_StatusCode
  172. UA_Connection_receiveChunksBlocking(UA_Connection *connection, void *application,
  173. UA_Connection_processChunk processCallback,
  174. UA_UInt32 timeout) {
  175. UA_DateTime now = UA_DateTime_nowMonotonic();
  176. UA_DateTime maxDate = now + (timeout * UA_DATETIME_MSEC);
  177. struct completeChunkTrampolineData data;
  178. data.called = false;
  179. data.application = application;
  180. data.processCallback = processCallback;
  181. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  182. while(true) {
  183. /* Listen for messages to arrive */
  184. UA_ByteString packet = UA_BYTESTRING_NULL;
  185. retval = connection->recv(connection, &packet, timeout);
  186. if(retval != UA_STATUSCODE_GOOD)
  187. break;
  188. /* Try to process one complete chunk */
  189. retval = UA_Connection_processChunks(connection, &data,
  190. completeChunkTrampoline, &packet);
  191. connection->releaseRecvBuffer(connection, &packet);
  192. if(data.called)
  193. break;
  194. /* We received a message. But the chunk is incomplete. Compute the
  195. * remaining timeout. */
  196. now = UA_DateTime_nowMonotonic();
  197. /* >= avoid timeout to be set to 0 */
  198. if(now >= maxDate)
  199. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  200. /* round always to upper value to avoid timeout to be set to 0
  201. * if(maxDate - now) < (UA_DATETIME_MSEC/2) */
  202. timeout = (UA_UInt32)(((maxDate - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  203. }
  204. return retval;
  205. }
  206. UA_StatusCode
  207. UA_Connection_receiveChunksNonBlocking(UA_Connection *connection, void *application,
  208. UA_Connection_processChunk processCallback) {
  209. struct completeChunkTrampolineData data;
  210. data.called = false;
  211. data.application = application;
  212. data.processCallback = processCallback;
  213. /* Listen for messages to arrive */
  214. UA_ByteString packet = UA_BYTESTRING_NULL;
  215. UA_StatusCode retval = connection->recv(connection, &packet, 1);
  216. if((retval != UA_STATUSCODE_GOOD) && (retval != UA_STATUSCODE_GOODNONCRITICALTIMEOUT))
  217. return retval;
  218. /* Try to process one complete chunk */
  219. retval = UA_Connection_processChunks(connection, &data, completeChunkTrampoline, &packet);
  220. connection->releaseRecvBuffer(connection, &packet);
  221. return retval;
  222. }
  223. void UA_Connection_detachSecureChannel(UA_Connection *connection) {
  224. UA_SecureChannel *channel = connection->channel;
  225. if(channel)
  226. /* only replace when the channel points to this connection */
  227. UA_atomic_cmpxchg((void**)&channel->connection, connection, NULL);
  228. UA_atomic_xchg((void**)&connection->channel, NULL);
  229. }
  230. // TODO: Return an error code
  231. void
  232. UA_Connection_attachSecureChannel(UA_Connection *connection, UA_SecureChannel *channel) {
  233. if(UA_atomic_cmpxchg((void**)&channel->connection, NULL, connection) == NULL)
  234. UA_atomic_xchg((void**)&connection->channel, (void*)channel);
  235. }