src/Socket.cpp
author František Kučera <franta-hg@frantovo.cz>
Sat, 30 Jul 2022 23:25:23 +0200
branchv_0
changeset 9 de48b9278211
parent 7 e6f005f3edfe
child 10 6a6b93507856
permissions -rw-r--r--
TCP and UDP client sockets - first version

/**
 * Relational pipes
 * Copyright © 2022 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdexcept>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <vector>
#include <memory>
#include <regex>

#include "Socket.h"

namespace relpipe {
namespace out {
namespace socket {

using namespace relpipe::out::socket::options;

static const std::string findOption(SocketOptions options, std::string name, bool required = false, const std::string defaultValue = "") {
	for (auto o : options) if (o.name == name) return o.value;
	if (required) throw std::invalid_argument("Option " + name + " is required but was not found");
	else return defaultValue;
}

class FD {
private:
	int fd;
public:

	FD(int fd) : fd(fd) {
	};

	virtual ~FD() {
		close(fd);
	}

	int getFD() {
		return fd;
	}
};

static void check(int result, std::string message) {
	if (result == 0); // OK
	else throw std::logic_error("Got error result: " + std::to_string(result) + " - " + message);
}

class UDPClientSocket : public Socket {
private:
	struct sockaddr_in remoteAddress;
	int protocol = IPPROTO_UDP;
	int type = SOCK_DGRAM;
public:

	static std::shared_ptr<Socket> open(const SocketOptions& options) {
		std::shared_ptr<UDPClientSocket> s = std::make_shared<UDPClientSocket>();
		memset((char *) &s->remoteAddress, 0, sizeof (s->remoteAddress));
		s->remoteAddress.sin_family = AF_INET;
		s->remoteAddress.sin_addr.s_addr = inet_addr(findOption(options, OPTION_HOST, true).c_str()); // TODO: use getaddrinfo() instead (because of error -1 = 255.255.255.255)
		s->remoteAddress.sin_port = htons(std::stoi(findOption(options, OPTION_PORT, true)));

		auto protocol = findOption(options, OPTION_PROTOCOL);
		if (protocol == PROTOCOL_SCTP) {
			s->protocol = IPPROTO_SCTP;
			s->type = SOCK_SEQPACKET;
		}

		return s;
	}

	void send(const std::string& message) override {
		FD s(::socket(AF_INET, type, protocol));
		sendto(s.getFD(), message.c_str(), message.size(), 0, (sockaddr*) & remoteAddress, sizeof (remoteAddress));
	}

	const std::string receive() override {
		// TODO: TCP receive()
		return "TODO: receive() a message";
	}

};

class TCPClientSocket : public Socket {
private:
	struct sockaddr_in remoteAddress;
public:

	static std::shared_ptr<Socket> open(const SocketOptions& options) {
		std::shared_ptr<TCPClientSocket> s = std::make_shared<TCPClientSocket>();
		memset((char *) &s->remoteAddress, 0, sizeof (s->remoteAddress));
		s->remoteAddress.sin_family = AF_INET;
		s->remoteAddress.sin_addr.s_addr = inet_addr(findOption(options, OPTION_HOST, true).c_str()); // TODO: use getaddrinfo() instead (because of error -1 = 255.255.255.255)
		s->remoteAddress.sin_port = htons(std::stoi(findOption(options, OPTION_PORT, true)));
		return s;
	}

	void send(const std::string& message) override {
		FD s(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
		check(::connect(s.getFD(), (sockaddr*) & remoteAddress, sizeof (remoteAddress)), "connect socket");
		ssize_t written = ::write(s.getFD(), message.c_str(), message.size());
		if (written != message.size()) throw std::logic_error("writing to the socket failed");
	}

	const std::string receive() override {
		// TODO: TCP receive()
		return "TODO: receive() a message";
	}


};

template<const char* protocol, const char* role, const char* mode, typename SocketClass>
class TemplateSocketFactory : public SocketFactory {
public:

	bool canHandle(const SocketOptions& options) override {
		return findOption(options, OPTION_PROTOCOL) == protocol
				&& findOption(options, OPTION_ROLE) == role
				&& findOption(options, OPTION_MODE) == mode;
	}

	std::shared_ptr<Socket> open(const SocketOptions& options) override {
		return SocketClass::open(options);
	}
};

static std::vector<std::shared_ptr<SocketFactory>> factories
{
	std::make_shared<TemplateSocketFactory<PROTOCOL_TCP, ROLE_CLIENT, MODE_STREAM, TCPClientSocket >> (),
	std::make_shared<TemplateSocketFactory<PROTOCOL_TCP, ROLE_SERVER, MODE_STREAM, TCPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_UDP, ROLE_CLIENT, MODE_DATAGRAM, UDPClientSocket >> (),
	std::make_shared<TemplateSocketFactory<PROTOCOL_UDP, ROLE_SERVER, MODE_DATAGRAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_SCTP, ROLE_CLIENT, MODE_STREAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_SCTP, ROLE_CLIENT, MODE_DATAGRAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_SCTP, ROLE_SERVER, MODE_STREAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_SCTP, ROLE_SERVER, MODE_DATAGRAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_UDS, ROLE_CLIENT, MODE_STREAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_UDS, ROLE_CLIENT, MODE_DATAGRAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_UDS, ROLE_SERVER, MODE_STREAM, UDPClientSocket >> (), // TODO: correct class
	std::make_shared<TemplateSocketFactory<PROTOCOL_UDS, ROLE_SERVER, MODE_DATAGRAM, UDPClientSocket >> (), // TODO: correct class
};

std::shared_ptr<SocketFactory> SocketFactory::find(const SocketOptions& options) {
	for (auto f : factories) if (f->canHandle(options)) return f;
	throw std::logic_error("Unable to find a SocketFactory"); // TODO: add relevant options?
}


}
}
}