You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by al...@apache.org on 2018/02/21 17:10:27 UTC
[1/2] nifi-minifi-cpp git commit: MINIFICPP-406: Ensure that Context
Service OR minifi properties can be used to configure secure comms ( HTTP &
Socket)
Repository: nifi-minifi-cpp
Updated Branches:
refs/heads/master c89ef2206 -> 0b1a01ad4
MINIFICPP-406: Ensure that Context Service OR minifi properties can be used
to configure secure comms ( HTTP & Socket)
Project: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/repo
Commit: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/commit/13a283d9
Tree: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/tree/13a283d9
Diff: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/diff/13a283d9
Branch: refs/heads/master
Commit: 13a283d981596b71ba01aa44fe52536712be7925
Parents: c89ef22
Author: Marc Parisi <ph...@apache.org>
Authored: Sat Feb 17 13:00:26 2018 -0500
Committer: Marc Parisi <ph...@apache.org>
Committed: Tue Feb 20 07:41:45 2018 -0500
----------------------------------------------------------------------
README.md | 2 +-
cmake/BuildTests.cmake | 2 +
libminifi/include/io/ClientSocket.h | 2 +
libminifi/include/io/StreamFactory.h | 12 +-
libminifi/include/io/TLSSocket.h | 193 ------------
libminifi/include/io/tls/TLSServerSocket.h | 71 +++++
libminifi/include/io/tls/TLSSocket.h | 58 ++--
libminifi/include/processors/GetTCP.h | 9 +-
.../include/sitetosite/SiteToSiteFactory.h | 11 +-
libminifi/src/c2/ControllerSocketProtocol.cpp | 2 +-
libminifi/src/io/ClientSocket.cpp | 21 +-
libminifi/src/io/StreamFactory.cpp | 20 +-
libminifi/src/io/tls/TLSServerSocket.cpp | 114 +++++++
libminifi/src/io/tls/TLSSocket.cpp | 303 ++++++++++++++++---
libminifi/src/processors/GetTCP.cpp | 24 +-
libminifi/test/integration/IntegrationBase.h | 4 +-
.../test/integration/SecureSocketGetTCPTest.cpp | 198 ++++++++++++
libminifi/test/resources/TestGetTCPSecure.yml | 90 ++++++
libminifi/test/resources/nifi-key.pem | 27 ++
libminifi/test/unit/GetTCPTests.cpp | 4 +
libminifi/test/unit/SocketTests.cpp | 14 +
libminifi/test/unit/UpdateAttributeTests.cpp | 14 +-
22 files changed, 897 insertions(+), 298 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
index 3228cba..2bcb231 100644
--- a/README.md
+++ b/README.md
@@ -478,7 +478,7 @@ Additionally, users can utilize the MiNiFi Toolkit Converter (version 0.0.1 - sc
if you do not want to enable client certificate base authorization
nifi.security.need.ClientAuth=false
-If you are using HTTP Site to Site, you have the option of specifying an SSL Context Service definition for the RPGs.
+You have the option of specifying an SSL Context Service definition for the RPGs instead of the properties above.
This will link to a corresponding SSL Context service defined in the flow.
To do this specify the SSL Context Service Property in your RPGs and link it to
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/cmake/BuildTests.cmake
----------------------------------------------------------------------
diff --git a/cmake/BuildTests.cmake b/cmake/BuildTests.cmake
index 9a180f0..2a0277b 100644
--- a/cmake/BuildTests.cmake
+++ b/cmake/BuildTests.cmake
@@ -117,3 +117,5 @@ endforeach()
add_test(NAME TestExecuteProcess COMMAND TestExecuteProcess )
+add_test(NAME SecureSocketGetTCPTest COMMAND SecureSocketGetTCPTest "${TEST_RESOURCES}/TestGetTCPSecure.yml" "${TEST_RESOURCES}/")
+
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/io/ClientSocket.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/ClientSocket.h b/libminifi/include/io/ClientSocket.h
index fb5758f..263865c 100644
--- a/libminifi/include/io/ClientSocket.h
+++ b/libminifi/include/io/ClientSocket.h
@@ -265,6 +265,8 @@ class Socket : public BaseStream {
std::atomic<uint16_t> socket_max_;
uint16_t listeners_;
+
+ bool nonBlocking_;
private:
std::shared_ptr<logging::Logger> logger_;
static std::string init_hostname() {
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/io/StreamFactory.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/StreamFactory.h b/libminifi/include/io/StreamFactory.h
index bcb2847..bbb09b9 100644
--- a/libminifi/include/io/StreamFactory.h
+++ b/libminifi/include/io/StreamFactory.h
@@ -21,7 +21,7 @@
#include "Sockets.h"
#include "utils/StringUtils.h"
#include "validation.h"
-
+#include "controllers/SSLContextService.h"
namespace org {
namespace apache {
namespace nifi {
@@ -34,6 +34,8 @@ class AbstractStreamFactory {
}
virtual std::unique_ptr<Socket> createSocket(const std::string &host, const uint16_t port) = 0;
+
+ virtual std::unique_ptr<Socket> createSecureSocket(const std::string &host, const uint16_t port, const std::shared_ptr<minifi::controllers::SSLContextService> &ssl_service) = 0;
};
/**
@@ -52,6 +54,14 @@ class StreamFactory {
return delegate_->createSocket(host, port);
}
+ /**
+ * Creates a socket and returns a unique ptr
+ *
+ */
+ std::unique_ptr<Socket> createSecureSocket(const std::string &host, const uint16_t port, const std::shared_ptr<minifi::controllers::SSLContextService> &ssl_service) {
+ return delegate_->createSecureSocket(host, port, ssl_service);
+ }
+
StreamFactory(const std::shared_ptr<Configure> &configure);
protected:
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/io/TLSSocket.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/TLSSocket.h b/libminifi/include/io/TLSSocket.h
deleted file mode 100644
index e9e6ce4..0000000
--- a/libminifi/include/io/TLSSocket.h
+++ /dev/null
@@ -1,193 +0,0 @@
-/**
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef LIBMINIFI_INCLUDE_IO_TLSSOCKET_H_
-#define LIBMINIFI_INCLUDE_IO_TLSSOCKET_H_
-
-#include <cstdint>
-#include "ClientSocket.h"
-#include <atomic>
-#include <mutex>
-
-#include "properties/Configure.h"
-
-namespace org {
-namespace apache {
-namespace nifi {
-namespace minifi {
-namespace io {
-
-#include <openssl/ssl.h>
-#include <openssl/err.h>
-
-#define TLS_ERROR_CONTEXT 1
-#define TLS_ERROR_PEM_MISSING 2
-#define TLS_ERROR_CERT_MISSING 3
-#define TLS_ERROR_KEY_ERROR 4
-#define TLS_ERROR_CERT_ERROR 5
-
-class TLSContext {
-
- public:
-
- /**
- * Build an instance, creating a memory fence, which
- * allows us to avoid locking. This is tantamount to double checked locking.
- * @returns new TLSContext;
- */
- static TLSContext *getInstance() {
- TLSContext* atomic_context = context_instance.load(std::memory_order_relaxed);
- std::atomic_thread_fence(std::memory_order_acquire);
- if (atomic_context == nullptr) {
- std::lock_guard<std::mutex> lock(context_mutex);
- atomic_context = context_instance.load(std::memory_order_relaxed);
- if (atomic_context == nullptr) {
- atomic_context = new TLSContext();
- atomic_context->initialize();
- std::atomic_thread_fence(std::memory_order_release);
- context_instance.store(atomic_context, std::memory_order_relaxed);
- }
- }
- return atomic_context;
- }
-
- virtual ~TLSContext() {
- if (0 != ctx)
- SSL_CTX_free(ctx);
- }
-
- SSL_CTX *getContext() {
- return ctx;
- }
-
- short getError() {
- return error_value;
- }
-
- short initialize();
-
- private:
-
- static int pemPassWordCb(char *buf, int size, int rwflag, void *userdata) {
- std::string passphrase;
-
- if (Configure::getConfigure()->get(Configure::nifi_security_client_pass_phrase, passphrase)) {
-
- std::ifstream file(passphrase.c_str(), std::ifstream::in);
- if (!file.good()) {
- memset(buf, 0x00, size);
- return 0;
- }
-
- std::string password;
- password.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
- file.close();
- memset(buf, 0x00, size);
- memcpy(buf, password.c_str(), password.length() - 1);
-
- return password.length() - 1;
- }
- return 0;
- }
-
- TLSContext();
-
- std::shared_ptr<logging::Logger> logger_;
- Configure *configuration;
- SSL_CTX *ctx;
-
- short error_value;
-
- static std::atomic<TLSContext*> context_instance;
- static std::mutex context_mutex;
-};
-
-class TLSSocket : public Socket {
- public:
-
- /**
- * Constructor that accepts host name, port and listeners. With this
- * contructor we will be creating a server socket
- * @param hostname our host name
- * @param port connecting port
- * @param listeners number of listeners in the queue
- */
- explicit TLSSocket(const std::string &hostname, const uint16_t port, const uint16_t listeners);
-
- /**
- * Constructor that creates a client socket.
- * @param hostname hostname we are connecting to.
- * @param port port we are connecting to.
- */
- explicit TLSSocket(const std::string &hostname, const uint16_t port);
-
- /**
- * Move constructor.
- */
- explicit TLSSocket(const TLSSocket &&);
-
- virtual ~TLSSocket();
-
- /**
- * Initializes the socket
- * @return result of the creation operation.
- */
- short initialize();
-
- /**
- * Attempt to select the socket file descriptor
- * @param msec timeout interval to wait
- * @returns file descriptor
- */
- virtual short select_descriptor(const uint16_t msec);
-
- /**
- * Reads data and places it into buf
- * @param buf buffer in which we extract data
- * @param buflen
- */
- virtual int readData(uint8_t *buf, int buflen);
-
- /**
- * Write value to the stream using std::vector
- * @param buf incoming buffer
- * @param buflen buffer to write
- *
- */
- int writeData(std::vector<uint8_t> &buf, int buflen);
-
- /**
- * Write value to the stream using uint8_t ptr
- * @param buf incoming buffer
- * @param buflen buffer to write
- *
- */
- int writeData(uint8_t *value, int size);
-
- protected:
-
- SSL* ssl;
-
-};
-
-} /* namespace io */
-} /* namespace minifi */
-} /* namespace nifi */
-} /* namespace apache */
-} /* namespace org */
-
-#endif /* LIBMINIFI_INCLUDE_IO_TLSSOCKET_H_ */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/io/tls/TLSServerSocket.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/tls/TLSServerSocket.h b/libminifi/include/io/tls/TLSServerSocket.h
new file mode 100644
index 0000000..a7ec6fe
--- /dev/null
+++ b/libminifi/include/io/tls/TLSServerSocket.h
@@ -0,0 +1,71 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef LIBMINIFI_INCLUDE_IO_TLSSERVERSOCKET_H_
+#define LIBMINIFI_INCLUDE_IO_TLSSERVERSOCKET_H_
+
+#include "TLSSocket.h"
+
+namespace org {
+namespace apache {
+namespace nifi {
+namespace minifi {
+namespace io {
+
+/**
+ * Purpose: Server socket abstraction that makes focusing the accept/block paradigm
+ * simpler.
+ */
+class TLSServerSocket : public TLSSocket {
+ public:
+ explicit TLSServerSocket(const std::shared_ptr<TLSContext> &context, const std::string &hostname, const uint16_t port, const uint16_t listeners);
+
+ virtual ~TLSServerSocket();
+
+ int16_t initialize(bool loopbackOnly){
+ is_loopback_only_ = loopbackOnly;
+ return TLSSocket::initialize();
+ }
+
+ virtual int16_t initialize(){
+ return TLSSocket::initialize();
+ }
+
+ /**
+ * Registers a call back and starts the read for the server socket.
+ */
+ void registerCallback(std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*,int *)> handler);
+
+ private:
+
+ std::function<void(std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*,int *)> handler)> fx;
+
+ void close_fd(int fd );
+
+ std::atomic<bool> running_;
+
+ std::thread server_read_thread_;
+
+ std::shared_ptr<logging::Logger> logger_;
+};
+
+} /* namespace io */
+} /* namespace minifi */
+} /* namespace nifi */
+} /* namespace apache */
+} /* namespace org */
+#endif /* LIBMINIFI_INCLUDE_IO_TLSSERVERSOCKET_H_ */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/io/tls/TLSSocket.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/tls/TLSSocket.h b/libminifi/include/io/tls/TLSSocket.h
index 14978e4..d3257e1 100644
--- a/libminifi/include/io/tls/TLSSocket.h
+++ b/libminifi/include/io/tls/TLSSocket.h
@@ -20,10 +20,11 @@
#include <openssl/ssl.h>
#include <openssl/err.h>
+#include "controllers/SSLContextService.h"
#include <atomic>
#include <cstdint>
-#include "../ClientSocket.h"
-
+#include "io/ClientSocket.h"
+#include "capi/expect.h"
#include "properties/Configure.h"
namespace org {
@@ -68,7 +69,7 @@ class OpenSSLInitializer {
class TLSContext : public SocketContext {
public:
- TLSContext(const std::shared_ptr<Configure> &configure);
+ TLSContext(const std::shared_ptr<Configure> &configure, const std::shared_ptr<minifi::controllers::SSLContextService> &ssl_service = nullptr);
virtual ~TLSContext() {
if (0 != ctx)
@@ -83,34 +84,26 @@ class TLSContext : public SocketContext {
return error_value;
}
- int16_t initialize();
+ int16_t initialize(bool server_method = false);
private:
- static int pemPassWordCb(char *buf, int size, int rwflag, void *configure) {
- std::string passphrase;
-
- if (static_cast<Configure*>(configure)->get(Configure::nifi_security_client_pass_phrase, passphrase)) {
+ static int pemPassWordCb(char *buf, int size, int rwflag, void *userdata) {
- std::ifstream file(passphrase.c_str(), std::ifstream::in);
- if (!file.good()) {
- memset(buf, 0x00, size);
- return 0;
- }
+ std::string *pass = (std::string*) userdata;
+ if (pass->length() > 0) {
- std::string password;
- password.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
- file.close();
memset(buf, 0x00, size);
- memcpy(buf, password.c_str(), password.length() - 1);
+ memcpy(buf, pass->c_str(), pass->length() - 1);
- return password.length() - 1;
+ return pass->length() - 1;
}
return 0;
}
std::shared_ptr<logging::Logger> logger_;
std::shared_ptr<Configure> configure_;
+ std::shared_ptr<minifi::controllers::SSLContextService> ssl_service_;
SSL_CTX *ctx;
int16_t error_value;
@@ -148,7 +141,11 @@ class TLSSocket : public Socket {
* Initializes the socket
* @return result of the creation operation.
*/
- int16_t initialize();
+ int16_t initialize(){
+ return initialize(true);
+ }
+
+ int16_t initialize(bool blocking);
/**
* Attempt to select the socket file descriptor
@@ -159,6 +156,10 @@ class TLSSocket : public Socket {
virtual int readData(std::vector<uint8_t> &buf, int buflen);
+ virtual int readData(uint8_t *buf, int buflen, bool retrieve_all_bytes);
+
+ virtual int readData(std::vector<uint8_t> &buf, int buflen, bool retrieve_all_bytes);
+
/**
* Reads data and places it into buf
* @param buf buffer in which we extract data
@@ -183,8 +184,25 @@ class TLSSocket : public Socket {
int writeData(uint8_t *value, int size);
protected:
+
+ int writeData(uint8_t *value, int size, int fd);
+
+ SSL *get_ssl(int fd) {
+ if (UNLIKELY(listeners_ > 0)) {
+ std::lock_guard<std::mutex> lock(ssl_mutex_);
+ return ssl_map_[fd];
+ }
+ else{
+ return ssl_;
+ }
+ }
+
+ void close_ssl(int fd);
+ std::atomic<bool> connected_;
std::shared_ptr<TLSContext> context_;
- SSL* ssl;
+ SSL* ssl_;
+ std::mutex ssl_mutex_;
+ std::map<int, SSL*> ssl_map_;
private:
std::shared_ptr<logging::Logger> logger_;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/processors/GetTCP.h
----------------------------------------------------------------------
diff --git a/libminifi/include/processors/GetTCP.h b/libminifi/include/processors/GetTCP.h
index 7b5436f..4d331a1 100644
--- a/libminifi/include/processors/GetTCP.h
+++ b/libminifi/include/processors/GetTCP.h
@@ -28,6 +28,7 @@
#include "utils/ThreadPool.h"
#include "core/logging/LoggerConfiguration.h"
#include "core/state/metrics/MetricsBase.h"
+#include "controllers/SSLContextService.h"
namespace org {
namespace apache {
@@ -185,6 +186,7 @@ class GetTCP : public core::Processor, public state::metrics::MetricsSource {
reconnect_interval_(5000),
receive_buffer_size_(16 * 1024 * 1024),
connection_attempt_limit_(3),
+ ssl_service_(nullptr),
logger_(logging::LoggerFactory<GetTCP>::getLogger()) {
metrics_ = std::make_shared<GetTCPMetrics>();
}
@@ -200,6 +202,7 @@ class GetTCP : public core::Processor, public state::metrics::MetricsSource {
static core::Property ReconnectInterval;
static core::Property StayConnected;
static core::Property ReceiveBufferSize;
+ static core::Property SSLContextService;
static core::Property ConnectionAttemptLimit;
static core::Property EndOfMessageByte;
@@ -273,8 +276,10 @@ class GetTCP : public core::Processor, public state::metrics::MetricsSource {
std::mutex mutex_;
-// last listing time for root directory ( if recursive, we will consider the root
-// as the top level time.
+ std::shared_ptr<minifi::controllers::SSLContextService> ssl_service_;
+
+ // last listing time for root directory ( if recursive, we will consider the root
+ // as the top level time.
std::shared_ptr<logging::Logger> logger_;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/include/sitetosite/SiteToSiteFactory.h
----------------------------------------------------------------------
diff --git a/libminifi/include/sitetosite/SiteToSiteFactory.h b/libminifi/include/sitetosite/SiteToSiteFactory.h
index 96865b0..9a48b93 100644
--- a/libminifi/include/sitetosite/SiteToSiteFactory.h
+++ b/libminifi/include/sitetosite/SiteToSiteFactory.h
@@ -36,10 +36,17 @@ namespace sitetosite {
* @returns SiteToSitePeer
*/
static std::unique_ptr<SiteToSitePeer> createStreamingPeer(const SiteToSiteClientConfiguration &client_configuration) {
- std::unique_ptr<org::apache::nifi::minifi::io::DataStream> str = std::unique_ptr<org::apache::nifi::minifi::io::DataStream>(
- client_configuration.getStreamFactory()->createSocket(client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort()));
+ std::unique_ptr<org::apache::nifi::minifi::io::DataStream> str = nullptr;
+ if (nullptr != client_configuration.getSecurityContext()) {
+ str = std::unique_ptr<org::apache::nifi::minifi::io::DataStream>(
+ client_configuration.getStreamFactory()->createSecureSocket(client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort(), client_configuration.getSecurityContext()));
+ } else {
+ str = std::unique_ptr<org::apache::nifi::minifi::io::DataStream>(
+ client_configuration.getStreamFactory()->createSocket(client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort()));
+ }
auto peer = std::unique_ptr<SiteToSitePeer>(new SiteToSitePeer(std::move(str), client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort()));
return peer;
+
}
/**
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/src/c2/ControllerSocketProtocol.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/c2/ControllerSocketProtocol.cpp b/libminifi/src/c2/ControllerSocketProtocol.cpp
index 22e8696..a60cece 100644
--- a/libminifi/src/c2/ControllerSocketProtocol.cpp
+++ b/libminifi/src/c2/ControllerSocketProtocol.cpp
@@ -51,7 +51,7 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
if ((host == "localhost" || host == "127.0.0.1" || host == "::") && !anyInterface) {
server_socket_->initialize(true);
} else {
- server_socket_->initialize(true);
+ server_socket_->initialize(false);
}
auto check = [this]() -> bool {
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/src/io/ClientSocket.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/ClientSocket.cpp b/libminifi/src/io/ClientSocket.cpp
index d98c4ed..a382cda 100644
--- a/libminifi/src/io/ClientSocket.cpp
+++ b/libminifi/src/io/ClientSocket.cpp
@@ -48,6 +48,7 @@ Socket::Socket(const std::shared_ptr<SocketContext> &context, const std::string
is_loopback_only_(false),
listeners_(listeners),
canonical_hostname_(""),
+ nonBlocking_(false),
logger_(logging::LoggerFactory<Socket>::getLogger()) {
FD_ZERO(&total_list_);
FD_ZERO(&read_fds_);
@@ -68,6 +69,7 @@ Socket::Socket(const Socket &&other)
total_list_(other.total_list_),
read_fds_(other.read_fds_),
canonical_hostname_(std::move(other.canonical_hostname_)),
+ nonBlocking_(false),
logger_(std::move(other.logger_)) {
}
@@ -89,13 +91,7 @@ void Socket::closeStream() {
void Socket::setNonBlocking() {
if (listeners_ <= 0) {
- // Put the socket in non-blocking mode:
- if (fcntl(socket_file_descriptor_, F_SETFL, O_NONBLOCK) < 0) {
- // handle error
- logger_->log_error("Could not create non blocking to socket", strerror(errno));
- } else {
- logger_->log_debug("Successfully applied O_NONBLOCK to fd");
- }
+ nonBlocking_ = true;
}
}
@@ -117,7 +113,7 @@ int8_t Socket::createConnection(const addrinfo *p, in_addr_t &addr) {
sa_loc->sin_addr.s_addr = htonl(INADDR_ANY);
}
if (bind(socket_file_descriptor_, p->ai_addr, p->ai_addrlen) == -1) {
- logger_->log_error("Could not bind to socket", strerror(errno));
+ logger_->log_error("Could not bind to socket, reason %s", strerror(errno));
return -1;
}
}
@@ -205,6 +201,15 @@ int16_t Socket::initialize() {
}
// we've successfully connected
if (port_ > 0 && createConnection(p, addr) >= 0) {
+ // Put the socket in non-blocking mode:
+ if (nonBlocking_) {
+ if (fcntl(socket_file_descriptor_, F_SETFL, O_NONBLOCK) < 0) {
+ // handle error
+ logger_->log_error("Could not create non blocking to socket", strerror(errno));
+ } else {
+ logger_->log_debug("Successfully applied O_NONBLOCK to fd");
+ }
+ }
logger_->log_debug("Successfully created connection");
return 0;
break;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/src/io/StreamFactory.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/StreamFactory.cpp b/libminifi/src/io/StreamFactory.cpp
index 7990edd..a66e4c1 100644
--- a/libminifi/src/io/StreamFactory.cpp
+++ b/libminifi/src/io/StreamFactory.cpp
@@ -54,8 +54,9 @@ class SocketCreator : public AbstractStreamFactory {
return std::make_shared<SocketContext>(configure);
}
- SocketCreator<T, V>(std::shared_ptr<Configure> configure) {
- context_ = create(configure);
+ SocketCreator<T, V>(const std::shared_ptr<Configure> &configuration)
+ : configuration_(configuration) {
+ context_ = create(configuration);
}
template<typename U = T>
@@ -72,8 +73,23 @@ class SocketCreator : public AbstractStreamFactory {
return std::unique_ptr<Socket>(socket);
}
+ std::unique_ptr<Socket> createSecureSocket(const std::string &host, const uint16_t port, const std::shared_ptr<minifi::controllers::SSLContextService> &ssl_service) {
+#ifdef OPENSSL_SUPPORT
+ if (ssl_service != nullptr) {
+ auto ptr = std::make_shared<TLSContext>(configuration_, ssl_service);
+ TLSSocket *socket = new TLSSocket(ptr, host, port);
+ return std::unique_ptr<Socket>(socket);
+ } else {
+ return nullptr;
+ }
+#else
+ return nullptr;
+#endif
+ }
+
private:
std::shared_ptr<V> context_;
+ std::shared_ptr<Configure> configuration_;
};
// std::atomic<StreamFactory*> StreamFactory::context_instance_;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/src/io/tls/TLSServerSocket.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/tls/TLSServerSocket.cpp b/libminifi/src/io/tls/TLSServerSocket.cpp
new file mode 100644
index 0000000..582d0e9
--- /dev/null
+++ b/libminifi/src/io/tls/TLSServerSocket.cpp
@@ -0,0 +1,114 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "io/tls/TLSServerSocket.h"
+#include <netinet/tcp.h>
+#include <sys/types.h>
+#include <netdb.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <cstdio>
+#include <memory>
+#include <chrono>
+#include <thread>
+#include <utility>
+#include <vector>
+#include <cerrno>
+#include <iostream>
+#include <algorithm>
+#include <string>
+#include "io/validation.h"
+#include "core/logging/LoggerConfiguration.h"
+
+namespace org {
+namespace apache {
+namespace nifi {
+namespace minifi {
+namespace io {
+
+TLSServerSocket::TLSServerSocket(const std::shared_ptr<TLSContext> &context, const std::string &hostname, const uint16_t port, const uint16_t listeners = -1)
+ : TLSSocket(context, hostname, port, listeners),
+ running_(true),
+ logger_(logging::LoggerFactory<TLSServerSocket>::getLogger()) {
+}
+
+TLSServerSocket::~TLSServerSocket() {
+ running_ = false;
+ if (server_read_thread_.joinable())
+ server_read_thread_.join();
+}
+
+/**
+ * Initializes the socket
+ * @return result of the creation operation.
+ */
+void TLSServerSocket::registerCallback(std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*, int *)> handler) {
+ fx = [this](std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*, int *)> handler) {
+ int ret = 0;
+ std::vector<int> fds;
+ int size;
+ while (accept_function()) {
+ int fd = select_descriptor(3000);
+ if (fd > 0) {
+ int fd_remove = 0;
+ std::vector<uint8_t> data;
+ if ( handler(&data, &size) > 0 ) {
+ ret = writeData(data.data(), size, fd);
+ if (ret < 0) {
+ close_ssl(fd_remove);
+ } else {
+ fds.push_back(fd);
+ }
+ }
+ } else {
+ int fd_remove = 0;
+ for (auto &&fd : fds) {
+ std::vector<uint8_t> data;
+ if ( handler(&data, &size) > 0 ) {
+ ret = writeData(data.data(), size, fd);
+ if (ret < 0) {
+ fd_remove = fd;
+ break;
+ }
+ }
+ }
+ if (fd_remove > 0) {
+ close_ssl(fd_remove);
+ fds.erase(std::remove(fds.begin(), fds.end(), fd_remove), fds.end());
+ }
+ }
+ }
+ for (auto &&fd : fds) {
+ close_ssl(fd);
+ }
+ };
+ server_read_thread_ = std::thread(fx, accept_function, handler);
+}
+
+void TLSServerSocket::close_fd(int fd) {
+ std::lock_guard<std::recursive_mutex> guard(selection_mutex_);
+ close(fd);
+ FD_CLR(fd, &total_list_);
+}
+
+} /* namespace io */
+} /* namespace minifi */
+} /* namespace nifi */
+} /* namespace apache */
+} /* namespace org */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/src/io/tls/TLSSocket.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/tls/TLSSocket.cpp b/libminifi/src/io/tls/TLSSocket.cpp
index a38ce0e..ef5958c 100644
--- a/libminifi/src/io/tls/TLSSocket.cpp
+++ b/libminifi/src/io/tls/TLSSocket.cpp
@@ -36,21 +36,25 @@ namespace io {
std::atomic<OpenSSLInitializer*> OpenSSLInitializer::context_instance;
std::mutex OpenSSLInitializer::context_mutex;
-TLSContext::TLSContext(const std::shared_ptr<Configure> &configure)
+TLSContext::TLSContext(const std::shared_ptr<Configure> &configure, const std::shared_ptr<minifi::controllers::SSLContextService> &ssl_service)
: SocketContext(configure),
error_value(0),
ctx(0),
logger_(logging::LoggerFactory<TLSContext>::getLogger()),
- configure_(configure) {
+ configure_(configure),
+ ssl_service_(ssl_service) {
}
+
/**
* The memory barrier is defined by the singleton
*/
-int16_t TLSContext::initialize() {
+int16_t TLSContext::initialize(bool server_method) {
if (ctx != 0) {
return error_value;
}
+ logger_->log_debug("initializing %X", this);
+
if (nullptr == OpenSSLInitializer::getInstance()) {
return error_value;
}
@@ -60,9 +64,8 @@ int16_t TLSContext::initialize() {
if (!(configure_->get(Configure::nifi_security_need_ClientAuth, clientAuthStr) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(clientAuthStr, needClientCert))) {
needClientCert = true;
}
-
const SSL_METHOD *method;
- method = TLSv1_2_client_method();
+ method = server_method ? TLSv1_2_server_method() : TLSv1_2_client_method();
ctx = SSL_CTX_new(method);
if (ctx == NULL) {
logger_->log_error("Could not create SSL context, error: %s.", std::strerror(errno));
@@ -75,21 +78,42 @@ int16_t TLSContext::initialize() {
std::string passphrase;
std::string caCertificate;
- if (!(configure_->get(Configure::nifi_security_client_certificate, certificate) && configure_->get(Configure::nifi_security_client_private_key, privatekey))) {
- logger_->log_error("Certificate and Private Key PEM file not configured, error: %s.", std::strerror(errno));
- error_value = TLS_ERROR_PEM_MISSING;
- return error_value;
+ if (ssl_service_ != nullptr) {
+ certificate = ssl_service_->getCertificateFile();
+ privatekey = ssl_service_->getPrivateKeyFile();
+ caCertificate = ssl_service_->getCACertificate();
+ passphrase = ssl_service_->getPassphrase();
+ } else {
+ if (!(configure_->get(Configure::nifi_security_client_certificate, certificate) && configure_->get(Configure::nifi_security_client_private_key, privatekey))) {
+ logger_->log_error("Certificate and Private Key PEM file not configured, error: %s.", std::strerror(errno));
+ error_value = TLS_ERROR_PEM_MISSING;
+ return error_value;
+ }
}
// load certificates and private key in PEM format
if (SSL_CTX_use_certificate_file(ctx, certificate.c_str(), SSL_FILETYPE_PEM) <= 0) {
- logger_->log_error("Could not create load certificate, error : %s", std::strerror(errno));
+ logger_->log_error("Could not load certificate %s, for %X and %X error : %s", certificate, this, ctx, std::strerror(errno));
error_value = TLS_ERROR_CERT_MISSING;
return error_value;
}
- if (configure_->get(Configure::nifi_security_client_pass_phrase, passphrase)) {
+ if (ssl_service_ != nullptr) {
// if the private key has passphase
SSL_CTX_set_default_passwd_cb(ctx, pemPassWordCb);
- SSL_CTX_set_default_passwd_cb_userdata(ctx, static_cast<void*>(configure_.get()));
+ SSL_CTX_set_default_passwd_cb_userdata(ctx, static_cast<void*>(const_cast<char*>(passphrase.c_str())));
+ } else {
+ if (configure_->get(Configure::nifi_security_client_pass_phrase, passphrase)) {
+ std::ifstream file(passphrase.c_str(), std::ifstream::in);
+ if (!file.good()) {
+ return error_value;
+ }
+
+ std::string password;
+ password.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
+ file.close();
+ passphrase = password;
+ SSL_CTX_set_default_passwd_cb(ctx, pemPassWordCb);
+ SSL_CTX_set_default_passwd_cb_userdata(ctx, static_cast<void*>(const_cast<char*>(passphrase.c_str())));
+ }
}
int retp = SSL_CTX_use_PrivateKey_file(ctx, privatekey.c_str(), SSL_FILETYPE_PEM);
@@ -105,7 +129,7 @@ int16_t TLSContext::initialize() {
return error_value;
}
// load CA certificates
- if (configure_->get(Configure::nifi_security_client_ca_certificate, caCertificate)) {
+ if (ssl_service_ != nullptr || configure_->get(Configure::nifi_security_client_ca_certificate, caCertificate)) {
retp = SSL_CTX_load_verify_locations(ctx, caCertificate.c_str(), 0);
if (retp == 0) {
logger_->log_error("Can not load CA certificate, Exiting, error : %s", std::strerror(errno));
@@ -114,14 +138,17 @@ int16_t TLSContext::initialize() {
}
}
- logger_->log_debug("Load/Verify Client Certificate OK.");
+ logger_->log_debug("Load/Verify Client Certificate OK. for %X and %X", this, ctx);
}
return 0;
}
TLSSocket::~TLSSocket() {
- if (ssl != 0)
- SSL_free(ssl);
+ if (ssl_ != 0) {
+ SSL_free(ssl_);
+ ssl_ = nullptr;
+ }
+ closeStream();
}
/**
* Constructor that accepts host name, port and listeners. With this
@@ -132,76 +159,231 @@ TLSSocket::~TLSSocket() {
*/
TLSSocket::TLSSocket(const std::shared_ptr<TLSContext> &context, const std::string &hostname, const uint16_t port, const uint16_t listeners)
: Socket(context, hostname, port, listeners),
- ssl(0),
+ ssl_(0),
logger_(logging::LoggerFactory<TLSSocket>::getLogger()) {
context_ = context;
}
TLSSocket::TLSSocket(const std::shared_ptr<TLSContext> &context, const std::string &hostname, const uint16_t port)
: Socket(context, hostname, port, 0),
- ssl(0),
+ ssl_(0),
logger_(logging::LoggerFactory<TLSSocket>::getLogger()) {
context_ = context;
}
TLSSocket::TLSSocket(const TLSSocket &&d)
: Socket(std::move(d)),
- ssl(0),
+ ssl_(0),
logger_(std::move(d.logger_)) {
context_ = d.context_;
}
-int16_t TLSSocket::initialize() {
- int16_t ret = context_->initialize();
+int16_t TLSSocket::initialize(bool blocking) {
+ bool is_server = false;
+ if (listeners_ > 0)
+ is_server = true;
+
+ if (!blocking)
+ setNonBlocking();
+ logger_->log_trace("Initializing TLSSocket %d", is_server);
+ int16_t ret = context_->initialize(is_server);
Socket::initialize();
- if (!ret) {
+
+ if (!ret && listeners_ == 0) {
// we have s2s secure config
- ssl = SSL_new(context_->getContext());
- SSL_set_fd(ssl, socket_file_descriptor_);
- if (SSL_connect(ssl) == -1) {
+ ssl_ = SSL_new(context_->getContext());
+ SSL_set_fd(ssl_, socket_file_descriptor_);
+ connected_ = false;
+ int rez = SSL_connect(ssl_);
+ if (rez < 0) {
+ ERR_print_errors_fp(stderr);
+ int ssl_error = SSL_get_error(ssl_, rez);
+ if (ssl_error == SSL_ERROR_WANT_WRITE) {
+ logger_->log_trace("want read");
+ return 0;
+ } else if (ssl_error == SSL_ERROR_WANT_READ) {
+ logger_->log_trace("want read");
+ return 0;
+ } else {
+ return -1;
+ }
logger_->log_error("SSL socket connect failed to %s %d", requested_hostname_, port_);
- SSL_free(ssl);
- ssl = NULL;
+ SSL_free(ssl_);
+ ssl_ = NULL;
close(socket_file_descriptor_);
return -1;
} else {
- logger_->log_debug("SSL socket connect success to %s %d", requested_hostname_, port_);
+ connected_ = true;
+ logger_->log_debug("SSL socket connect success to %s %d, on fd %d", requested_hostname_, port_, socket_file_descriptor_);
return 0;
}
}
+
return ret;
}
+void TLSSocket::close_ssl(int fd) {
+ FD_CLR(fd, &total_list_); // add to master set
+ if (UNLIKELY(listeners_ > 0)) {
+ std::lock_guard<std::mutex> lock(ssl_mutex_);
+ auto fd_ssl = ssl_map_[fd];
+ if (nullptr != fd_ssl) {
+ SSL_free(fd_ssl);
+ ssl_map_[fd] = nullptr;
+ close(fd);
+ }
+ }
+}
+
int16_t TLSSocket::select_descriptor(const uint16_t msec) {
- if (ssl && SSL_pending(ssl))
- return 1;
- return Socket::select_descriptor(msec);
+// if (ssl && SSL_pending(ssl))
+ // return 1;
+ if (listeners_ == 0 && connected_) {
+ return socket_file_descriptor_;
+ }
+
+ struct timeval tv;
+
+ read_fds_ = total_list_;
+
+ tv.tv_sec = msec / 1000;
+ tv.tv_usec = (msec % 1000) * 1000;
+
+ std::lock_guard<std::recursive_mutex> guard(selection_mutex_);
+
+ if (msec > 0)
+ select(socket_max_ + 1, &read_fds_, NULL, NULL, &tv);
+ else
+ select(socket_max_ + 1, &read_fds_, NULL, NULL, NULL);
+
+ for (int i = 0; i <= socket_max_; i++) {
+ if (FD_ISSET(i, &read_fds_)) {
+ if (i == socket_file_descriptor_) {
+ if (listeners_ > 0) {
+ struct sockaddr_in remoteaddr; // client address
+ socklen_t addrlen = sizeof remoteaddr;
+ int newfd = accept(socket_file_descriptor_, (struct sockaddr *) &remoteaddr, &addrlen);
+ FD_SET(newfd, &total_list_); // add to master set
+ if (newfd > socket_max_) { // keep track of the max
+ socket_max_ = newfd;
+ }
+ auto ssl = SSL_new(context_->getContext());
+ SSL_set_fd(ssl, newfd);
+ auto accept_value = SSL_accept(ssl);
+ if (accept_value != -1) {
+ ssl_map_[newfd] = ssl;
+ return newfd;
+ } else {
+ int ssl_err = SSL_get_error(ssl, accept_value);
+ logger_->log_error("Could not accept %d, error code %d", newfd, ssl_err);
+ close_ssl(newfd);
+ return -1;
+ }
+ } else {
+ if (!connected_) {
+ int rez = SSL_connect(ssl_);
+
+ if (rez < 0) {
+ ERR_print_errors_fp(stderr);
+ int ssl_error = SSL_get_error(ssl_, rez);
+ if (ssl_error == SSL_ERROR_WANT_WRITE) {
+ logger_->log_trace("want write");
+ return socket_file_descriptor_;
+ } else if (ssl_error == SSL_ERROR_WANT_READ) {
+ logger_->log_trace("want read");
+ return socket_file_descriptor_;
+ } else {
+ return -1;
+ }
+ logger_->log_error("SSL socket connect failed to %s %d", requested_hostname_, port_);
+ SSL_free(ssl_);
+ ssl_ = NULL;
+ close(socket_file_descriptor_);
+ return -1;
+ } else {
+ connected_ = true;
+ logger_->log_debug("SSL socket connect success to %s %d, on fd %d", requested_hostname_, port_, socket_file_descriptor_);
+ return socket_file_descriptor_;
+ }
+ }
+ }
+ return socket_file_descriptor_;
+ // we have a new connection
+ } else {
+ // data to be received on i
+ return i;
+ }
+ }
+ }
+
+ bool is_server = listeners_ > 0;
+
+ if (listeners_ == 0) {
+ return socket_file_descriptor_;
+ }
+
+ logger_->log_trace("%s Could not find a suitable file descriptor or select timed out", is_server ? "Server:" : "Client:");
+
+ return -1;
}
int TLSSocket::writeData(std::vector<uint8_t>& buf, int buflen) {
- return Socket::writeData(buf, buflen);
+ int16_t fd = select_descriptor(1000);
+ return writeData(buf.data(), buflen, fd);
+}
+
+int TLSSocket::readData(std::vector<uint8_t> &buf, int buflen, bool retrieve_all_bytes) {
+ if (static_cast<int>(buf.capacity()) < buflen) {
+ buf.resize(buflen);
+ }
+ return readData(reinterpret_cast<uint8_t*>(&buf[0]), buflen, retrieve_all_bytes);
+}
+
+int TLSSocket::readData(uint8_t *buf, int buflen, bool retrieve_all_bytes) {
+ int total_read = 0;
+ int status = 0;
+ int loc = 0;
+ int16_t fd = select_descriptor(1000);
+ auto fd_ssl = get_ssl(fd);
+ if (!SSL_pending(fd_ssl)) {
+ return 0;
+ }
+ while (buflen) {
+ if (fd <= 0) {
+ return -1;
+ }
+ int sslStatus;
+ do {
+ status = SSL_read(fd_ssl, buf + loc, buflen);
+ sslStatus = SSL_get_error(fd_ssl, status);
+ } while (status < 0 && sslStatus == SSL_ERROR_WANT_READ && SSL_pending(fd_ssl));
+
+ buflen -= status;
+ loc += status;
+ total_read += status;
+ }
+
+ return total_read;
}
int TLSSocket::readData(std::vector<uint8_t> &buf, int buflen) {
if (buf.capacity() < buflen) {
buf.reserve(buflen);
}
- if (IsNullOrEmpty(ssl))
- return -1;
int total_read = 0;
int status = 0;
int loc = 0;
while (buflen) {
int16_t fd = select_descriptor(1000);
if (fd <= 0) {
- close(socket_file_descriptor_);
return -1;
}
+ auto fd_ssl = get_ssl(fd);
int sslStatus;
do {
- status = SSL_read(ssl, buf.data() + loc, buflen);
- sslStatus = SSL_get_error(ssl, status);
+ status = SSL_read(fd_ssl, buf.data() + loc, buflen);
+ sslStatus = SSL_get_error(fd_ssl, status);
} while (status < 0 && sslStatus == SSL_ERROR_WANT_READ);
buflen -= status;
@@ -212,17 +394,43 @@ int TLSSocket::readData(std::vector<uint8_t> &buf, int buflen) {
return total_read;
}
-int TLSSocket::writeData(uint8_t *value, int size) {
- if (IsNullOrEmpty(ssl))
+int TLSSocket::writeData(uint8_t *value, int size, int fd) {
+ int bytes = 0;
+ int sent = 0;
+ auto fd_ssl = get_ssl(fd);
+ if (IsNullOrEmpty(fd_ssl)) {
return -1;
- // for SSL, wait for the TLS IO is completed
+ }
+ while (bytes < size) {
+ sent = SSL_write(fd_ssl, value + bytes, size - bytes);
+ // check for errors
+ if (sent < 0) {
+ int ret = 0;
+ ret = SSL_get_error(fd_ssl, sent);
+ logger_->log_trace("WriteData socket %d send failed %s %d", fd, strerror(errno), ret);
+
+ return sent;
+ }
+ logger_->log_trace("WriteData socket %d send succeed %d", fd, sent);
+ bytes += sent;
+ }
+ return size;
+}
+
+int TLSSocket::writeData(uint8_t *value, int size) {
int bytes = 0;
int sent = 0;
+ int fd = select_descriptor(1000);
+ auto fd_ssl = get_ssl(fd);
+ if (IsNullOrEmpty(fd_ssl))
+ return -1;
while (bytes < size) {
- sent = SSL_write(ssl, value + bytes, size - bytes);
+ sent = SSL_write(fd_ssl, value + bytes, size - bytes);
// check for errors
if (sent < 0) {
- logger_->log_error("Site2Site Peer socket %d send failed %s", socket_file_descriptor_, strerror(errno));
+ int ret = 0;
+ ret = SSL_get_error(fd_ssl, sent);
+ logger_->log_error("WriteData socket %d send failed %s %d", fd, strerror(errno), ret);
return sent;
}
bytes += sent;
@@ -231,8 +439,8 @@ int TLSSocket::writeData(uint8_t *value, int size) {
}
int TLSSocket::readData(uint8_t *buf, int buflen) {
- if (IsNullOrEmpty(ssl))
- return -1;
+ // if (IsNullOrEmpty(ssl))
+// return -1;
int total_read = 0;
int status = 0;
while (buflen) {
@@ -244,8 +452,11 @@ int TLSSocket::readData(uint8_t *buf, int buflen) {
int sslStatus;
do {
- status = SSL_read(ssl, buf, buflen);
- sslStatus = SSL_get_error(ssl, status);
+ auto fd_ssl = get_ssl(fd);
+ if (IsNullOrEmpty(fd_ssl))
+ return -1;
+ status = SSL_read(fd_ssl, buf, buflen);
+ sslStatus = SSL_get_error(fd_ssl, status);
} while (status < 0 && sslStatus == SSL_ERROR_WANT_READ);
buflen -= status;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/src/processors/GetTCP.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/processors/GetTCP.cpp b/libminifi/src/processors/GetTCP.cpp
index 3bf15b2..79fe733 100644
--- a/libminifi/src/processors/GetTCP.cpp
+++ b/libminifi/src/processors/GetTCP.cpp
@@ -52,6 +52,7 @@ core::Property GetTCP::EndpointList("endpoint-list", "A comma delimited list of
core::Property GetTCP::ConcurrentHandlers("concurrent-handler-count", "Number of concurrent handlers for this session", "1");
core::Property GetTCP::ReconnectInterval("reconnect-interval", "The number of seconds to wait before attempting to reconnect to the endpoint.", "5s");
core::Property GetTCP::ReceiveBufferSize("receive-buffer-size", "The size of the buffer to receive data in. Default 16384 (16MB).", "16MB");
+core::Property GetTCP::SSLContextService("SSL Context Service", "SSL Context Service Name", "");
core::Property GetTCP::StayConnected("Stay Connected", "Determines if we keep the same socket despite having no data", "true");
core::Property GetTCP::ConnectionAttemptLimit("connection-attempt-timeout", "Maximum number of connection attempts before attempting backup hosts, if configured.", "3");
core::Property GetTCP::EndOfMessageByte(
@@ -90,6 +91,7 @@ void GetTCP::initialize() {
properties.insert(EndOfMessageByte);
properties.insert(ReceiveBufferSize);
properties.insert(StayConnected);
+ properties.insert(SSLContextService);
setSupportedProperties(properties);
// Set the supported relationships
std::set<core::Relationship> relationships;
@@ -154,7 +156,6 @@ void GetTCP::onSchedule(const std::shared_ptr<core::ProcessContext> &context, co
do {
if ( socket_ring_buffer_.try_dequeue(socket_ptr) ) {
int size_read = socket_ptr->readData(buffer, receive_buffer_size_, false);
-
if (size_read >= 0) {
if (size_read > 0) {
// determine cut location
@@ -206,6 +207,13 @@ void GetTCP::onSchedule(const std::shared_ptr<core::ProcessContext> &context, co
return 0;
};
+ if (context->getProperty(SSLContextService.getName(), value)) {
+ std::shared_ptr<core::controller::ControllerService> service = context->getControllerService(value);
+ if (nullptr != service) {
+ ssl_service_ = std::static_pointer_cast<minifi::controllers::SSLContextService>(service);
+ }
+ }
+
utils::ThreadPool<int> pool = utils::ThreadPool<int>(concurrent_handlers_);
client_thread_pool_ = std::move(pool);
client_thread_pool_.start();
@@ -230,29 +238,27 @@ void GetTCP::onTrigger(const std::shared_ptr<core::ProcessContext> &context, con
for (auto &endpoint : endpoints) {
auto endPointFuture = live_clients_.find(endpoint);
-
// does not exist
if (endPointFuture == live_clients_.end()) {
logger_->log_info("creating endpoint for %s", endpoint);
std::vector<std::string> hostAndPort = utils::StringUtils::split(endpoint, ":");
if (hostAndPort.size() == 2) {
- logger_->log_debug("Opening another socket to %s:%s", hostAndPort.at(0), hostAndPort.at(1));
- std::unique_ptr<io::Socket> socket = stream_factory_->createSocket(hostAndPort.at(0), std::stoi(hostAndPort.at(1)));
-
+ logger_->log_debug("Opening another socket to %s:%s is secure %d", hostAndPort.at(0), hostAndPort.at(1), (ssl_service_ != nullptr));
+ std::unique_ptr<io::Socket> socket =
+ ssl_service_ != nullptr ?
+ stream_factory_->createSecureSocket(hostAndPort.at(0), std::stoi(hostAndPort.at(1)), ssl_service_) : stream_factory_->createSocket(hostAndPort.at(0), std::stoi(hostAndPort.at(1)));
+ socket->setNonBlocking();
if (socket->initialize() != -1) {
- socket->setNonBlocking();
logger_->log_debug("Enqueueing socket into ring buffer %s:%s", hostAndPort.at(0), hostAndPort.at(1));
socket_ring_buffer_.enqueue(std::move(socket));
-
} else {
logger_->log_error("Could not create socket during initialization for %s", endpoint);
+ continue;
}
} else {
logger_->log_error("Could not create socket for %s", endpoint);
}
-
std::future<int> *future = new std::future<int>();
-
std::unique_ptr<utils::AfterExecute<int>> after_execute = std::unique_ptr<utils::AfterExecute<int>>(new SocketAfterExecute(running_, endpoint, &live_clients_, &mutex_));
utils::Worker<int> functor(f_ex, "workers", std::move(after_execute));
if (client_thread_pool_.execute(std::move(functor), *future)) {
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/integration/IntegrationBase.h
----------------------------------------------------------------------
diff --git a/libminifi/test/integration/IntegrationBase.h b/libminifi/test/integration/IntegrationBase.h
index 8446993..887b1a9 100644
--- a/libminifi/test/integration/IntegrationBase.h
+++ b/libminifi/test/integration/IntegrationBase.h
@@ -23,7 +23,7 @@
#include "core/yaml/YamlConfiguration.h"
#include "FlowController.h"
#include "properties/Configure.h"
-#include "unit/ProvenanceTestHelper.h"
+#include "../unit/ProvenanceTestHelper.h"
#include "io/StreamFactory.h"
#include "RemoteProcessorGroupPort.h"
#include "core/ConfigurableComponent.h"
@@ -136,4 +136,4 @@ void IntegrationBase::run(std::string test_file_location) {
cleanup();
}
-#endif /* LIBMINIFI_TEST_INTEGRATION_INTEGRATIONBASE_H_ */
\ No newline at end of file
+#endif /* LIBMINIFI_TEST_INTEGRATION_INTEGRATIONBASE_H_ */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/integration/SecureSocketGetTCPTest.cpp
----------------------------------------------------------------------
diff --git a/libminifi/test/integration/SecureSocketGetTCPTest.cpp b/libminifi/test/integration/SecureSocketGetTCPTest.cpp
new file mode 100644
index 0000000..412ea71
--- /dev/null
+++ b/libminifi/test/integration/SecureSocketGetTCPTest.cpp
@@ -0,0 +1,198 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <sys/stat.h>
+#undef NDEBUG
+#include <cassert>
+#include <utility>
+#include <chrono>
+#include <fstream>
+#include <memory>
+#include <string>
+#include <thread>
+#include <type_traits>
+#include <vector>
+#include <iostream>
+#include <sstream>
+#include "HTTPClient.h"
+#include "processors/GetTCP.h"
+#include "../TestBase.h"
+#include "utils/StringUtils.h"
+#include "core/Core.h"
+#include "core/logging/Logger.h"
+#include "core/ProcessGroup.h"
+#include "core/yaml/YamlConfiguration.h"
+#include "FlowController.h"
+#include "properties/Configure.h"
+#include "../unit/ProvenanceTestHelper.h"
+#include "io/StreamFactory.h"
+#include "RemoteProcessorGroupPort.h"
+#include "core/ConfigurableComponent.h"
+#include "controllers/SSLContextService.h"
+#include "c2/C2Agent.h"
+#include "IntegrationBase.h"
+#include "processors/LogAttribute.h"
+#include "io/tls/TLSSocket.h"
+#include "io/tls/TLSServerSocket.h"
+
+class SecureSocketTest : public IntegrationBase {
+ public:
+ explicit SecureSocketTest(bool isSecure)
+ : isSecure(isSecure) {
+ char format[] = "/tmp/ssth.XXXXXX";
+ dir = testController.createTempDirectory(format);
+ }
+
+ void testSetup() {
+ LogTestController::getInstance().setDebug<minifi::io::Socket>();
+ LogTestController::getInstance().setDebug<minifi::io::TLSContext>();
+ LogTestController::getInstance().setDebug<core::ProcessSession>();
+ LogTestController::getInstance().setTrace<minifi::io::TLSSocket>();
+ LogTestController::getInstance().setTrace<processors::GetTCP>();
+ std::fstream file;
+ ss << dir << "/" << "tstFile.ext";
+ file.open(ss.str(), std::ios::out);
+ file << "tempFile";
+ file.close();
+ }
+
+ void cleanup() {
+ LogTestController::getInstance().reset();
+ unlink(ss.str().c_str());
+ }
+
+ void runAssertions() {
+ assert(LogTestController::getInstance().contains("send succeed 20") == true);
+ }
+
+ void queryRootProcessGroup(std::shared_ptr<core::ProcessGroup> pg) {
+ std::shared_ptr<core::Processor> proc = pg->findProcessor("invoke");
+ assert(proc != nullptr);
+
+ std::shared_ptr<minifi::processors::GetTCP> inv = std::dynamic_pointer_cast<minifi::processors::GetTCP>(proc);
+
+ assert(inv != nullptr);
+ std::string url = "";
+ configuration->set("nifi.remote.input.secure", "true");
+ configuration->set("nifi.security.client.disable.host.verification", "true");
+ configuration->set("nifi.security.client.disable.peer.verification", "true");
+ std::string path = key_dir + "cn.crt.pem";
+ configuration->set("nifi.security.client.certificate", path);
+ path = key_dir + "cn.ckey.pem";
+ configuration->set("nifi.security.client.private.key", path);
+ path = key_dir + "cn.pass";
+ configuration->set("nifi.security.client.pass.phrase", path);
+ path = key_dir + "nifi-cert.pem";
+ configuration->set("nifi.security.client.ca.certificate", path);
+ configuration->set("nifi.c2.enable", "false");
+ std::shared_ptr<org::apache::nifi::minifi::io::TLSContext> socket_context = std::make_shared<org::apache::nifi::minifi::io::TLSContext>(configuration);
+ server_socket = std::make_shared<org::apache::nifi::minifi::io::TLSServerSocket>(socket_context, "localhost", 8776, 3);
+ server_socket->initialize();
+
+ isRunning_ = true;
+ check = [this]() -> bool {
+ return isRunning_;
+ };
+ handler = [this](std::vector<uint8_t> *b, int *size) {
+ b->reserve(20);
+ memset(b->data(), 0x00, 20);
+ memcpy(b->data(), "hello world", 11);
+ *size = 20;
+ return *size;
+ };
+ server_socket->registerCallback(check, handler);
+ }
+
+ void run(std::string test_file_location) {
+ testSetup();
+
+ std::shared_ptr<core::Repository> test_repo = std::make_shared<TestRepository>();
+ std::shared_ptr<core::Repository> test_flow_repo = std::make_shared<TestFlowRepository>();
+
+ configuration->set(minifi::Configure::nifi_flow_configuration_file, test_file_location);
+
+ std::shared_ptr<core::ContentRepository> content_repo = std::make_shared<core::repository::VolatileContentRepository>();
+ content_repo->initialize(configuration);
+ std::shared_ptr<minifi::io::StreamFactory> stream_factory = std::make_shared<minifi::io::StreamFactory>(configuration);
+ std::unique_ptr<core::FlowConfiguration> yaml_ptr = std::unique_ptr<core::YamlConfiguration>(
+ new core::YamlConfiguration(test_repo, test_repo, content_repo, stream_factory, configuration, test_file_location));
+
+ core::YamlConfiguration yaml_config(test_repo, test_repo, content_repo, stream_factory, configuration, test_file_location);
+
+ std::unique_ptr<core::ProcessGroup> ptr = yaml_config.getRoot(test_file_location);
+ std::shared_ptr<core::ProcessGroup> pg = std::shared_ptr<core::ProcessGroup>(ptr.get());
+
+ queryRootProcessGroup(pg);
+
+ ptr.release();
+
+ std::shared_ptr<TestRepository> repo = std::static_pointer_cast<TestRepository>(test_repo);
+
+ std::shared_ptr<minifi::FlowController> controller = std::make_shared<minifi::FlowController>(test_repo, test_flow_repo, configuration, std::move(yaml_ptr), content_repo, DEFAULT_ROOT_GROUP_NAME,
+ true);
+ controller->load();
+ controller->start();
+ waitToVerifyProcessor();
+ controller->waitUnload(60000);
+ isRunning_ = false;
+ std::cout << "close?" << std::endl;
+ server_socket->closeStream();
+ server_socket = nullptr;
+ runAssertions();
+
+ cleanup();
+ }
+
+ virtual void waitToVerifyProcessor() {
+ std::this_thread::sleep_for(std::chrono::seconds(3));
+ }
+
+ protected:
+ std::function<bool()> check;
+ std::function<int(std::vector<uint8_t>*b, int *size)> handler;
+ std::atomic<bool> isRunning_;
+ bool isSecure;
+ char *dir;
+ std::stringstream ss;
+ TestController testController;
+ std::shared_ptr<org::apache::nifi::minifi::io::TLSServerSocket> server_socket;
+};
+
+static void sigpipe_handle(int x) {}
+
+int main(int argc, char **argv) {
+ std::string key_dir, test_file_location, url;
+ url = "http://localhost:8888/api/heartbeat";
+ if (argc > 1) {
+ test_file_location = argv[1];
+ key_dir = argv[2];
+ }
+ bool isSecure = false;
+ if (url.find("https") != std::string::npos) {
+ isSecure = true;
+ }
+
+ signal(SIGPIPE, sigpipe_handle);
+
+ SecureSocketTest harness(true);
+
+ harness.setKeyDir(key_dir);
+
+ harness.run(test_file_location);
+
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/resources/TestGetTCPSecure.yml
----------------------------------------------------------------------
diff --git a/libminifi/test/resources/TestGetTCPSecure.yml b/libminifi/test/resources/TestGetTCPSecure.yml
new file mode 100644
index 0000000..6138f1d
--- /dev/null
+++ b/libminifi/test/resources/TestGetTCPSecure.yml
@@ -0,0 +1,90 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+Flow Controller:
+ name: MiNiFi Flow
+ id: 2438e3c8-015a-1000-79ca-83af40ec1990
+Processors:
+ - name: invoke
+ id: 2438e3c8-015a-1000-79ca-83af40ec1991
+ class: org.apache.nifi.processors.standard.GetTCP
+ max concurrent tasks: 1
+ scheduling strategy: TIMER_DRIVEN
+ scheduling period: 10 msec
+ penalization period: 30 msec
+ yield period: 10 msec
+ run duration nanos: 0
+ auto-terminated relationships list:
+ Properties:
+ SSL Context Service: SSLContextService
+ endpoint-list: localhost:8776
+ end-of-message-byte: d
+ reconnect-interval: 5ms
+ connection-attempt-timeout: 2000
+ - name: LogAttribute
+ id: 2438e3c8-015a-1000-79ca-83af40ec1992
+ class: org.apache.nifi.processors.standard.LogAttribute
+ max concurrent tasks: 1
+ scheduling strategy: TIMER_DRIVEN
+ scheduling period: 1 sec
+ penalization period: 30 sec
+ yield period: 1 sec
+ run duration nanos: 0
+ auto-terminated relationships list: response
+ Properties:
+ Log Level: info
+ Log Payload: true
+
+Connections:
+ - name: TransferFilesToRPG
+ id: 2438e3c8-015a-1000-79ca-83af40ec1997
+ source name: invoke
+ source id: 2438e3c8-015a-1000-79ca-83af40ec1991
+ source relationship name: success
+ destination name: LogAttribute
+ destination id: 2438e3c8-015a-1000-79ca-83af40ec1992
+ max work queue size: 0
+ max work queue data size: 1 MB
+ flowfile expiration: 60 sec
+ - name: TransferFilesToRPG2
+ id: 2438e3c8-015a-1000-79ca-83af40ec1917
+ source name: LogAttribute
+ source id: 2438e3c8-015a-1000-79ca-83af40ec1992
+ destination name: LogAttribute
+ destination id: 2438e3c8-015a-1000-79ca-83af40ec1992
+ source relationship name: success
+ max work queue size: 0
+ max work queue data size: 1 MB
+ flowfile expiration: 60 sec
+
+Controller Services:
+ - name: SSLContextService
+ id: 2438e3c8-015a-1000-79ca-83af40ec1994
+ class: SSLContextService
+ Properties:
+ Client Certificate:
+ - value: cn.crt.pem
+ Private Key:
+ - value: cn.ckey.pem
+ Passphrase:
+ - value: cn.pass
+ CA Certificate:
+ - value: nifi-cert.pem
+
+Remote Processing Groups:
+
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/resources/nifi-key.pem
----------------------------------------------------------------------
diff --git a/libminifi/test/resources/nifi-key.pem b/libminifi/test/resources/nifi-key.pem
new file mode 100644
index 0000000..0fd6eb0
--- /dev/null
+++ b/libminifi/test/resources/nifi-key.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpAIBAAKCAQEAwCF6Tchue7tR66BPg886WOYNPgSwNaq1KJQSuGcEHK2wlAEu
+YfiYz9LbjFLZRLRY2CF9mIGb683byrnvOMcq6a+YdXDaOHZnkKBSsI/xTzScXTv3
+EKSueZ0sMuD7L0y/2Cs2lf8heBUEUqmNe15J9yvEQ1GpJ0j7iCCneKYjjezFWglR
+Sv/9suvqVCxIxr4j9gXODgyU3wdwIxkQUBJXk4GtDp03Rxcx6Ch0VBwjcGkYHhcs
+GHRzg6dcr795tLfOQNA/Vlje0+RtH/KU/WXgzl9nKtxD7XUwZyhoElzNcehN0WmK
+DgAmASncvy7+YYzKU69H14Q+2n/apdoqx/kTQQIDAQABAoIBAQCz7eY69+y4BXo3
+nz84Ipby8CcQoJVg/QiBAwLxHNCWBvdp9B069PQvFLo1FNWSaQ8XAW48p4yc7YHb
+vftRgfwnMyIlQdWrsP9WSz6FSZhkY9HX4rODK6aWD+J3l4jFCCxVxkpteKwgaBZP
+T6hHE8tTJfK8VLqEJu4g0uvjqjt7ydJT69lThdyf3VE0v6ZeSjsya5qqw+9RK+uC
+q5T/8FxeFZgpfR6UXXnoLAmAkfcMZNIBo6cOJWi/BQHjZdpCOVXUBtu0/lC8bffa
+4/ESaxRS8kOp+WEb64pT7u6F7yhD/kve6ZnJj/SX1EvN+RzB3zoVG42WUs/+/SwN
+dU1ERz+tAoGBAPbgZPDnWuKxW7Cam/Aqmvux624C1lNfhfXEGURhyc+wHWjjhWRe
+2vEPJOVxG5pN/FAo+lFoGiLe3QsLRLPlQrGfT/92W28QEcRrRSutjRZOL3wKezQA
+DkAPU9HX3lACR5yQD6+a0HHgMr1MqeNFPi9MPPjywGywTyWzHd4WQqvTAoGBAMc7
+J4fpr5uPVq9mKemK67i7meJ8AxjjU7oNe8EN+2XfCYcQUmgIo+dLzV9+DTrYkoTz
+iqjA6Ph2DNs6YHI/JNwsdSbAz6KVDteimt3t+uyNpiMGuyLmfOgpYEMJcHp+q6I6
+7PGKVS4c5iPFiYuIo23Is9ZMxOVQp76+UOy09rwbAoGBAOM5Za7VQjGkTGAf7ab/
+j+ZZu/dlZR8XrJSoCRmHZ9hgoLEJuJzJMXruFWeY028SmEivbrW+u0+dEJY5qOJr
+ARe7KkZXCZEPmUrP8Lpi4pjFHa9tdjhGVNdhRCTAKz442vCfJ9DZDUHCuPDCvxsP
+gEzIPtZjl/hxzmdElRj0JClBAoGAaXmfzAyjs6+HLQThW4r4kKyBI66T1TFEulM5
+GVPVrHEQEjlJ51nrrCAtckjBqE3QBCMLXZwDusaEt+uH8/QKB6Zhv0qEooZXfUHQ
+y32aQnIbap+9oxRzPFXraJIuwisdop2fo6Cgx/D0xitmTkDghNaknue1tdGlfQ40
+uZx0o9ECgYBeKeNbMnWoO46ZOrhaz8On+fIY7xtboV2bALy7lvUbWd9B41ntqYUm
+NHlYXDDU+Izs5wnNJnNnx4vECuUzYbpeY82dvMewlQwfl5aiyKrjo7VxLm//2U/K
+hlID6DU5wi9O+TAQ319DhxT7Ja+AQxO/OFS/mfrtwJEevxXqJLu55Q==
+-----END RSA PRIVATE KEY-----
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/unit/GetTCPTests.cpp
----------------------------------------------------------------------
diff --git a/libminifi/test/unit/GetTCPTests.cpp b/libminifi/test/unit/GetTCPTests.cpp
index 87121dc..6e28bf1 100644
--- a/libminifi/test/unit/GetTCPTests.cpp
+++ b/libminifi/test/unit/GetTCPTests.cpp
@@ -415,3 +415,7 @@ TEST_CASE("GetTCPEmptyNoConnect", "[GetTCP3]") {
LogTestController::getInstance().reset();
}
+
+
+
+
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/unit/SocketTests.cpp
----------------------------------------------------------------------
diff --git a/libminifi/test/unit/SocketTests.cpp b/libminifi/test/unit/SocketTests.cpp
index a4785f9..7e78846 100644
--- a/libminifi/test/unit/SocketTests.cpp
+++ b/libminifi/test/unit/SocketTests.cpp
@@ -227,3 +227,17 @@ TEST_CASE("TestTLSContextCreation2", "[TestSocket7]") {
REQUIRE(tls == nullptr);
}
+/**
+ * MINIFI-329 was created in regards to an option existing but not
+ * being properly evaluated.
+ */
+TEST_CASE("TestTLSContextCreationNullptr", "[TestSocket7]") {
+ std::shared_ptr<minifi::Configure> configure = std::make_shared<minifi::Configure>();
+ configure->set("nifi.remote.input.secure", "false");
+ minifi::io::StreamFactory factory(configure);
+ std::string host = "localhost";
+ minifi::io::Socket *socket = factory.createSecureSocket(host, 10001, nullptr).release();
+ minifi::io::TLSSocket *tls = dynamic_cast<minifi::io::TLSSocket*>(socket);
+ REQUIRE(tls == nullptr);
+}
+
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/13a283d9/libminifi/test/unit/UpdateAttributeTests.cpp
----------------------------------------------------------------------
diff --git a/libminifi/test/unit/UpdateAttributeTests.cpp b/libminifi/test/unit/UpdateAttributeTests.cpp
index 9009ea2..fe68515 100644
--- a/libminifi/test/unit/UpdateAttributeTests.cpp
+++ b/libminifi/test/unit/UpdateAttributeTests.cpp
@@ -27,19 +27,11 @@ TEST_CASE("UpdateAttributeTest", "[updateAttributeTest]") {
LogTestController::getInstance().setDebug<minifi::processors::UpdateAttribute>();
LogTestController::getInstance().setDebug<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
-
std::shared_ptr<TestPlan> plan = testController.createPlan();
- const auto &generate_proc = plan->addProcessor("GenerateFlowFile",
- "generate");
- const auto &update_proc = plan->addProcessor("UpdateAttribute",
- "update",
- core::Relationship("success", "description"),
- true);
- const auto &log_proc = plan->addProcessor("LogAttribute",
- "log",
- core::Relationship("success", "description"),
- true);
+ const auto &generate_proc = plan->addProcessor("GenerateFlowFile", "generate");
+ const auto &update_proc = plan->addProcessor("UpdateAttribute", "update", core::Relationship("success", "description"), true);
+ const auto &log_proc = plan->addProcessor("LogAttribute", "log", core::Relationship("success", "description"), true);
plan->setProperty(update_proc, "test_attr_1", "test_val_1", true);
plan->setProperty(update_proc, "test_attr_2", "test_val_2", true);
[2/2] nifi-minifi-cpp git commit: MINIFICPP-408: Resolve
configuration of minificontroller. Ensure it can use context service if one
exists within flow by loading configuration
Posted by al...@apache.org.
MINIFICPP-408: Resolve configuration of minificontroller. Ensure it can use context service if one exists within flow by loading configuration
This closes #265.
Signed-off-by: Aldrin Piri <al...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/repo
Commit: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/commit/0b1a01ad
Tree: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/tree/0b1a01ad
Diff: http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/diff/0b1a01ad
Branch: refs/heads/master
Commit: 0b1a01ad4a3e070c5ab96c0f97d3240aac7b6788
Parents: 13a283d
Author: Marc Parisi <ph...@apache.org>
Authored: Tue Feb 20 09:42:09 2018 -0500
Committer: Aldrin Piri <al...@apache.org>
Committed: Wed Feb 21 12:10:02 2018 -0500
----------------------------------------------------------------------
controller/Controller.h | 47 ++++
controller/MiNiFiController.cpp | 49 ++++-
libminifi/include/c2/ControllerSocketProtocol.h | 2 +-
libminifi/include/io/ServerSocket.h | 20 +-
libminifi/include/io/Sockets.h | 2 +
.../include/io/tls/SecureDescriptorStream.h | 189 ++++++++++++++++
libminifi/include/io/tls/TLSServerSocket.h | 9 +-
libminifi/src/c2/ControllerSocketProtocol.cpp | 87 +++++---
libminifi/src/io/ServerSocket.cpp | 8 +-
libminifi/src/io/tls/SecureDescriptorStream.cpp | 216 +++++++++++++++++++
libminifi/src/io/tls/TLSServerSocket.cpp | 24 ++-
libminifi/src/io/tls/TLSSocket.cpp | 8 +-
.../test/integration/SecureSocketGetTCPTest.cpp | 1 -
13 files changed, 614 insertions(+), 48 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/controller/Controller.h
----------------------------------------------------------------------
diff --git a/controller/Controller.h b/controller/Controller.h
index 9cd3ba1..809e74c 100644
--- a/controller/Controller.h
+++ b/controller/Controller.h
@@ -18,6 +18,8 @@
#ifndef CONTROLLER_CONTROLLER_H_
#define CONTROLLER_CONTROLLER_H_
+#include "core/RepositoryFactory.h"
+#include "core/ConfigurationFactory.h"
#include "io/ClientSocket.h"
#include "c2/ControllerSocketProtocol.h"
@@ -197,4 +199,49 @@ int listConnections(std::unique_ptr<minifi::io::Socket> socket, std::ostream &ou
return 0;
}
+std::shared_ptr<core::controller::ControllerService> getControllerService(const std::shared_ptr<minifi::Configure> &configuration, const std::string &service_name) {
+
+ std::string prov_repo_class = "provenancerepository";
+ std::string flow_repo_class = "flowfilerepository";
+ std::string nifi_configuration_class_name = "yamlconfiguration";
+ std::string content_repo_class = "filesystemrepository";
+
+ configuration->get(minifi::Configure::nifi_provenance_repository_class_name, prov_repo_class);
+ // Create repos for flow record and provenance
+ std::shared_ptr<core::Repository> prov_repo = core::createRepository(prov_repo_class, true, "provenance");
+ prov_repo->initialize(configuration);
+
+ configuration->get(minifi::Configure::nifi_flow_repository_class_name, flow_repo_class);
+
+ std::shared_ptr<core::Repository> flow_repo = core::createRepository(flow_repo_class, true, "flowfile");
+
+ flow_repo->initialize(configuration);
+
+ configuration->get(minifi::Configure::nifi_content_repository_class_name, content_repo_class);
+
+ std::shared_ptr<core::ContentRepository> content_repo = core::createContentRepository(content_repo_class, true, "content");
+
+ content_repo->initialize(configuration);
+
+ std::string content_repo_path;
+ if (configuration->get(minifi::Configure::nifi_dbcontent_repository_directory_default, content_repo_path)) {
+ std::cout << "setting default dir to " << content_repo_path << std::endl;
+ minifi::setDefaultDirectory(content_repo_path);
+ }
+
+ configuration->get(minifi::Configure::nifi_configuration_class_name, nifi_configuration_class_name);
+
+ std::shared_ptr<minifi::io::StreamFactory> stream_factory = std::make_shared<minifi::io::StreamFactory>(configuration);
+
+ std::unique_ptr<core::FlowConfiguration> flow_configuration = core::createFlowConfiguration(prov_repo, flow_repo, content_repo, configuration, stream_factory, nifi_configuration_class_name);
+
+ std::shared_ptr<minifi::FlowController> controller = std::unique_ptr<minifi::FlowController>(
+ new minifi::FlowController(prov_repo, flow_repo, configuration, std::move(flow_configuration), content_repo));
+ controller->load();
+ auto service = controller->getControllerService(service_name);
+ if (service)
+ service->onEnable();
+ return service;
+}
+
#endif /* CONTROLLER_CONTROLLER_H_ */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/controller/MiNiFiController.cpp
----------------------------------------------------------------------
diff --git a/controller/MiNiFiController.cpp b/controller/MiNiFiController.cpp
index 65d9dbd..811aa07 100644
--- a/controller/MiNiFiController.cpp
+++ b/controller/MiNiFiController.cpp
@@ -34,7 +34,7 @@
#include "core/RepositoryFactory.h"
#include "FlowController.h"
#include "Main.h"
-
+#include "properties/Configure.h"
#include "Controller.h"
#include "c2/ControllerSocketProtocol.h"
@@ -87,6 +87,39 @@ int main(int argc, char **argv) {
log_properties->loadConfigureFile(DEFAULT_LOG_PROPERTIES_FILE);
logging::LoggerConfiguration::getConfiguration().initialize(log_properties);
+ std::string context_name;
+
+ std::shared_ptr<minifi::controllers::SSLContextService> secure_context = nullptr;
+
+ // if the user wishes to use a controller service we need to instantiate the flow
+ if (configuration->get("controller.ssl.context.service", context_name)) {
+ std::shared_ptr<core::controller::ControllerService> service = getControllerService(configuration, context_name);
+ if (nullptr != service) {
+ secure_context = std::static_pointer_cast<minifi::controllers::SSLContextService>(service);
+ }
+ }
+
+ if (nullptr == secure_context) {
+ std::string secureStr;
+ bool is_secure = false;
+ if (configuration->get(minifi::Configure::nifi_remote_input_secure, secureStr) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(secureStr, is_secure)) {
+ std::cout << "Creating secure context" << std::endl;
+ secure_context = std::make_shared<minifi::controllers::SSLContextService>("ControllerSocketProtocolSSL", configuration);
+ secure_context->onEnable();
+ }
+ }
+
+ std::string value;
+
+ bool disable = false;
+ if (secure_context && configuration->get(minifi::Configure::nifi_security_client_disable_host_verification, value) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(value, disable)) {
+ secure_context->setDisableHostVerification();
+ }
+ disable = false;
+ if (secure_context && configuration->get(minifi::Configure::nifi_security_client_disable_peer_verification, value) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(value, disable)) {
+ secure_context->setDisablePeerVerification();
+ }
+
auto stream_factory_ = std::make_shared<minifi::io::StreamFactory>(configuration);
std::string host = "localhost", portStr, caCert;
@@ -144,7 +177,7 @@ int main(int argc, char **argv) {
if (result.count("stop") > 0) {
auto& components = result["stop"].as<std::vector<std::string>>();
for (const auto& component : components) {
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (!stopComponent(std::move(socket), component))
std::cout << component << " requested to stop" << std::endl;
else
@@ -155,7 +188,7 @@ int main(int argc, char **argv) {
if (result.count("start") > 0) {
auto& components = result["start"].as<std::vector<std::string>>();
for (const auto& component : components) {
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (!startComponent(std::move(socket), component))
std::cout << component << " requested to start" << std::endl;
else
@@ -166,7 +199,7 @@ int main(int argc, char **argv) {
if (result.count("c") > 0) {
auto& components = result["c"].as<std::vector<std::string>>();
for (const auto& connection : components) {
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (!clearConnection(std::move(socket), connection))
std::cout << "Cleared " << connection << std::endl;
else
@@ -177,7 +210,7 @@ int main(int argc, char **argv) {
if (result.count("getsize") > 0) {
auto& components = result["getsize"].as<std::vector<std::string>>();
for (const auto& component : components) {
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (getConnectionSize(std::move(socket), std::cout, component) < 0)
std::cout << "Could not connect to remote host " << host << ":" << port << std::endl;
}
@@ -186,7 +219,7 @@ int main(int argc, char **argv) {
if (result.count("l") > 0) {
auto& option = result["l"].as<std::string>();
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (option == "components") {
if (listComponents(std::move(socket), std::cout, show_headers) < 0)
std::cout << "Could not connect to remote host " << host << ":" << port << std::endl;
@@ -198,14 +231,14 @@ int main(int argc, char **argv) {
}
if (result.count("getfull") > 0) {
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (getFullConnections(std::move(socket), std::cout) < 0)
std::cout << "Could not connect to remote host " << host << ":" << port << std::endl;
}
if (result.count("updateflow") > 0) {
auto& flow_file = result["updateflow"].as<std::string>();
- auto socket = stream_factory_->createSocket(host, port);
+ auto socket = secure_context != nullptr ? stream_factory_->createSecureSocket(host, port, secure_context) : stream_factory_->createSocket(host, port);
if (updateFlow(std::move(socket), std::cout, flow_file) < 0)
std::cout << "Could not connect to remote host " << host << ":" << port << std::endl;
}
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/include/c2/ControllerSocketProtocol.h
----------------------------------------------------------------------
diff --git a/libminifi/include/c2/ControllerSocketProtocol.h b/libminifi/include/c2/ControllerSocketProtocol.h
index 156cf5c..e437cc4 100644
--- a/libminifi/include/c2/ControllerSocketProtocol.h
+++ b/libminifi/include/c2/ControllerSocketProtocol.h
@@ -74,7 +74,7 @@ class ControllerSocketProtocol : public HeartBeatReporter {
std::map<std::string, bool> component_map_;
- std::unique_ptr<io::ServerSocket> server_socket_;
+ std::unique_ptr<io::BaseServerSocket> server_socket_;
std::shared_ptr<minifi::io::StreamFactory> stream_factory_;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/include/io/ServerSocket.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/ServerSocket.h b/libminifi/include/io/ServerSocket.h
index 025d05f..3af2e4f 100644
--- a/libminifi/include/io/ServerSocket.h
+++ b/libminifi/include/io/ServerSocket.h
@@ -26,17 +26,31 @@ namespace nifi {
namespace minifi {
namespace io {
+
+class BaseServerSocket {
+
+ public:
+
+ virtual ~BaseServerSocket(){
+
+ }
+
+ virtual int16_t initialize(bool loopbackOnly) = 0;
+
+ virtual void registerCallback(std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler) = 0;
+
+};
/**
* Purpose: Server socket abstraction that makes focusing the accept/block paradigm
* simpler.
*/
-class ServerSocket : public Socket {
+class ServerSocket : public BaseServerSocket, public Socket {
public:
explicit ServerSocket(const std::shared_ptr<SocketContext> &context, const std::string &hostname, const uint16_t port, const uint16_t listeners);
virtual ~ServerSocket();
- int16_t initialize(bool loopbackOnly){
+ virtual int16_t initialize(bool loopbackOnly){
is_loopback_only_ = loopbackOnly;
return Socket::initialize();
}
@@ -48,7 +62,7 @@ class ServerSocket : public Socket {
/**
* Registers a call back and starts the read for the server socket.
*/
- void registerCallback(std::function<bool()> accept_function, std::function<void(int)> handler);
+ virtual void registerCallback(std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler);
private:
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/include/io/Sockets.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/Sockets.h b/libminifi/include/io/Sockets.h
index 78ea645..4552fe5 100644
--- a/libminifi/include/io/Sockets.h
+++ b/libminifi/include/io/Sockets.h
@@ -23,6 +23,8 @@
#ifdef OPENSSL_SUPPORT
#include "tls/TLSSocket.h"
+#include "tls/TLSServerSocket.h"
#endif
+
#endif /* LIBMINIFI_INCLUDE_IO_TLS_SECURESOCKET_H_ */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/include/io/tls/SecureDescriptorStream.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/tls/SecureDescriptorStream.h b/libminifi/include/io/tls/SecureDescriptorStream.h
new file mode 100644
index 0000000..c791ae8
--- /dev/null
+++ b/libminifi/include/io/tls/SecureDescriptorStream.h
@@ -0,0 +1,189 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef LIBMINIFI_INCLUDE_IO_SECUREDESCRIPTORSTREAM_H_
+#define LIBMINIFI_INCLUDE_IO_SECUREDESCRIPTORSTREAM_H_
+
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <iostream>
+#include <cstdint>
+#include <string>
+#include "io/EndianCheck.h"
+#include "io/BaseStream.h"
+#include "io/Serializable.h"
+#include "core/logging/LoggerConfiguration.h"
+
+namespace org {
+namespace apache {
+namespace nifi {
+namespace minifi {
+namespace io {
+
+/**
+ * Purpose: File Stream Base stream extension. This is intended to be a thread safe access to
+ * read/write to the local file system.
+ *
+ * Design: Simply extends BaseStream and overrides readData/writeData to allow a sink to the
+ * fstream object.
+ */
+class SecureDescriptorStream : public io::BaseStream {
+ public:
+ /**
+ * File Stream constructor that accepts an fstream shared pointer.
+ * It must already be initialized for read and write.
+ */
+ explicit SecureDescriptorStream(int fd, SSL *s);
+
+ virtual ~SecureDescriptorStream() {
+
+ }
+
+ /**
+ * Skip to the specified offset.
+ * @param offset offset to which we will skip
+ */
+ void seek(uint64_t offset);
+
+ const uint64_t getSize() const {
+ return -1;
+ }
+
+ // data stream extensions
+ /**
+ * Reads data and places it into buf
+ * @param buf buffer in which we extract data
+ * @param buflen
+ */
+ virtual int readData(std::vector<uint8_t> &buf, int buflen);
+ /**
+ * Reads data and places it into buf
+ * @param buf buffer in which we extract data
+ * @param buflen
+ */
+ virtual int readData(uint8_t *buf, int buflen);
+
+ /**
+ * Write value to the stream using std::vector
+ * @param buf incoming buffer
+ * @param buflen buffer to write
+ *
+ */
+ virtual int writeData(std::vector<uint8_t> &buf, int buflen);
+
+ /**
+ * writes value to stream
+ * @param value value to write
+ * @param size size of value
+ */
+ virtual int writeData(uint8_t *value, int size);
+
+ /**
+ * Returns the underlying buffer
+ * @return vector's array
+ **/
+ const uint8_t *getBuffer() const {
+ throw std::runtime_error("Stream does not support this operation");
+ }
+
+ /**
+ * reads a byte from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int read(uint8_t &value);
+
+ /**
+ * reads two bytes from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int read(uint16_t &base_value, bool is_little_endian = false);
+
+ /**
+ * reads a byte from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int read(char &value);
+
+ /**
+ * reads a byte array from the stream
+ * @param value reference in which will set the result
+ * @param len length to read
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int read(uint8_t *value, int len);
+
+ /**
+ * reads four bytes from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int read(uint32_t &value, bool is_little_endian = false);
+
+ /**
+ * reads eight byte from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int read(uint64_t &value, bool is_little_endian = false);
+
+
+ /**
+ * read UTF from stream
+ * @param str reference string
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+ virtual int readUTF(std::string &str, bool widen = false);
+
+ protected:
+
+ /**
+ * Creates a vector and returns the vector using the provided
+ * type name.
+ * @param t incoming object
+ * @returns vector.
+ */
+ template<typename T>
+ std::vector<uint8_t> readBuffer(const T&);
+ std::recursive_mutex file_lock_;
+
+ int fd_;
+
+ SSL *ssl_;
+
+ private:
+
+ std::shared_ptr<logging::Logger> logger_;
+
+};
+
+} /* namespace io */
+} /* namespace minifi */
+} /* namespace nifi */
+} /* namespace apache */
+} /* namespace org */
+
+#endif /* LIBMINIFI_INCLUDE_IO_SECUREDESCRIPTORSTREAM_H_ */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/include/io/tls/TLSServerSocket.h
----------------------------------------------------------------------
diff --git a/libminifi/include/io/tls/TLSServerSocket.h b/libminifi/include/io/tls/TLSServerSocket.h
index a7ec6fe..b5f683c 100644
--- a/libminifi/include/io/tls/TLSServerSocket.h
+++ b/libminifi/include/io/tls/TLSServerSocket.h
@@ -19,6 +19,7 @@
#define LIBMINIFI_INCLUDE_IO_TLSSERVERSOCKET_H_
#include "TLSSocket.h"
+#include "../ServerSocket.h"
namespace org {
namespace apache {
@@ -30,7 +31,7 @@ namespace io {
* Purpose: Server socket abstraction that makes focusing the accept/block paradigm
* simpler.
*/
-class TLSServerSocket : public TLSSocket {
+class TLSServerSocket : public BaseServerSocket, public TLSSocket {
public:
explicit TLSServerSocket(const std::shared_ptr<TLSContext> &context, const std::string &hostname, const uint16_t port, const uint16_t listeners);
@@ -50,6 +51,12 @@ class TLSServerSocket : public TLSSocket {
*/
void registerCallback(std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*,int *)> handler);
+ /**
+ * Initializes the socket
+ * @return result of the creation operation.
+ */
+ virtual void registerCallback(std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler);
+
private:
std::function<void(std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*,int *)> handler)> fx;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/src/c2/ControllerSocketProtocol.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/c2/ControllerSocketProtocol.cpp b/libminifi/src/c2/ControllerSocketProtocol.cpp
index a60cece..ae84c1c 100644
--- a/libminifi/src/c2/ControllerSocketProtocol.cpp
+++ b/libminifi/src/c2/ControllerSocketProtocol.cpp
@@ -18,7 +18,6 @@
#include "c2/ControllerSocketProtocol.h"
#include "utils/StringUtils.h"
-#include "io/DescriptorStream.h"
#include <utility>
#include <memory>
#include <vector>
@@ -35,17 +34,56 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
HeartBeatReporter::initialize(controller, updateSink, configuration);
stream_factory_ = std::make_shared<minifi::io::StreamFactory>(configuration);
- std::string host = "localhost", port, limitStr;
+ std::string host = "localhost", port, limitStr, context_name;
bool anyInterface = false;
+
+ std::shared_ptr<minifi::controllers::SSLContextService> secure_context = nullptr;
+
+ if (configuration_->get("controller.ssl.context.service", context_name)) {
+ std::shared_ptr<core::controller::ControllerService> service = controller->getControllerService(context_name);
+ if (nullptr != service) {
+ secure_context = std::static_pointer_cast<minifi::controllers::SSLContextService>(service);
+ }
+ }
+ if (nullptr == secure_context) {
+ std::string secureStr;
+ bool is_secure = false;
+ if (configuration->get(Configure::nifi_remote_input_secure, secureStr) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(secureStr, is_secure)) {
+ secure_context = std::make_shared<minifi::controllers::SSLContextService>("ControllerSocketProtocolSSL", configuration);
+ secure_context->onEnable();
+ }
+ }
+
+ std::string value;
+
+ bool disable = false;
+ if (secure_context && configuration->get(Configure::nifi_security_client_disable_host_verification, value) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(value, disable)) {
+ secure_context->setDisableHostVerification();
+ }
+ disable = false;
+ if (secure_context && configuration->get(Configure::nifi_security_client_disable_peer_verification, value) && org::apache::nifi::minifi::utils::StringUtils::StringToBool(value, disable)) {
+ secure_context->setDisablePeerVerification();
+ }
+
if (configuration_->get("controller.socket.local.any.interface", limitStr)) {
utils::StringUtils::StringToBool(limitStr, anyInterface);
}
- // if host name isn't defined we will use localhost
+// if host name isn't defined we will use localhost
configuration_->get("controller.socket.host", host);
if (nullptr != configuration_ && configuration_->get("controller.socket.port", port)) {
- server_socket_ = std::unique_ptr<io::ServerSocket>(new io::ServerSocket(nullptr, host, std::stoi(port), 2));
+ if (nullptr != secure_context) {
+#ifdef OPENSSL_SUPPORT
+ // if there is no openssl support we won't be using SSL
+ auto tls_context = std::make_shared<io::TLSContext>(configuration, secure_context);
+ server_socket_ = std::unique_ptr<io::BaseServerSocket>(new io::TLSServerSocket(tls_context, host, std::stoi(port), 2));
+#else
+ server_socket_ = std::unique_ptr<io::BaseServerSocket>(new io::ServerSocket(nullptr, host, std::stoi(port), 2));
+#endif
+ } else {
+ server_socket_ = std::unique_ptr<io::BaseServerSocket>(new io::ServerSocket(nullptr, host, std::stoi(port), 2));
+ }
// if we have a localhost hostname and we did not manually specify any.interface we will
// bind only to the loopback adapter
if ((host == "localhost" || host == "127.0.0.1" || host == "::") && !anyInterface) {
@@ -58,46 +96,45 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
return update_sink_->isRunning();
};
- auto handler = [this](int fd) {
+ auto handler = [this](io::BaseStream *stream) {
uint8_t head;
- io::DescriptorStream stream(fd);
- if (stream.read(head) != 1) {
- logger_->log_debug("Connection broke with fd %d", fd);
+ if (stream->read(head) != 1) {
+ logger_->log_debug("Connection broke");
return;
}
switch (head) {
case Operation::START:
{
std::string componentStr;
- int size = stream.readUTF(componentStr);
+ int size = stream->readUTF(componentStr);
if ( size != -1 ) {
auto components = update_sink_->getComponents(componentStr);
for (auto component : components) {
component->start();
}
} else {
- logger_->log_debug("Connection broke with fd %d", fd);
+ logger_->log_debug("Connection broke");
}
}
break;
case Operation::STOP:
{
std::string componentStr;
- int size = stream.readUTF(componentStr);
+ int size = stream->readUTF(componentStr);
if ( size != -1 ) {
auto components = update_sink_->getComponents(componentStr);
for (auto component : components) {
component->stop(true, 1000);
}
} else {
- logger_->log_debug("Connection broke with fd %d", fd);
+ logger_->log_debug("Connection broke");
}
}
break;
case Operation::CLEAR:
{
std::string connection;
- int size = stream.readUTF(connection);
+ int size = stream->readUTF(connection);
if ( size != -1 ) {
update_sink_->clearConnection(connection);
}
@@ -106,19 +143,19 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
case Operation::UPDATE:
{
std::string what;
- int size = stream.readUTF(what);
+ int size = stream->readUTF(what);
if (size == -1) {
- logger_->log_debug("Connection broke with fd %d", fd);
+ logger_->log_debug("Connection broke");
break;
}
if (what == "flow") {
std::string ff_loc;
- int size = stream.readUTF(ff_loc);
+ int size = stream->readUTF(ff_loc);
std::ifstream tf(ff_loc);
std::string configuration((std::istreambuf_iterator<char>(tf)),
std::istreambuf_iterator<char>());
if (size == -1) {
- logger_->log_debug("Connection broke with fd %d", fd);
+ logger_->log_debug("Connection broke");
break;
}
update_sink_->applyUpdate(configuration);
@@ -128,16 +165,16 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
case Operation::DESCRIBE:
{
std::string what;
- int size = stream.readUTF(what);
+ int size = stream->readUTF(what);
if (size == -1) {
- logger_->log_debug("Connection broke with fd %d", fd);
+ logger_->log_debug("Connection broke");
break;
}
if (what == "queue") {
std::string connection;
- int size = stream.readUTF(connection);
+ int size = stream->readUTF(connection);
if (size == -1) {
- logger_->log_debug("Connection broke with fd %d", fd);
+ logger_->log_debug("Connection broke");
break;
}
std::stringstream response;
@@ -148,7 +185,7 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
io::BaseStream resp;
resp.writeData(&head, 1);
resp.writeUTF(response.str());
- write(fd, resp.getBuffer(), resp.getSize());
+ stream->writeData(const_cast<uint8_t*>(resp.getBuffer()), resp.getSize());
} else if (what == "components") {
io::BaseStream resp;
resp.writeData(&head, 1);
@@ -157,7 +194,7 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
for (const auto &component : update_sink_->getAllComponents()) {
resp.writeUTF(component->getComponentName());
}
- write(fd, resp.getBuffer(), resp.getSize());
+ stream->writeData(const_cast<uint8_t*>(resp.getBuffer()), resp.getSize());
} else if (what == "connections") {
io::BaseStream resp;
resp.writeData(&head, 1);
@@ -166,7 +203,7 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
for (const auto &connection : queue_full_) {
resp.writeUTF(connection.first, false);
}
- write(fd, resp.getBuffer(), resp.getSize());
+ stream->writeData(const_cast<uint8_t*>(resp.getBuffer()), resp.getSize());
} else if (what == "getfull") {
std::vector<std::string> full_connections;
{
@@ -184,7 +221,7 @@ void ControllerSocketProtocol::initialize(const std::shared_ptr<core::controller
for (auto conn : full_connections) {
resp.writeUTF(conn);
}
- write(fd, resp.getBuffer(), resp.getSize());
+ stream->writeData(const_cast<uint8_t*>(resp.getBuffer()), resp.getSize());
}
}
break;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/src/io/ServerSocket.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/ServerSocket.cpp b/libminifi/src/io/ServerSocket.cpp
index 1a72a0f..bfb098f 100644
--- a/libminifi/src/io/ServerSocket.cpp
+++ b/libminifi/src/io/ServerSocket.cpp
@@ -16,6 +16,7 @@
* limitations under the License.
*/
#include "io/ServerSocket.h"
+#include "io/DescriptorStream.h"
#include <netinet/tcp.h>
#include <sys/types.h>
#include <netdb.h>
@@ -55,12 +56,13 @@ ServerSocket::~ServerSocket() {
* Initializes the socket
* @return result of the creation operation.
*/
-void ServerSocket::registerCallback(std::function<bool()> accept_function, std::function<void(int)> handler) {
- auto fx = [this](std::function<bool()> accept_function, std::function<void(int)> handler) {
+void ServerSocket::registerCallback(std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler) {
+ auto fx = [this](std::function<bool()> accept_function, std::function<void(io::BaseStream *stream)> handler) {
while (running_) {
int fd = select_descriptor(1000);
if (fd >= 0) {
- handler(fd);
+ io::DescriptorStream stream(fd);
+ handler(&stream);
close_fd(fd);
}
}
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/src/io/tls/SecureDescriptorStream.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/tls/SecureDescriptorStream.cpp b/libminifi/src/io/tls/SecureDescriptorStream.cpp
new file mode 100644
index 0000000..c1ddd8a
--- /dev/null
+++ b/libminifi/src/io/tls/SecureDescriptorStream.cpp
@@ -0,0 +1,216 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "io/tls/SecureDescriptorStream.h"
+#include <fstream>
+#include <unistd.h>
+#include <vector>
+#include <memory>
+#include <string>
+#include "io/validation.h"
+namespace org {
+namespace apache {
+namespace nifi {
+namespace minifi {
+namespace io {
+
+SecureDescriptorStream::SecureDescriptorStream(int fd, SSL *ssl)
+ : fd_(fd), ssl_(ssl),
+ logger_(logging::LoggerFactory<SecureDescriptorStream>::getLogger()) {
+}
+
+void SecureDescriptorStream::seek(uint64_t offset) {
+ std::lock_guard<std::recursive_mutex> lock(file_lock_);
+ lseek(fd_, offset, 0x00);
+}
+
+int SecureDescriptorStream::writeData(std::vector<uint8_t> &buf, int buflen) {
+ if (static_cast<int>(buf.capacity()) < buflen) {
+ return -1;
+ }
+ return writeData(reinterpret_cast<uint8_t *>(&buf[0]), buflen);
+}
+
+// data stream overrides
+
+int SecureDescriptorStream::writeData(uint8_t *value, int size) {
+ if (!IsNullOrEmpty(value)) {
+ std::lock_guard<std::recursive_mutex> lock(file_lock_);
+ int bytes = 0;
+ int sent = 0;
+ while (bytes < size) {
+ sent = SSL_write(ssl_, value + bytes, size - bytes);
+ // check for errors
+ if (sent < 0) {
+ int ret = 0;
+ ret = SSL_get_error(ssl_, sent);
+ logger_->log_error("WriteData socket %d send failed %s %d", fd_, strerror(errno), ret);
+ return sent;
+ }
+ bytes += sent;
+ }
+ return size;
+ } else {
+ return -1;
+ }
+}
+
+template<typename T>
+inline std::vector<uint8_t> SecureDescriptorStream::readBuffer(const T& t) {
+ std::vector<uint8_t> buf;
+ buf.resize(sizeof t);
+ readData(reinterpret_cast<uint8_t *>(&buf[0]), sizeof(t));
+ return buf;
+}
+
+int SecureDescriptorStream::readData(std::vector<uint8_t> &buf, int buflen) {
+ if (static_cast<int>(buf.capacity()) < buflen) {
+ buf.resize(buflen);
+ }
+ int ret = readData(reinterpret_cast<uint8_t*>(&buf[0]), buflen);
+
+ if (ret < buflen) {
+ buf.resize(ret);
+ }
+ return ret;
+}
+
+int SecureDescriptorStream::readData(uint8_t *buf, int buflen) {
+ if (!IsNullOrEmpty(buf)) {
+ int total_read = 0;
+ int status = 0;
+ while (buflen) {
+ int sslStatus;
+ do {
+ status = SSL_read(ssl_, buf, buflen);
+ sslStatus = SSL_get_error(ssl_, status);
+ } while (status < 0 && sslStatus == SSL_ERROR_WANT_READ);
+
+ if (status < 0)
+ break;
+
+ buflen -= status;
+ buf += status;
+ total_read += status;
+ }
+
+ return total_read;
+
+ } else {
+ return -1;
+ }
+}
+
+/**
+ * reads a byte from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::read(uint8_t &value) {
+ return Serializable::read(value, reinterpret_cast<DataStream*>(this));
+}
+
+/**
+ * reads two bytes from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::read(uint16_t &base_value, bool is_little_endian) {
+ auto buf = readBuffer(base_value);
+ if (is_little_endian) {
+ base_value = (buf[0] << 8) | buf[1];
+ } else {
+ base_value = buf[0] | buf[1] << 8;
+ }
+ return 2;
+}
+
+/**
+ * reads a byte from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::read(char &value) {
+ return readData(reinterpret_cast<uint8_t*>(&value), 1);
+}
+
+/**
+ * reads a byte array from the stream
+ * @param value reference in which will set the result
+ * @param len length to read
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::read(uint8_t *value, int len) {
+ return readData(value, len);
+}
+
+/**
+ * reads four bytes from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::read(uint32_t &value, bool is_little_endian) {
+ auto buf = readBuffer(value);
+ if (is_little_endian) {
+ value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
+ } else {
+ value = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;
+ }
+ return 4;
+}
+
+/**
+ * reads eight byte from the stream
+ * @param value reference in which will set the result
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::read(uint64_t &value, bool is_little_endian) {
+ auto buf = readBuffer(value);
+
+ if (is_little_endian) {
+ value = ((uint64_t) buf[0] << 56) | ((uint64_t) (buf[1] & 255) << 48) | ((uint64_t) (buf[2] & 255) << 40) | ((uint64_t) (buf[3] & 255) << 32) | ((uint64_t) (buf[4] & 255) << 24)
+ | ((uint64_t) (buf[5] & 255) << 16) | ((uint64_t) (buf[6] & 255) << 8) | ((uint64_t) (buf[7] & 255) << 0);
+ } else {
+ value = ((uint64_t) buf[0] << 0) | ((uint64_t) (buf[1] & 255) << 8) | ((uint64_t) (buf[2] & 255) << 16) | ((uint64_t) (buf[3] & 255) << 24) | ((uint64_t) (buf[4] & 255) << 32)
+ | ((uint64_t) (buf[5] & 255) << 40) | ((uint64_t) (buf[6] & 255) << 48) | ((uint64_t) (buf[7] & 255) << 56);
+ }
+ return 8;
+}
+
+/**
+ * read UTF from stream
+ * @param str reference string
+ * @param stream stream from which we will read
+ * @return resulting read size
+ **/
+int SecureDescriptorStream::readUTF(std::string &str, bool widen) {
+ return Serializable::readUTF(str, reinterpret_cast<DataStream*>(this), widen);
+}
+
+} /* namespace io */
+} /* namespace minifi */
+} /* namespace nifi */
+} /* namespace apache */
+} /* namespace org */
+
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/src/io/tls/TLSServerSocket.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/tls/TLSServerSocket.cpp b/libminifi/src/io/tls/TLSServerSocket.cpp
index 582d0e9..f7901d3 100644
--- a/libminifi/src/io/tls/TLSServerSocket.cpp
+++ b/libminifi/src/io/tls/TLSServerSocket.cpp
@@ -15,6 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+#include "io/tls/SecureDescriptorStream.h"
#include "io/tls/TLSServerSocket.h"
#include <netinet/tcp.h>
#include <sys/types.h>
@@ -58,6 +59,26 @@ TLSServerSocket::~TLSServerSocket() {
* Initializes the socket
* @return result of the creation operation.
*/
+void TLSServerSocket::registerCallback(std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler) {
+ auto fx = [this](std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler) {
+ while (running_) {
+ int fd = select_descriptor(1000);
+ if (fd >= 0) {
+ auto ssl = get_ssl(fd);
+ if (ssl != nullptr) {
+ io::SecureDescriptorStream stream(fd, ssl);
+ handler(&stream);
+ close_fd(fd);
+ }
+ }
+ }
+ };
+ server_read_thread_ = std::thread(fx, accept_function, handler);
+}
+/**
+ * Initializes the socket
+ * @return result of the creation operation.
+ */
void TLSServerSocket::registerCallback(std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*, int *)> handler) {
fx = [this](std::function<bool()> accept_function, std::function<int(std::vector<uint8_t>*, int *)> handler) {
int ret = 0;
@@ -103,8 +124,7 @@ void TLSServerSocket::registerCallback(std::function<bool()> accept_function, st
void TLSServerSocket::close_fd(int fd) {
std::lock_guard<std::recursive_mutex> guard(selection_mutex_);
- close(fd);
- FD_CLR(fd, &total_list_);
+ close_ssl(fd);
}
} /* namespace io */
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/src/io/tls/TLSSocket.cpp
----------------------------------------------------------------------
diff --git a/libminifi/src/io/tls/TLSSocket.cpp b/libminifi/src/io/tls/TLSSocket.cpp
index ef5958c..ed94d36 100644
--- a/libminifi/src/io/tls/TLSSocket.cpp
+++ b/libminifi/src/io/tls/TLSSocket.cpp
@@ -236,8 +236,6 @@ void TLSSocket::close_ssl(int fd) {
}
int16_t TLSSocket::select_descriptor(const uint16_t msec) {
-// if (ssl && SSL_pending(ssl))
- // return 1;
if (listeners_ == 0 && connected_) {
return socket_file_descriptor_;
}
@@ -271,6 +269,7 @@ int16_t TLSSocket::select_descriptor(const uint16_t msec) {
SSL_set_fd(ssl, newfd);
auto accept_value = SSL_accept(ssl);
if (accept_value != -1) {
+ logger_->log_trace("Accepted on %d", newfd);
ssl_map_[newfd] = ssl;
return newfd;
} else {
@@ -439,8 +438,6 @@ int TLSSocket::writeData(uint8_t *value, int size) {
}
int TLSSocket::readData(uint8_t *buf, int buflen) {
- // if (IsNullOrEmpty(ssl))
-// return -1;
int total_read = 0;
int status = 0;
while (buflen) {
@@ -459,6 +456,9 @@ int TLSSocket::readData(uint8_t *buf, int buflen) {
sslStatus = SSL_get_error(fd_ssl, status);
} while (status < 0 && sslStatus == SSL_ERROR_WANT_READ);
+ if (status < 0)
+ break;
+
buflen -= status;
buf += status;
total_read += status;
http://git-wip-us.apache.org/repos/asf/nifi-minifi-cpp/blob/0b1a01ad/libminifi/test/integration/SecureSocketGetTCPTest.cpp
----------------------------------------------------------------------
diff --git a/libminifi/test/integration/SecureSocketGetTCPTest.cpp b/libminifi/test/integration/SecureSocketGetTCPTest.cpp
index 412ea71..02ea113 100644
--- a/libminifi/test/integration/SecureSocketGetTCPTest.cpp
+++ b/libminifi/test/integration/SecureSocketGetTCPTest.cpp
@@ -149,7 +149,6 @@ class SecureSocketTest : public IntegrationBase {
waitToVerifyProcessor();
controller->waitUnload(60000);
isRunning_ = false;
- std::cout << "close?" << std::endl;
server_socket->closeStream();
server_socket = nullptr;
runAssertions();