use std::format in logger, re-organize main.cpp, add SIGINT handling.

This commit is contained in:
Wirlaburla committed 2025-01-01 18:18:00 -06:00
1 parent 54693d03cd
commit f59ea622cc
7 files changed
+343 -273

No files matched your search

+267 -210
View File
@@ -8,6 +8,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <csignal>
#include <mutex>
#include <memory>
#include <system_error>
@@ -33,198 +34,23 @@ struct ftpconn {
bool close = false;
} fdc[MAX_CLIENTS];
void runClient(struct ftpconn* cfd) {
if (!cfd) {
logger->print(LOGLEVEL_ERROR, "Invalid connection handle");
return;
}
std::unique_lock<std::mutex> lock(client_mutex);
if (!cfd->client) {
logger->print(LOGLEVEL_ERROR, "Invalid client handle");
return;
}
int client_sock = cfd->client->control_sock;
Client* client = cfd->client;
lock.unlock();
char inbuf[BUFFERSIZE];
logger->print(LOGLEVEL_DEBUG, "C(%i) Client initialized", client_sock);
while (true) {
memset(inbuf, 0, BUFFERSIZE);
if (fcntl(client_sock, F_GETFD) < 0) {
logger->print(LOGLEVEL_DEBUG, "C(%i) Socket closed", client_sock);
break;
}
struct timeval tv;
tv.tv_sec = 60;
tv.tv_usec = 0;
fd_set readfds, writefds;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_SET(client_sock, &readfds);
// Add socket to writefds if SSL wants to write
if (client->isSecure() && client->getSSL()) {
FD_SET(client_sock, &writefds);
}
int select_result = select(client_sock + 1, &readfds, &writefds, NULL, &tv);
if (select_result < 0) {
if (errno == EINTR) continue;
logger->print(LOGLEVEL_ERROR, "C(%i) Select failed: %s", client_sock, strerror(errno));
break;
}
if (select_result == 0) {
logger->print(LOGLEVEL_DEBUG, "C(%i) Connection timeout", client_sock);
break;
}
int rc;
if (client->isSecure() && client->getSSL()) {
if (!client->isHandshakeComplete()) {
// Continue SSL handshake
ERR_clear_error(); // Clear any previous errors
int ret = SSL_accept(client->getSSL());
if (ret <= 0) {
int ssl_err = SSL_get_error(client->getSSL(), ret);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
continue; // Need more data for handshake
}
unsigned long err = ERR_get_error();
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
logger->print(LOGLEVEL_ERROR, "C(%i) SSL handshake failed with error: %d (%s)",
client_sock, ssl_err, err_buf);
break;
}
client->setHandshakeComplete(true);
logger->print(LOGLEVEL_DEBUG, "C(%i) SSL handshake completed", client_sock);
continue;
} else {
// Normal SSL read after handshake
ERR_clear_error(); // Clear any previous errors
rc = SSL_read(client->getSSL(), inbuf, sizeof(inbuf) - 1);
if (rc <= 0) {
int ssl_err = SSL_get_error(client->getSSL(), rc);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
continue;
}
if (ssl_err == SSL_ERROR_SYSCALL) {
unsigned long err = ERR_get_error();
if (err == 0 && rc == 0) {
logger->print(LOGLEVEL_DEBUG, "C(%i) SSL connection closed", client_sock);
} else {
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
logger->print(LOGLEVEL_ERROR, "C(%i) SSL_read syscall error: %s",
client_sock, err_buf);
}
} else {
unsigned long err = ERR_get_error();
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
logger->print(LOGLEVEL_ERROR, "C(%i) SSL_read failed with error: %d (%s)",
client_sock, ssl_err, err_buf);
}
break;
}
}
} else {
rc = recv(client_sock, inbuf, sizeof(inbuf) - 1, 0);
if (rc <= 0) {
if (rc == 0) {
logger->print(LOGLEVEL_DEBUG, "C(%i) Client disconnected", client_sock);
} else {
logger->print(LOGLEVEL_ERROR, "C(%i) Recv failed: %s", client_sock, strerror(errno));
}
break;
}
}
inbuf[rc] = '\0';
if (rc >= 2 && inbuf[rc-2] == '\r' && inbuf[rc-1] == '\n') {
rc -= 2;
inbuf[rc] = '\0';
}
std::string input(inbuf, rc);
logger->print(LOGLEVEL_DEBUG, "C(%i) >> %s", client_sock, input.c_str());
std::string::size_type space_pos = input.find(" ");
std::string cmd = space_pos != std::string::npos ?
toUpper(input.substr(0, space_pos)) : toUpper(input);
std::string args = space_pos != std::string::npos ?
input.substr(space_pos + 1) : "";
lock.lock();
if (!cfd->client) {
lock.unlock();
break;
}
int revc = client->receive(cmd, args);
lock.unlock();
if (revc != 0) break;
}
// Mark for cleanup
logger->print(LOGLEVEL_DEBUG, "C(%i) Client thread ending", client_sock);
cfd->close = true;
}
void initializePlugins() {
std::string plugin_dir = config->getValue("core", "plugin_path", PLUGIN_DIR);
auto& auth_manager = PluginManager<Auth>::getInstance();
auto& filer_manager = PluginManager<Filer>::getInstance();
auth_manager.setLogger(logger);
filer_manager.setLogger(logger);
// Try loading all plugins into both managers
for (const auto& entry : std::filesystem::directory_iterator(plugin_dir)) {
if (entry.path().extension() == ".so") {
logger->print(LOGLEVEL_DEBUG, "Loading plugin: %s", entry.path().c_str());
auth_manager.loadPlugin(entry.path().string());
filer_manager.loadPlugin(entry.path().string());
}
}
// Initialize auth
std::string auth_type = config->getValue("engines", "auth", "pam");
auth = auth_manager.createPlugin(auth_type, config->get(auth_type)->get());
if (!auth) {
logger->print(LOGLEVEL_CRITICAL, "Failed to create auth engine: %s", auth_type.c_str());
exit(1);
}
// Initialize filer
std::string filer_type = config->getValue("engines", "filer", "local");
default_filer_name = filer_type;
default_filer_factory = filer_manager.getFactory(filer_type);
if (!default_filer_factory) {
logger->print(LOGLEVEL_CRITICAL, "Failed to get filer factory for type: %s", filer_type.c_str());
exit(1);
}
}
void runClient(struct ftpconn* cfd);
void initializePlugins();
void shutdown(int signum);
int main(int argc , char *argv[]) {
printf("%s %s Copyright (C) 2024 Worlio LLC\n", APPNAME, VERSION);
printf("This program comes with ABSOLUTELY NO WARRANTY.\n");
printf("This is free software, and you are welcome to redistribute it under certain conditions.\n\n");
std::cout <<
std::format(
"{} {} Maintained by Worlio LLC 2024-2025\n"
"This program comes with ABSOLUTELY NO WARRANTY.\n"
"This is free software, and you are welcome to redistribute it under certain conditions.\n\n",
APPNAME,
VERSION
);
// SIGNALS
signal(SIGPIPE, SIG_IGN);
std::signal(SIGINT, shutdown);
config = new ConfigFile(concatPath(std::string(CONFIG_DIR), "ftp.conf"));
server_name = config->getValue("core", "server_name", "%a %v");
@@ -249,17 +75,37 @@ int main(int argc , char *argv[]) {
logger->openFileOnLevel(LOGLEVEL_ERROR, config->getValue("logging", "error", mainLogFile).c_str());
logger->openFileOnLevel(LOGLEVEL_CRITICAL, config->getValue("logging", "critical", mainLogFile).c_str());
std::string console_loglevel_string = config->getValue("logging", "console", "all");
if (console_loglevel_string == "all")
logger->setConsoleLevel(LOGLEVEL_MAX);
else if (console_loglevel_string == "debug")
logger->setConsoleLevel(LOGLEVEL_DEBUG);
else if (console_loglevel_string == "info")
logger->setConsoleLevel(LOGLEVEL_INFO);
else if (console_loglevel_string == "warning")
logger->setConsoleLevel(LOGLEVEL_WARNING);
else if (console_loglevel_string == "error")
logger->setConsoleLevel(LOGLEVEL_ERROR);
else if (console_loglevel_string == "critical")
logger->setConsoleLevel(LOGLEVEL_CRITICAL);
else if (console_loglevel_string == "none")
logger->setConsoleLevel(LOGLEVEL_MIN);
else {
logger->setConsoleLevel(LOGLEVEL_MIN);
logger->print(LOGLEVEL_ERROR, "Could not determine console log type.");
}
bool ssl_enable = config->getBool("net", "ssl", true);
bool ssl_flags = SSL_OP_NO_TICKET;
if (ssl_enable) {
std::string cert_file = config->getValue("ssl", "certificate", "cert.pem");
if (cert_file[0] != '/')
cert_file = concatPath(std::string(CONFIG_DIR), cert_file);
logger->print(LOGLEVEL_INFO, "Using certificate file: %s", cert_file.c_str());
logger->print(LOGLEVEL_INFO, "Using certificate file: {}", cert_file);
std::string key_file = config->getValue("ssl", "private_key", "key.pem");
if (key_file[0] != '/')
key_file = concatPath(std::string(CONFIG_DIR), key_file);
logger->print(LOGLEVEL_INFO, "Using private key file: %s", key_file.c_str());
logger->print(LOGLEVEL_INFO, "Using private key file: {}", key_file);
if (!SSLManager::getInstance().initialize(cert_file, key_file)) {
logger->print(LOGLEVEL_CRITICAL, "Failed to initialize SSL");
return 1;
@@ -338,11 +184,11 @@ int main(int argc , char *argv[]) {
if ((src = bind(master_socket, (struct sockaddr *)&ctrl_address, sizeof(ctrl_address))) < 0) {
logger->print(
LOGLEVEL_CRITICAL,
"Bind to %i.%i.%i.%i:%i failed",
&server_address[0],
&server_address[1],
&server_address[2],
&server_address[3],
"Bind to {}.{}.{}.{}:{} failed",
static_cast<unsigned int>(server_address[0]),
static_cast<unsigned int>(server_address[1]),
static_cast<unsigned int>(server_address[2]),
static_cast<unsigned int>(server_address[3]),
server_port
);
close(master_socket);
@@ -381,7 +227,7 @@ int main(int argc , char *argv[]) {
// Handle poll errors properly without skipping cleanup
if (fds[i].revents != POLLIN) {
if (fds[i].fd != master_socket) {
logger->print(LOGLEVEL_ERROR, "Poll error on fd %d", fds[i].fd);
logger->print(LOGLEVEL_ERROR, "net: poll error on fd {}", fds[i].fd);
fdc[i].close = true;
}
}
@@ -392,7 +238,7 @@ int main(int argc , char *argv[]) {
newsock = accept(master_socket, NULL, NULL);
if (newsock < 0) {
if (errno != EWOULDBLOCK) {
logger->print(LOGLEVEL_ERROR, "accept() failed: %s", strerror(errno));
logger->print(LOGLEVEL_ERROR, "net: accept() failed: {}", strerror(errno));
runServer = false;
}
break;
@@ -417,7 +263,7 @@ int main(int argc , char *argv[]) {
int flags = fcntl(newsock, F_GETFL, 0);
fcntl(newsock, F_SETFL, flags | O_NONBLOCK);
logger->print(LOGLEVEL_DEBUG, "C(%i) Accepted client in slot %d", newsock, slot);
logger->print(LOGLEVEL_DEBUG, "client {} accepted in slot {}", newsock, slot);
fds[slot].fd = newsock;
fds[slot].events = POLLIN;
@@ -439,7 +285,7 @@ int main(int argc , char *argv[]) {
// Handle cleanup for any connections marked for closing
if (fds[i].fd != master_socket && (fdc[i].close || fds[i].revents != POLLIN)) {
int fd = fds[i].fd;
logger->print(LOGLEVEL_DEBUG, "C(%i) Cleaning up client in slot %d", fd, i);
logger->print(LOGLEVEL_DEBUG, "cleaning up client {} from slot {}", fd, i);
// Close socket
if (fd > 0) {
@@ -464,8 +310,6 @@ int main(int argc , char *argv[]) {
fds[i].revents = 0;
memset(&fdc[i], 0, sizeof(struct ftpconn));
logger->print(LOGLEVEL_DEBUG, "C(%i) Cleanup completed", fd);
// Recalculate nfds if needed
if (i == nfds - 1) {
for (int j = nfds - 1; j >= 0; j--) {
@@ -478,21 +322,234 @@ int main(int argc , char *argv[]) {
}
}
}
logger->print(LOGLEVEL_INFO, "Server closing...");
close(master_socket);
for (int i = 0; i < current_size; i++) {
if (fds[i].fd != master_socket) {
int fd = fds[i].fd;
logger->print(LOGLEVEL_DEBUG, "disconnecting client {} from slot {}", fd, i);
// Cleanup
for (int i = 0; i < nfds; i++) {
if (fds[i].fd >= 0) {
close(fds[i].fd);
if (fdc[i].thread && fdc[i].thread->joinable()) {
fdc[i].thread->join();
if (fd > 0) {
shutdown(fd, SHUT_RDWR);
close(fd);
}
delete fdc[i].thread;
if (fdc[i].thread) {
if (fdc[i].thread->joinable()) {
fdc[i].thread->join();
}
delete fdc[i].thread;
}
// Clean up client
delete fdc[i].client;
// Reset slot
fds[i].fd = -1;
fds[i].events = 0;
fds[i].revents = 0;
memset(&fdc[i], 0, sizeof(struct ftpconn));
if (i == nfds - 1) {
for (int j = nfds - 1; j >= 0; j--) {
if (fds[j].fd != -1) {
nfds = j + 1;
break;
}
}
}
}
}
close(master_socket);
logger->print(LOGLEVEL_INFO, "Server closing...");
logger->close();
return 0;
}
void initializePlugins() {
std::string plugin_dir = config->getValue("core", "plugin_path", PLUGIN_DIR);
auto& auth_manager = PluginManager<Auth>::getInstance();
auto& filer_manager = PluginManager<Filer>::getInstance();
auth_manager.setLogger(logger);
filer_manager.setLogger(logger);
// Try loading all plugins into both managers
for (const auto& entry : std::filesystem::directory_iterator(plugin_dir)) {
if (entry.path().extension() == ".so") {
logger->print(LOGLEVEL_DEBUG, "Loading plugin: {}", entry.path().string());
auth_manager.loadPlugin(entry.path().string());
filer_manager.loadPlugin(entry.path().string());
}
}
// Initialize auth
std::string auth_type = config->getValue("engines", "auth", "pam");
auth = auth_manager.createPlugin(auth_type, config->get(auth_type)->get());
if (!auth) {
logger->print(LOGLEVEL_CRITICAL, "Failed to create auth engine: {}", auth_type);
exit(1);
}
// Initialize filer
std::string filer_type = config->getValue("engines", "filer", "local");
default_filer_name = filer_type;
default_filer_factory = filer_manager.getFactory(filer_type);
if (!default_filer_factory) {
logger->print(LOGLEVEL_CRITICAL, "Failed to get filer factory for type {}", filer_type);
exit(1);
}
}
void runClient(struct ftpconn* cfd) {
if (!cfd) {
logger->print(LOGLEVEL_ERROR, "Invalid connection handle");
return;
}
std::unique_lock<std::mutex> lock(client_mutex);
if (!cfd->client) {
logger->print(LOGLEVEL_ERROR, "Invalid client handle");
return;
}
int client_sock = cfd->client->control_sock;
Client* client = cfd->client;
lock.unlock();
char inbuf[BUFFERSIZE];
logger->print(LOGLEVEL_DEBUG, "client {} initialized", client_sock);
while (!cfd->close) {
memset(inbuf, 0, BUFFERSIZE);
if (fcntl(client_sock, F_GETFD) < 0) {
logger->print(LOGLEVEL_DEBUG, "closed client {} socket", client_sock);
break;
}
struct timeval tv;
tv.tv_sec = 60;
tv.tv_usec = 0;
fd_set readfds, writefds;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_SET(client_sock, &readfds);
// Add socket to writefds if SSL wants to write
if (client->isSecure() && client->getSSL()) {
FD_SET(client_sock, &writefds);
}
int select_result = select(client_sock + 1, &readfds, &writefds, NULL, &tv);
if (select_result < 0) {
if (errno == EINTR) continue;
logger->print(LOGLEVEL_ERROR, "client {} experienced select fail: %s", client_sock, strerror(errno));
break;
}
if (select_result == 0) {
logger->print(LOGLEVEL_INFO, "client {} timeout", client_sock);
break;
}
int rc;
if (client->isSecure() && client->getSSL()) {
if (!client->isHandshakeComplete()) {
// Continue SSL handshake
ERR_clear_error(); // Clear any previous errors
int ret = SSL_accept(client->getSSL());
if (ret <= 0) {
int ssl_err = SSL_get_error(client->getSSL(), ret);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
continue; // Need more data for handshake
}
unsigned long err = ERR_get_error();
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
logger->print(LOGLEVEL_ERROR, "client {} SSL handshake failed with error: {} ({})",
client_sock, ssl_err, err_buf);
break;
}
client->setHandshakeComplete(true);
logger->print(LOGLEVEL_DEBUG, "client {} SSL handshake completed", client_sock);
continue;
} else {
// Normal SSL read after handshake
ERR_clear_error(); // Clear any previous errors
rc = SSL_read(client->getSSL(), inbuf, sizeof(inbuf) - 1);
if (rc <= 0) {
int ssl_err = SSL_get_error(client->getSSL(), rc);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
continue;
}
if (ssl_err == SSL_ERROR_SYSCALL) {
unsigned long err = ERR_get_error();
if (err == 0 && rc == 0) {
logger->print(LOGLEVEL_DEBUG, "client {} SSL connection closed", client_sock);
} else {
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
logger->print(LOGLEVEL_ERROR, "client {} experienced SSL_read syscall error: {}",
client_sock, err_buf);
}
} else {
unsigned long err = ERR_get_error();
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
logger->print(LOGLEVEL_ERROR, "client {} experienced SSL_read error: {} ({})",
client_sock, ssl_err, err_buf);
}
break;
}
}
} else {
rc = recv(client_sock, inbuf, sizeof(inbuf) - 1, 0);
if (rc <= 0) {
if (rc == 0) {
logger->print(LOGLEVEL_DEBUG, "client {} disconnected", client_sock);
} else {
logger->print(LOGLEVEL_ERROR, "recieve from client {} failed: {}", client_sock, strerror(errno));
}
break;
}
}
inbuf[rc] = '\0';
if (rc >= 2 && inbuf[rc-2] == '\r' && inbuf[rc-1] == '\n') {
rc -= 2;
inbuf[rc] = '\0';
}
std::string input(inbuf, rc);
logger->print(LOGLEVEL_DEBUG, "recieved from client {}: {}", client_sock, input);
std::string::size_type space_pos = input.find(" ");
std::string cmd = space_pos != std::string::npos ?
toUpper(input.substr(0, space_pos)) : toUpper(input);
std::string args = space_pos != std::string::npos ?
input.substr(space_pos + 1) : "";
lock.lock();
if (!cfd->client) {
lock.unlock();
break;
}
int revc = client->receive(cmd, args);
lock.unlock();
if (revc != 0) break;
}
// Mark for cleanup
logger->print(LOGLEVEL_DEBUG, "client {} thread ending", client_sock);
cfd->close = true;
}
void shutdown(int signum) {
runServer = false;
}