ua_connection.c 11 KB

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