Compare commits
9 commits
3c8bd791e6
...
a463fd84a2
Author | SHA1 | Date | |
---|---|---|---|
|
a463fd84a2 | ||
621b3581a5 | |||
092bf2d7d3 | |||
60c1cd512f | |||
d52a64f07d | |||
9cd77421a6 | |||
cc8c9c58dc | |||
b5428005b0 | |||
e2ac9fd1b9 |
34 changed files with 1656 additions and 1226 deletions
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
build/
|
||||||
|
docs/
|
||||||
|
hermesrc.example
|
|
@ -6,6 +6,7 @@ set(LOGGER_CLASS UnixLogger CACHE STRING "One of UnixLogger, FileLogger or NullL
|
||||||
|
|
||||||
add_executable (hermes
|
add_executable (hermes
|
||||||
${CMAKE_CURRENT_BINARY_DIR}/Configfile.cpp
|
${CMAKE_CURRENT_BINARY_DIR}/Configfile.cpp
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/Configfile.h
|
||||||
src/Exception.cpp
|
src/Exception.cpp
|
||||||
src/hermes.cpp
|
src/hermes.cpp
|
||||||
src/ServerSocket.cpp
|
src/ServerSocket.cpp
|
||||||
|
@ -14,7 +15,7 @@ add_executable (hermes
|
||||||
src/Proxy.cpp
|
src/Proxy.cpp
|
||||||
src/Socket.cpp)
|
src/Socket.cpp)
|
||||||
|
|
||||||
option(BUILD_DOC "Build documentation")
|
option(BUILD_DOCS "Build documentation")
|
||||||
|
|
||||||
if(WIN32)
|
if(WIN32)
|
||||||
set(SOURCES ${SOURCES}
|
set(SOURCES ${SOURCES}
|
||||||
|
@ -23,6 +24,7 @@ if(WIN32)
|
||||||
target_compile_definitions(hermes PRIVATE WIN32)
|
target_compile_definitions(hermes PRIVATE WIN32)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
target_include_directories(hermes PRIVATE include)
|
||||||
target_compile_definitions(hermes PRIVATE LOGGER_CLASS=${LOGGER_CLASS})
|
target_compile_definitions(hermes PRIVATE LOGGER_CLASS=${LOGGER_CLASS})
|
||||||
target_sources(hermes PRIVATE src/${LOGGER_CLASS}.cpp)
|
target_sources(hermes PRIVATE src/${LOGGER_CLASS}.cpp)
|
||||||
|
|
||||||
|
@ -30,7 +32,7 @@ target_sources(hermes PRIVATE src/${LOGGER_CLASS}.cpp)
|
||||||
find_library (SQLITE3_LIBRARY NAMES libsqlite3 sqlite3)
|
find_library (SQLITE3_LIBRARY NAMES libsqlite3 sqlite3)
|
||||||
|
|
||||||
# optional dependency libspf2
|
# optional dependency libspf2
|
||||||
find_library (SPF2_LIBRARY NAMES spf2 libspf2)
|
find_library (SPF2_LIBRARY REQUIRED NAMES spf2 libspf2)
|
||||||
if(SPF2_LIB)
|
if(SPF2_LIB)
|
||||||
target_compile_definitions(hermes PRIVATE HAVE_SPF2)
|
target_compile_definitions(hermes PRIVATE HAVE_SPF2)
|
||||||
target_sources(hermes PRIVATE src/Spf.cpp)
|
target_sources(hermes PRIVATE src/Spf.cpp)
|
||||||
|
@ -48,26 +50,43 @@ include_directories(
|
||||||
${CMAKE_CURRENT_BINARY_DIR}
|
${CMAKE_CURRENT_BINARY_DIR}
|
||||||
src)
|
src)
|
||||||
|
|
||||||
|
set(CONFIG_TEMPLATE ${CMAKE_CURRENT_SOURCE_DIR}/src/Configfile.tmpl)
|
||||||
|
|
||||||
# generation of various files
|
# generation of various files
|
||||||
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Configfile.cpp
|
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Configfile.cpp
|
||||||
COMMAND cpp ${OPT_DEFS} ${CMAKE_CURRENT_SOURCE_DIR}/src/Configfile.tmpl -I
|
COMMAND python "${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_config.py" "${CONFIG_TEMPLATE}"
|
||||||
${CMAKE_CURRENT_BINARY_DIR} |
|
--cpp-template "${CMAKE_CURRENT_SOURCE_DIR}/src/Configfile.cpp.in"
|
||||||
${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_config.pl
|
--output-cpp "${CMAKE_CURRENT_BINARY_DIR}/Configfile.cpp"
|
||||||
DEPENDS src/Configfile.cpp.in src/Configfile.h.in src/Configfile.tmpl
|
DEPENDS ${CONFIG_TEMPLATE} src/Configfile.cpp.in)
|
||||||
docs/hermes-options.html.in scripts/generate_config.pl)
|
|
||||||
|
|
||||||
|
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Configfile.h
|
||||||
|
COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_config.py "${CONFIG_TEMPLATE}"
|
||||||
|
--h-template "${CMAKE_CURRENT_SOURCE_DIR}/include/Configfile.h.in"
|
||||||
|
--output-h "${CMAKE_CURRENT_BINARY_DIR}/Configfile.h"
|
||||||
|
DEPENDS ${CONFIG_TEMPLATE} include/Configfile.h.in)
|
||||||
|
|
||||||
|
# DEPENDS src/Configfile.cpp.in src/Configfile.h.in src/Configfile.tmpl
|
||||||
|
# docs/hermes-options.html.in scripts/generate_config.py)
|
||||||
|
|
||||||
# doxygen
|
# doxygen
|
||||||
if (BUILD_DOCS)
|
if (BUILD_DOCS)
|
||||||
|
add_custom_command(OUTPUT docs/hermesrc.example
|
||||||
|
COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_config.py "${CONFIG_TEMPLATE}"
|
||||||
|
--output-example "${CMAKE_CURRENT_BINARY_DIR}/docs/hermesrc.example"
|
||||||
|
DEPENDS ${CONFIG_TEMPLATE})
|
||||||
|
add_custom_command(OUTPUT docs/html/hermes-options.html
|
||||||
|
COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_config.py "${CONFIG_TEMPLATE}"
|
||||||
|
--html-template "${CMAKE_CURRENT_SOURCE_DIR}/docs/hermes-options.html.in"
|
||||||
|
--output-html "${CMAKE_CURRENT_BINARY_DIR}/docs/html/hermes-options.html"
|
||||||
|
DEPENDS ${CONFIG_TEMPLATE} docs/hermes-options.html.in)
|
||||||
find_package (Doxygen)
|
find_package (Doxygen)
|
||||||
if(DOXYGEN_FOUND)
|
add_custom_target(doc ALL
|
||||||
add_custom_target(doc ALL
|
doxygen "${CMAKE_CURRENT_SOURCE_DIR}/docs/Doxyfile"
|
||||||
doxygen
|
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/docs
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/docs)
|
DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/docs/html/hermes-options.html" "${CMAKE_CURRENT_BINARY_DIR}/docs/hermesrc.example")
|
||||||
install(
|
install(
|
||||||
DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/docs/html
|
DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/docs/html
|
||||||
TYPE DOC)
|
TYPE DOC)
|
||||||
endif()
|
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
target_link_libraries(hermes
|
target_link_libraries(hermes
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
FROM alpine:3.18
|
FROM alpine:3.18
|
||||||
ADD . /hermes
|
ADD . /hermes
|
||||||
WORKDIR /hermes
|
WORKDIR /hermes
|
||||||
RUN apk add --no-cache perl graphviz doxygen gcc make openssl-dev libspf2-dev cmake g++ sqlite-dev gettext-dev
|
RUN apk add --no-cache graphviz doxygen gcc make openssl-dev libspf2-dev cmake g++ sqlite-dev gettext-dev python3
|
||||||
RUN cmake -B build
|
RUN cmake -B build
|
||||||
RUN cmake --build build
|
RUN cmake --build build
|
||||||
RUN mkdir /hermes-installation
|
RUN mkdir /hermes-installation
|
||||||
|
|
|
@ -1,62 +0,0 @@
|
||||||
#!/bin/bash
|
|
||||||
# Startup script for hermes
|
|
||||||
#
|
|
||||||
# chkconfig: 3 95 05
|
|
||||||
# description: hermes
|
|
||||||
|
|
||||||
# Source function library.
|
|
||||||
. /etc/rc.d/init.d/functions
|
|
||||||
|
|
||||||
prog=hermes
|
|
||||||
configfile=/etc/hermes/hermesrc
|
|
||||||
|
|
||||||
start() {
|
|
||||||
echo -n $"Starting $prog: "
|
|
||||||
daemon --check=$prog /usr/bin/hermes $configfile
|
|
||||||
RETVAL=$?
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
echo -n $"Stopping $prog: "
|
|
||||||
killproc $prog
|
|
||||||
RETVAL=$?
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
safestop() {
|
|
||||||
echo -n $"Stopping $prog(will process pending connections):"
|
|
||||||
killproc $prog -INT
|
|
||||||
rm /var/run/$prog.pid
|
|
||||||
RETVAL=$?
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
case "$1" in
|
|
||||||
start)
|
|
||||||
start
|
|
||||||
;;
|
|
||||||
|
|
||||||
stop)
|
|
||||||
stop
|
|
||||||
;;
|
|
||||||
|
|
||||||
restart)
|
|
||||||
safestop
|
|
||||||
sleep 2
|
|
||||||
start
|
|
||||||
;;
|
|
||||||
condrestart)
|
|
||||||
if test "x`pidfileofproc $prog`" != x; then
|
|
||||||
stop
|
|
||||||
start
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
|
|
||||||
*)
|
|
||||||
echo $"Usage: $0 {start|stop|restart|condrestart}"
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
esac
|
|
||||||
|
|
||||||
exit $RETVAL
|
|
|
@ -1,77 +0,0 @@
|
||||||
Summary: An anti-spam SMTP proxy
|
|
||||||
Name: @PACKAGE@
|
|
||||||
Version: @VERSION@
|
|
||||||
Release: 0
|
|
||||||
License: GPL
|
|
||||||
Group: System Environment/Daemons
|
|
||||||
Packager: Veit Wahlich <cru@zodia.de>
|
|
||||||
URL: http://www.hermes-project.com/
|
|
||||||
Source0: http://www.hermes-project.com/files/%{name}-%{version}.tar.bz2
|
|
||||||
Buildroot: %{_tmppath}/%{name}-%{version}-%{release}-root
|
|
||||||
|
|
||||||
%description
|
|
||||||
hermes is a generic, lightweight, portable and fast anti-spam smtp proxy.
|
|
||||||
Supports greylisting, dns blacklisting/whitelisting, protocol throttling, banner delaying, spf and some
|
|
||||||
other tricks to reject most spam before it even enters your system.
|
|
||||||
|
|
||||||
%prep
|
|
||||||
%setup -q
|
|
||||||
|
|
||||||
%build
|
|
||||||
%configure --docdir=%{_datadir}/doc/%{name}-%{version}
|
|
||||||
%__make %{?_smp_mflags}
|
|
||||||
|
|
||||||
%install
|
|
||||||
%__rm -rf %{buildroot}
|
|
||||||
%__make DESTDIR=%{buildroot} install
|
|
||||||
%__mkdir_p %{buildroot}%{_sysconfdir}/rc.d/init.d
|
|
||||||
%__mkdir_p %{buildroot}%{_sysconfdir}/hermes
|
|
||||||
%__mkdir_p %{buildroot}%{_localstatedir}/hermes
|
|
||||||
%__install -m 0755 dists/fc_init %{buildroot}%{_sysconfdir}/rc.d/init.d/hermes
|
|
||||||
%__install -m 0600 dists/hermesrc.example %{buildroot}%{_sysconfdir}/hermes/hermesrc
|
|
||||||
|
|
||||||
%clean
|
|
||||||
%__rm -rf %{buildroot}
|
|
||||||
|
|
||||||
%post
|
|
||||||
/sbin/chkconfig --add hermes
|
|
||||||
|
|
||||||
%preun
|
|
||||||
if [ $1 = 0 ]; then # execute this only if we are NOT doing an upgrade
|
|
||||||
%{_sysconfdir}/rc.d/init.d/hermes stop >/dev/null 2>&1
|
|
||||||
/sbin/chkconfig --del hermes
|
|
||||||
fi
|
|
||||||
exit 0
|
|
||||||
|
|
||||||
%files
|
|
||||||
%defattr(-, root, root, 0755)
|
|
||||||
%doc ChangeLog TODO AUTHORS dists/hermesrc.example docs/hermes-options.html docs/installing-hermes.txt docs/gpl.txt
|
|
||||||
%{_bindir}/hermes
|
|
||||||
%{_sysconfdir}/rc.d/init.d/hermes
|
|
||||||
%config %{_sysconfdir}/hermes/hermesrc
|
|
||||||
%dir %attr(0700,nobody,nobody) %{_localstatedir}/hermes
|
|
||||||
|
|
||||||
%changelog
|
|
||||||
* Thu Jun 14 2007 Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com> 1.4
|
|
||||||
- removed patches, they are now on upstream
|
|
||||||
|
|
||||||
* Fri May 25 2007 Veit Wahlich <cru@zodia.de> 1.3-2
|
|
||||||
- added patch fix_whether (documentation fixes)
|
|
||||||
- added patch add_rejectnoresolve (reject on no DNS reverse resolution feature)
|
|
||||||
- changed RPM group to system daemon standard
|
|
||||||
|
|
||||||
* Sat May 19 2007 Veit Wahlich <cru@zodia.de> 1.3-1
|
|
||||||
- Made /etc/hermes/hermesrc readonly as it may contain passwords
|
|
||||||
- Fixed ownership and permissions of /var/hermes to match configuration default
|
|
||||||
- Silenced setup macro output as required by some distributions
|
|
||||||
- Fixed docdir to a LSB compliant location, will be replaced by rpmbuild
|
|
||||||
- Packaged extra documentation
|
|
||||||
- Removed hermes-options.html.in from docs
|
|
||||||
- Use directory macros for files section
|
|
||||||
- Further specfile cleanups and macro usage
|
|
||||||
|
|
||||||
* Tue May 15 2007 Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
|
||||||
- Fixed rpm to create /var/hermes
|
|
||||||
|
|
||||||
* Fri Apr 11 2007 Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
|
||||||
- Initial release
|
|
1197
docs/Doxyfile
1197
docs/Doxyfile
File diff suppressed because it is too large
Load diff
20
include/Proxy.h
Normal file
20
include/Proxy.h
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
// Proxy.h
|
||||||
|
#pragma once
|
||||||
|
#include <string>
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include <boost/asio/ssl.hpp>
|
||||||
|
|
||||||
|
#define SMTP_STATE_WAIT_FOR_HELO 0
|
||||||
|
#define SMTP_STATE_WAIT_FOR_MAILFROM 1
|
||||||
|
#define SMTP_STATE_WAIT_FOR_RCPTTO 2
|
||||||
|
#define SMTP_STATE_WAIT_FOR_DATA 3
|
||||||
|
|
||||||
|
class Proxy {
|
||||||
|
public:
|
||||||
|
Proxy();
|
||||||
|
void run(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* outside);
|
||||||
|
|
||||||
|
private:
|
||||||
|
boost::asio::io_service& io_service_;
|
||||||
|
boost::asio::ssl::context ssl_context;
|
||||||
|
};
|
16
include/SocketInterface.h
Normal file
16
include/SocketInterface.h
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
// SocketInterface.h
|
||||||
|
#pragma once
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class SocketInterface {
|
||||||
|
public:
|
||||||
|
virtual ~SocketInterface() = default;
|
||||||
|
virtual void connect(const std::string& host, unsigned short port) = 0;
|
||||||
|
virtual void writeLine(const std::string& data) = 0;
|
||||||
|
virtual std::string readLine() = 0;
|
||||||
|
virtual bool canRead(double timeout) = 0;
|
||||||
|
virtual bool isClosed() = 0;
|
||||||
|
virtual void close() = 0;
|
||||||
|
virtual void prepareSSL(bool incoming) = 0;
|
||||||
|
virtual void startSSL(bool incoming) = 0;
|
||||||
|
};
|
|
@ -38,7 +38,7 @@ class Spf
|
||||||
Spf();
|
Spf();
|
||||||
~Spf();
|
~Spf();
|
||||||
static void deinitialize();
|
static void deinitialize();
|
||||||
bool query(string,string,string);
|
bool query(const string&, const string&, const string&);
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif //SPF_H
|
#endif //SPF_H
|
|
@ -1,123 +0,0 @@
|
||||||
#!/usr/bin/perl -w
|
|
||||||
|
|
||||||
# this small script generates the Configfile class from the
|
|
||||||
# Configfile.cpp.in and Configfile.h.in. this way when we want
|
|
||||||
# to add a new option to the config file, we just have to put it
|
|
||||||
# on Configfile.tmpl and automagically it will appear on our code
|
|
||||||
# It will also generate an example hermesrc from the same info.
|
|
||||||
# 2007-04-17 Now it also generates an html document for our webpage
|
|
||||||
|
|
||||||
my $hvar="";
|
|
||||||
my $cppvar1="",$cppvar2="",$cppvar3="",$conf_example="",$htmlvar="";
|
|
||||||
|
|
||||||
open HTMLIN, "<../docs/hermes-options.html.in";
|
|
||||||
$htmltempl=join("",<HTMLIN>);
|
|
||||||
close HTMLIN;
|
|
||||||
|
|
||||||
while(<>)
|
|
||||||
{
|
|
||||||
chomp;
|
|
||||||
if(! /^#/ && ! /^\t*$/ && ! /^\*/)
|
|
||||||
{
|
|
||||||
s/^\s+//;s/\s+$//;
|
|
||||||
@_=split ",";
|
|
||||||
my $camelcased=&camel_case($_[1]);
|
|
||||||
my $type=$_[0];
|
|
||||||
$type="list<string>" if($type =~ /list/);
|
|
||||||
$hvar1.="$type $_[1];\n";
|
|
||||||
$hvar2.="$type& get$camelcased();\n";
|
|
||||||
if($type =~ /list/)
|
|
||||||
{
|
|
||||||
$cppvar1.="$_[1]=Configfile::parseAsList($_[2]);\n";
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
$cppvar1.="$_[1]=$_[2];\n";
|
|
||||||
}
|
|
||||||
$cppvar2.="PARSE_".uc($_[0])."(\"$_[1]\",$_[1])\n";
|
|
||||||
$cppvar3.="GET_VAR(get$camelcased,$_[1],$type&)\n";
|
|
||||||
$conf_example.="$_[1] = $_[2]\n\n";
|
|
||||||
my $htmltemp=$htmltempl;
|
|
||||||
$htmltemp =~ s/%type%/$_[0]/;
|
|
||||||
$htmltemp =~ s/%name%/$_[1]/g;
|
|
||||||
$htmltemp =~ s/%default%/$_[2]/;
|
|
||||||
$htmltemp =~ s/%explanation%/$htmlexpl/;
|
|
||||||
$htmlexpl="";
|
|
||||||
$htmlvar.=$htmltemp;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if(/^\*clean\*$/) # clean restarts our htmlexpl contents
|
|
||||||
{
|
|
||||||
$htmlexpl="";
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if(/^\*/)
|
|
||||||
{
|
|
||||||
s/^\*$//;
|
|
||||||
s/^\*/#/;
|
|
||||||
$conf_example.="$_\n";
|
|
||||||
chomp;
|
|
||||||
s/^#//;
|
|
||||||
s/>/>/;
|
|
||||||
$htmlexpl.="$_\n";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
chomp $cppvar1;
|
|
||||||
chomp $cppvar2;
|
|
||||||
chomp $cppvar3;
|
|
||||||
chomp $hvar1;
|
|
||||||
chomp $hvar2;
|
|
||||||
chomp $conf_example;
|
|
||||||
|
|
||||||
open CPPIN, "<../src/Configfile.cpp.in";
|
|
||||||
$cppstr=join("",<CPPIN>);
|
|
||||||
close CPPIN;
|
|
||||||
open CPPOUT, ">Configfile.cpp";
|
|
||||||
$cppstr =~ s/%templ_default_values%/$cppvar1/;
|
|
||||||
$cppstr =~ s/%templ_parsevars%/$cppvar2/;
|
|
||||||
$cppstr =~ s/%templ_getmethods%/$cppvar3/;
|
|
||||||
print CPPOUT $cppstr;
|
|
||||||
close CPPOUT;
|
|
||||||
|
|
||||||
open HIN, "<../src/Configfile.h.in";
|
|
||||||
$hstr=join("",<HIN>);
|
|
||||||
close HIN;
|
|
||||||
open HOUT, ">Configfile.h";
|
|
||||||
$hstr =~ s/%templ_privateattribs%/$hvar1/;
|
|
||||||
$hstr =~ s/%templ_publicmethods%/$hvar2/;
|
|
||||||
print HOUT $hstr;
|
|
||||||
close HOUT;
|
|
||||||
|
|
||||||
open RCEX, ">../dists/hermesrc.example";
|
|
||||||
print RCEX $conf_example;
|
|
||||||
close RCEX;
|
|
||||||
|
|
||||||
open HTML, ">../docs/hermes-options.html";
|
|
||||||
print HTML $htmlvar;
|
|
||||||
close HTML;
|
|
||||||
|
|
||||||
sub camel_case()
|
|
||||||
{
|
|
||||||
my $str=shift;
|
|
||||||
my $outstr="";
|
|
||||||
|
|
||||||
for($i=0;$i<length($str);$i++)
|
|
||||||
{
|
|
||||||
my $letter=substr($str,$i,1);
|
|
||||||
if($letter eq "_")
|
|
||||||
{
|
|
||||||
$i++;
|
|
||||||
$outstr.=uc(substr($str,$i,1));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
$outstr.=$letter;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ucfirst($outstr);
|
|
||||||
}
|
|
157
scripts/generate_config.py
Normal file
157
scripts/generate_config.py
Normal file
|
@ -0,0 +1,157 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
import sys
|
||||||
|
import string
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
|
||||||
|
def camel_case(str_):
|
||||||
|
"""Convert snake_case to CamelCase."""
|
||||||
|
return string.capwords(str_, "_").replace("_", "")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# Set up argument parser
|
||||||
|
parser = argparse.ArgumentParser(description='Generate configuration files for Hermes.')
|
||||||
|
parser.add_argument('input_template',
|
||||||
|
type=argparse.FileType('r'),
|
||||||
|
help='Input configuration template file')
|
||||||
|
parser.add_argument('--html-template',
|
||||||
|
default='',
|
||||||
|
help='Path to HTML template input file')
|
||||||
|
parser.add_argument('--cpp-template',
|
||||||
|
default='',
|
||||||
|
help='Path to C++ template input file')
|
||||||
|
parser.add_argument('--h-template',
|
||||||
|
default='',
|
||||||
|
help='Path to header template input file')
|
||||||
|
parser.add_argument('--output-cpp',
|
||||||
|
default='',
|
||||||
|
help='Output path for generated C++ file')
|
||||||
|
parser.add_argument('--output-h',
|
||||||
|
default='',
|
||||||
|
help='Output path for generated header file')
|
||||||
|
parser.add_argument('--output-example',
|
||||||
|
default='',
|
||||||
|
help='Output path for example configuration')
|
||||||
|
parser.add_argument('--output-html',
|
||||||
|
default='',
|
||||||
|
help='Output path for generated HTML documentation')
|
||||||
|
|
||||||
|
# Parse arguments
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
hvar1 = []
|
||||||
|
hvar2 = []
|
||||||
|
cppvar1 = []
|
||||||
|
cppvar2 = []
|
||||||
|
cppvar3 = []
|
||||||
|
conf_example = []
|
||||||
|
htmlvar = []
|
||||||
|
htmlexpl = ""
|
||||||
|
|
||||||
|
# Process input
|
||||||
|
for line in args.input_template:
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
if not line or line.startswith('#') or line.startswith('*'):
|
||||||
|
if line == '*clean*':
|
||||||
|
htmlexpl = ""
|
||||||
|
elif line.startswith('*'):
|
||||||
|
line = line.replace('*', '#').strip()
|
||||||
|
conf_example.append(line)
|
||||||
|
|
||||||
|
# Convert line for HTML
|
||||||
|
line_html = line.lstrip('#').replace('>', '>')
|
||||||
|
htmlexpl += line_html + "\n"
|
||||||
|
continue
|
||||||
|
|
||||||
|
parts = line.split(',')
|
||||||
|
parts = [p.strip() for p in parts]
|
||||||
|
|
||||||
|
type_str = parts[0]
|
||||||
|
var_name = parts[1]
|
||||||
|
default_val = parts[2]
|
||||||
|
|
||||||
|
# Modify type for lists
|
||||||
|
if 'list' in type_str:
|
||||||
|
type_str = 'list<string>'
|
||||||
|
|
||||||
|
camel_name = camel_case(var_name)
|
||||||
|
|
||||||
|
# Generate header variables
|
||||||
|
hvar1.append(f"{type_str} {var_name};")
|
||||||
|
hvar2.append(f"{type_str}& get{camel_name}();")
|
||||||
|
|
||||||
|
# Generate cpp variables
|
||||||
|
if 'list' in type_str:
|
||||||
|
cppvar1.append(f"{var_name} = Configfile::parseAsList({default_val});")
|
||||||
|
else:
|
||||||
|
cppvar1.append(f"{var_name} = {default_val};")
|
||||||
|
|
||||||
|
cppvar2.append(f"PARSE_{parts[0].upper()}(\"{var_name}\", {var_name})")
|
||||||
|
cppvar3.append(f"GET_VAR(get{camel_name}, {var_name}, {type_str}&)")
|
||||||
|
|
||||||
|
# Generate config example
|
||||||
|
conf_example.append(f"{var_name} = {default_val}")
|
||||||
|
|
||||||
|
# Generate HTML
|
||||||
|
if args.html_template:
|
||||||
|
html_templ = open(args.html_template, 'r').read()
|
||||||
|
html_temp = html_templ.replace('%type%', parts[0]) \
|
||||||
|
.replace('%name%', var_name) \
|
||||||
|
.replace('%default%', default_val) \
|
||||||
|
.replace('%explanation%', htmlexpl)
|
||||||
|
htmlvar.append(html_temp)
|
||||||
|
htmlexpl = ""
|
||||||
|
|
||||||
|
# Convert lists to newline-separated strings
|
||||||
|
hvar1 = '\n'.join(hvar1)
|
||||||
|
hvar2 = '\n'.join(hvar2)
|
||||||
|
cppvar1 = '\n'.join(cppvar1)
|
||||||
|
cppvar2 = '\n'.join(cppvar2)
|
||||||
|
cppvar3 = '\n'.join(cppvar3)
|
||||||
|
conf_example = '\n\n'.join(conf_example)
|
||||||
|
htmlvar = ''.join(htmlvar)
|
||||||
|
|
||||||
|
# Write Configfile.cpp
|
||||||
|
if args.cpp_template and args.output_cpp:
|
||||||
|
try:
|
||||||
|
cpp_str = open(args.cpp_template, 'r').read()
|
||||||
|
cpp_str = cpp_str.replace('%templ_default_values%', cppvar1) \
|
||||||
|
.replace('%templ_parsevars%', cppvar2) \
|
||||||
|
.replace('%templ_getmethods%', cppvar3)
|
||||||
|
|
||||||
|
os.makedirs(os.path.dirname(args.output_cpp), exist_ok=True)
|
||||||
|
with open(args.output_cpp, 'w') as f:
|
||||||
|
f.write(cpp_str)
|
||||||
|
except FileNotFoundError:
|
||||||
|
print(f"Error: C++ template file {args.cpp_template} not found.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Write Configfile.h
|
||||||
|
if args.h_template and args.output_h:
|
||||||
|
try:
|
||||||
|
h_str = open(args.h_template, 'r').read()
|
||||||
|
h_str = h_str.replace('%templ_privateattribs%', hvar1) \
|
||||||
|
.replace('%templ_publicmethods%', hvar2)
|
||||||
|
|
||||||
|
os.makedirs(os.path.dirname(args.output_h), exist_ok=True)
|
||||||
|
with open(args.output_h, 'w') as f:
|
||||||
|
f.write(h_str)
|
||||||
|
except FileNotFoundError:
|
||||||
|
print(f"Error: Header template file {args.h_template} not found.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Write hermesrc.example
|
||||||
|
if args.output_example:
|
||||||
|
os.makedirs(os.path.dirname(args.output_example), exist_ok=True)
|
||||||
|
with open(args.output_example, 'w') as f:
|
||||||
|
f.write(conf_example)
|
||||||
|
|
||||||
|
# Write hermes-options.html
|
||||||
|
if args.output_html and htmlvar:
|
||||||
|
os.makedirs(os.path.dirname(args.output_html), exist_ok=True)
|
||||||
|
with open(args.output_html, 'w') as f:
|
||||||
|
f.write(htmlvar)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
|
@ -108,17 +108,6 @@ void Configfile::validateConfig()
|
||||||
throw Exception("Directory "+chroot+" doesn't exist, can't chroot to it.",__FILE__,__LINE__);
|
throw Exception("Directory "+chroot+" doesn't exist, can't chroot to it.",__FILE__,__LINE__);
|
||||||
#endif //WIN32
|
#endif //WIN32
|
||||||
|
|
||||||
//check if we have submit_stats on but no user and password
|
|
||||||
if(getSubmitStats()&&(""==getSubmitStatsUsername()||""==getSubmitStatsPassword()))
|
|
||||||
throw Exception("You have configured hermes to send stats, but have not configured a username or password.\n"
|
|
||||||
"If you don't have one, go to http://www.hermes-project.com and register there",__FILE__,__LINE__);
|
|
||||||
|
|
||||||
#ifndef HAVE_SSL
|
|
||||||
//check if we have activated submit_stats_ssl not having ssl activated
|
|
||||||
if(getSubmitStatsSsl())
|
|
||||||
throw Exception("You have configured stats submission through SSL, but hermes was compiled without SSL support",__FILE__,__LINE__);
|
|
||||||
#endif //HAVE_SSL
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
string Configfile::parseAsString(string str)
|
string Configfile::parseAsString(string str)
|
||||||
|
|
|
@ -9,7 +9,6 @@
|
||||||
*
|
*
|
||||||
|
|
||||||
*clean*
|
*clean*
|
||||||
#ifndef WIN32
|
|
||||||
|
|
||||||
* whether to fork to the background. initscripts require
|
* whether to fork to the background. initscripts require
|
||||||
* this to be true most of the time.
|
* this to be true most of the time.
|
||||||
|
@ -35,7 +34,6 @@ string,group,"nobody"
|
||||||
* if you set background=true above, this will write the pid
|
* if you set background=true above, this will write the pid
|
||||||
* of the forked hermes, not the original.
|
* of the forked hermes, not the original.
|
||||||
string,pid_file,"/var/run/hermes.pid"
|
string,pid_file,"/var/run/hermes.pid"
|
||||||
#endif //WIN32
|
|
||||||
|
|
||||||
* the port where hermes will listen for new connection.
|
* the port where hermes will listen for new connection.
|
||||||
* if you are going to use a port lower than 1024 (almost always,
|
* if you are going to use a port lower than 1024 (almost always,
|
||||||
|
@ -58,11 +56,7 @@ int,server_port,2525
|
||||||
* database file to use.
|
* database file to use.
|
||||||
* if you are chrooting, the path is relative to the chroot:
|
* if you are chrooting, the path is relative to the chroot:
|
||||||
* real filepath = chroot + database_file
|
* real filepath = chroot + database_file
|
||||||
#ifdef WIN32
|
|
||||||
string,database_file,"greylisting.db"
|
|
||||||
#else
|
|
||||||
string,database_file,"/var/hermes/greylisting.db"
|
string,database_file,"/var/hermes/greylisting.db"
|
||||||
#endif //WIN32
|
|
||||||
|
|
||||||
* whether to use greylisting.
|
* whether to use greylisting.
|
||||||
* greylisting will slightly delay your emails (configurable, see below)
|
* greylisting will slightly delay your emails (configurable, see below)
|
||||||
|
@ -120,13 +114,6 @@ bool,add_status_header,false
|
||||||
* time to delay the initial SMTP banner
|
* time to delay the initial SMTP banner
|
||||||
int,banner_delay_time,5
|
int,banner_delay_time,5
|
||||||
|
|
||||||
#ifdef REALLY_VERBOSE_DEBUG
|
|
||||||
* email to notify exceptions to.
|
|
||||||
* CAVEAT: the code that does this is VERY BUGGY and VERY VERBOSE, don't use unless you
|
|
||||||
* are a developer looking for a bug.
|
|
||||||
string,notify_to,""
|
|
||||||
#endif //REALLY_VERBOSE_DEBUG
|
|
||||||
|
|
||||||
* greylisting options.
|
* greylisting options.
|
||||||
*
|
*
|
||||||
*clean*
|
*clean*
|
||||||
|
@ -142,56 +129,12 @@ int,initial_blacklist,5
|
||||||
* 36 is a magic number, is the maximum days between a day and the same day next month
|
* 36 is a magic number, is the maximum days between a day and the same day next month
|
||||||
int,whitelist_expiry,36
|
int,whitelist_expiry,36
|
||||||
|
|
||||||
* whether to submit stats.
|
|
||||||
bool,submit_stats,true
|
|
||||||
|
|
||||||
* should stats be submited using SSL?
|
|
||||||
* recomended, but some people will compile without ssl.
|
|
||||||
#ifdef HAVE_SSL
|
|
||||||
bool,submit_stats_ssl,true
|
|
||||||
#else
|
|
||||||
bool,submit_stats_ssl,false
|
|
||||||
#endif //HAVE_SSL
|
|
||||||
|
|
||||||
* username (used to submit stats).
|
|
||||||
* you can register on http://www.hermes-project.com
|
|
||||||
string,submit_stats_username,"anonymous"
|
|
||||||
|
|
||||||
* password
|
|
||||||
string,submit_stats_password,"anonymous"
|
|
||||||
|
|
||||||
* log level:
|
* log level:
|
||||||
* 0: log only errors
|
* 0: log only errors
|
||||||
* 1: log errors and information (default)
|
* 1: log errors and information (default)
|
||||||
* 2: debug (passwords might be written in plaintext with this option, so use with care)
|
* 2: debug (passwords might be written in plaintext with this option, so use with care)
|
||||||
int,log_level,1
|
int,log_level,1
|
||||||
|
|
||||||
#if LOGGER_CLASS==FileLogger
|
|
||||||
* if you are using the filelogger, which file to log to.
|
|
||||||
string,file_logger_filename,"hermes.log"
|
|
||||||
|
|
||||||
* whether to keep the logger file locked between writes
|
|
||||||
bool,keep_file_locked,true
|
|
||||||
|
|
||||||
* frequency for log rotating in minutes
|
|
||||||
* default is 1440 (1 day)
|
|
||||||
* 0 means no rotation
|
|
||||||
int,log_rotation_frequency,1440
|
|
||||||
|
|
||||||
* format for the logfile rotation
|
|
||||||
* if you are using logfile rotation, file_logger represents the filename
|
|
||||||
* to which the logger will write, while this is the name files will get
|
|
||||||
* when rotated
|
|
||||||
* you can use the following variables:
|
|
||||||
* %%year%% - current year (4 digits)
|
|
||||||
* %%month%% - current month
|
|
||||||
* %%day%% - current day
|
|
||||||
* %%hour%% - current hour
|
|
||||||
* %%minute%% - current minute
|
|
||||||
* all of them are zero-padded
|
|
||||||
string,rotate_filename,"hermes-%%year%%-%%month%%-%%day%%-%%hour%%:%%minute%%.log"
|
|
||||||
#endif //LOGGER_CLASS==FileLogger
|
|
||||||
|
|
||||||
* whether to clean the database file and send stats.
|
* whether to clean the database file and send stats.
|
||||||
* if you have two instances of hermes running (for example one for smtp and other for smtps)
|
* if you have two instances of hermes running (for example one for smtp and other for smtps)
|
||||||
* you want to configure all of them but one to use clean_db=false.
|
* you want to configure all of them but one to use clean_db=false.
|
||||||
|
@ -201,9 +144,7 @@ string,rotate_filename,"hermes-%%year%%-%%month%%-%%day%%-%%hour%%:%%minute%%.lo
|
||||||
* will be left hanging around without any use.
|
* will be left hanging around without any use.
|
||||||
bool,clean_db,true
|
bool,clean_db,true
|
||||||
|
|
||||||
#ifdef HAVE_SSL
|
|
||||||
* ssl-related config options
|
* ssl-related config options
|
||||||
* NOTE: this NEEDS the openssl library
|
|
||||||
*
|
*
|
||||||
*clean*
|
*clean*
|
||||||
|
|
||||||
|
@ -235,7 +176,6 @@ string,certificate_file,"/etc/hermes/hermes.cert"
|
||||||
* # openssl dhparam -out dhparam.pem <numbits>
|
* # openssl dhparam -out dhparam.pem <numbits>
|
||||||
* (replace <numbits> with the number of bits suitable for you, e.G. 1024)
|
* (replace <numbits> with the number of bits suitable for you, e.G. 1024)
|
||||||
string,dhparams_file,""
|
string,dhparams_file,""
|
||||||
#endif //HAVE_SSL
|
|
||||||
|
|
||||||
* whether to add headers to the email sent or no.
|
* whether to add headers to the email sent or no.
|
||||||
* to be rfc compatible this HAS to be true, but if you set to false, no one will know you are using hermes
|
* to be rfc compatible this HAS to be true, but if you set to false, no one will know you are using hermes
|
||||||
|
@ -262,11 +202,7 @@ bool,check_helo_against_reverse,false
|
||||||
|
|
||||||
* whether to query the spf record for the incoming domain.
|
* whether to query the spf record for the incoming domain.
|
||||||
* should help, enable if you have libspf (if you don't, install it and recompile)
|
* should help, enable if you have libspf (if you don't, install it and recompile)
|
||||||
#ifdef HAVE_SPF
|
|
||||||
bool,query_spf,true
|
bool,query_spf,true
|
||||||
#else
|
|
||||||
bool,query_spf,false
|
|
||||||
#endif //HAVE_SPF
|
|
||||||
|
|
||||||
* return temporary error instead of permanent error.
|
* return temporary error instead of permanent error.
|
||||||
* Currently, this only applies to SPF and DNSBL rejected email
|
* Currently, this only applies to SPF and DNSBL rejected email
|
||||||
|
|
548
src/Proxy.cpp
548
src/Proxy.cpp
|
@ -1,338 +1,258 @@
|
||||||
/**
|
// Proxy.cpp
|
||||||
* hermes antispam proxy
|
|
||||||
* Copyright (C) 2006, 2007 Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
|
||||||
*
|
|
||||||
* 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 2 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, write to the Free Software Foundation, Inc.,
|
|
||||||
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
||||||
*
|
|
||||||
* @author Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
|
||||||
*/
|
|
||||||
#include "Proxy.h"
|
#include "Proxy.h"
|
||||||
|
#include "HostnameResolver.h"
|
||||||
|
#include <iostream>
|
||||||
|
#include <thread>
|
||||||
|
#include <format>
|
||||||
|
#include <boost/asio/ssl.hpp>
|
||||||
|
#include "Utils.h"
|
||||||
|
#include "Configfile.h"
|
||||||
|
|
||||||
extern LOGGER_CLASS hermes_log;
|
|
||||||
extern Configfile cfg;
|
extern Configfile cfg;
|
||||||
|
|
||||||
void Proxy::setOutside(Socket& p_outside)
|
void Proxy::run(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* outside) {
|
||||||
{
|
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* inside;
|
||||||
outside=p_outside;
|
// Original comments and variables retained
|
||||||
}
|
std::string from = "";
|
||||||
|
std::string to = "";
|
||||||
|
std::string ehlostr = "";
|
||||||
|
std::string resolvedname = "";
|
||||||
|
unsigned char last_state = SMTP_STATE_WAIT_FOR_HELO;
|
||||||
|
long unimplemented_requests = 0;
|
||||||
|
|
||||||
/**
|
#ifdef HAVE_SPF
|
||||||
* this function is the main part of the program, it just sniffs traffic
|
SpfChecker spf_checker;
|
||||||
* between server and client and acts acording to the following diagram:
|
#endif
|
||||||
*
|
|
||||||
* TODO: fill diagram and point to website with graphical version
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
void Proxy::run(string &peer_address)
|
|
||||||
{
|
|
||||||
#ifdef HAVE_SPF
|
|
||||||
Spf spf_checker;
|
|
||||||
#endif //HAVE_SPF
|
|
||||||
|
|
||||||
string from="";
|
try {
|
||||||
string to="";
|
// Resolve hostname using the Boost resolver
|
||||||
string ehlostr="";
|
try {
|
||||||
string resolvedname="";
|
resolvedname = HostnameResolver::resolveHostname(peer_address);
|
||||||
unsigned char last_state=SMTP_STATE_WAIT_FOR_HELO;
|
|
||||||
long unimplemented_requests=0;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
bool throttled=cfg.getThrottle(); //we start with a throttled connection
|
|
||||||
bool authenticated=false; //we start with a non-authenticated connection
|
|
||||||
bool esmtp=false;
|
|
||||||
string strtemp;
|
|
||||||
string hermes_status="unknown";
|
|
||||||
|
|
||||||
//check whitelist
|
|
||||||
if(!cfg.getDnsWhitelistDomains().empty()&&Utils::listed_on_dns_lists(cfg.getDnsWhitelistDomains(),cfg.getDnsWhitelistPercentage(),peer_address))
|
|
||||||
{
|
|
||||||
authenticated=true;
|
|
||||||
hermes_status="whitelisted";
|
|
||||||
if(true==cfg.getWhitelistedDisablesEverything())
|
|
||||||
throttled=false;
|
|
||||||
}
|
|
||||||
if(true==cfg.getWhitelistedDisablesEverything()&&Utils::whitelisted(cfg.getDatabaseFile(),peer_address))
|
|
||||||
{
|
|
||||||
throttled=false;
|
|
||||||
authenticated=true;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if(false==cfg.getAllowDataBeforeBanner())
|
|
||||||
{
|
|
||||||
sleep(cfg.getBannerDelayTime());
|
|
||||||
if(outside.canRead(0)) //if we have data waiting before the server gives us a 220 then quit, it's spam
|
|
||||||
{
|
|
||||||
LINF("421 (data_before_banner) (ip:"+peer_address+")");
|
|
||||||
sleep(20); // but first let's annoy spammers once more
|
|
||||||
outside.writeLine("421 Stop sending data before we show you the banner");
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
catch (const std::exception& e) {
|
||||||
}
|
std::cerr << std::format("Hostname resolution error: {}", e.what()) << std::endl;
|
||||||
|
resolvedname = "";
|
||||||
inside.init();
|
|
||||||
inside.connect(cfg.getServerHost(),cfg.getServerPort());
|
|
||||||
#ifdef HAVE_SSL
|
|
||||||
if(cfg.getOutgoingSsl())
|
|
||||||
{
|
|
||||||
inside.prepareSSL(false);
|
|
||||||
inside.startSSL(false);
|
|
||||||
}
|
|
||||||
if(cfg.getIncomingSsl())
|
|
||||||
{
|
|
||||||
outside.prepareSSL(true);
|
|
||||||
outside.startSSL(true);
|
|
||||||
}
|
|
||||||
#endif //HAVE_SSL
|
|
||||||
|
|
||||||
while(!outside.isClosed()&&!inside.isClosed())
|
|
||||||
{
|
|
||||||
if(outside.canRead(0.2)) //client wants to send something to server
|
|
||||||
{
|
|
||||||
strtemp=outside.readLine();
|
|
||||||
if(outside.isClosed())
|
|
||||||
return;
|
|
||||||
if(strtemp.length()>10&&"mail from:"==Utils::strtolower(strtemp.substr(0,10)))
|
|
||||||
{
|
|
||||||
from=Utils::getmail(strtemp);
|
|
||||||
last_state=SMTP_STATE_WAIT_FOR_RCPTTO;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if("ehlo"==Utils::strtolower(strtemp.substr(0,4)))
|
// Configure SSL contexts
|
||||||
esmtp=true;
|
boost::asio::ssl::context ssl_context(boost::asio::ssl::context::tlsv12);
|
||||||
|
ssl_context.set_verify_mode(boost::asio::ssl::verify_none);
|
||||||
|
|
||||||
if(strtemp.length()>4&&("ehlo"==Utils::strtolower(strtemp.substr(0,4))||"helo"==Utils::strtolower(strtemp.substr(0,4))))
|
bool throttled = cfg.getThrottle(); // Start with a throttled connection
|
||||||
{
|
bool authenticated = false; // Start with a non-authenticated connection
|
||||||
ehlostr=Utils::trim(strtemp.substr(5));
|
bool esmtp = false;
|
||||||
last_state=SMTP_STATE_WAIT_FOR_MAILFROM;
|
std::string strtemp;
|
||||||
}
|
std::string hermes_status = "unknown";
|
||||||
|
|
||||||
if(strtemp.length()>8&&"rcpt to:"==Utils::strtolower(strtemp.substr(0,8)))
|
// Check whitelist
|
||||||
{
|
if (!cfg.getDnsWhitelistDomains().empty() &&
|
||||||
string strlog="";
|
Utils::listed_on_dns_lists(cfg.getDnsWhitelistDomains(), cfg.getDnsWhitelistPercentage(), peer_address)) {
|
||||||
string code="";
|
authenticated = true;
|
||||||
string mechanism="";
|
hermes_status = "whitelisted";
|
||||||
string message="";
|
if (cfg.getWhitelistedDisablesEverything()) {
|
||||||
|
throttled = false;
|
||||||
to=Utils::getmail(strtemp);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
resolvedname=Socket::resolveInverselyToString(peer_address);
|
|
||||||
}
|
|
||||||
catch(Exception &e)
|
|
||||||
{
|
|
||||||
resolvedname="";
|
|
||||||
}
|
|
||||||
|
|
||||||
strlog="from "+from+" (ip:"+peer_address+", hostname:"+resolvedname+", "+(esmtp?"ehlo":"helo")+":"+ehlostr+") -> to "+to;
|
|
||||||
|
|
||||||
//check greylisting
|
|
||||||
if(cfg.getGreylist()&&!authenticated&&Utils::greylist(cfg.getDatabaseFile(),peer_address,from,to))
|
|
||||||
{
|
|
||||||
//should we greylist¿? if we have to, quit and then sleep 20 seconds before closing the connection
|
|
||||||
code="421";
|
|
||||||
mechanism="greylist";
|
|
||||||
message=code+" Greylisted!! Please try again in a few minutes.";
|
|
||||||
LINF("checking " + mechanism);
|
|
||||||
}
|
|
||||||
#ifdef HAVE_SPF
|
|
||||||
else if(cfg.getQuerySpf()&&!authenticated&&!spf_checker.query(peer_address,ehlostr,from))
|
|
||||||
{
|
|
||||||
hermes_status="spf-failed";
|
|
||||||
if(cfg.getAddStatusHeader())
|
|
||||||
code="250";
|
|
||||||
else
|
|
||||||
code=cfg.getReturnTempErrorOnReject()?"421":"550";
|
|
||||||
mechanism="spf";
|
|
||||||
message=code+" You do not seem to be allowed to send email for that particular domain.";
|
|
||||||
LINF("checking " + mechanism);
|
|
||||||
}
|
|
||||||
#endif //HAVE_SPF
|
|
||||||
//check blacklist
|
|
||||||
else if(!authenticated&&Utils::blacklisted(cfg.getDatabaseFile(),peer_address,to))
|
|
||||||
{
|
|
||||||
code=cfg.getReturnTempErrorOnReject()?"421":"550";
|
|
||||||
mechanism="allowed-domain-per-ip";
|
|
||||||
message=code+" You do not seem to be allowed to send email to that particular domain from that address.";
|
|
||||||
LINF("checking " + mechanism);
|
|
||||||
}
|
|
||||||
//check rbl
|
|
||||||
else if(!cfg.getDnsBlacklistDomains().empty()&&!authenticated&&Utils::listed_on_dns_lists(cfg.getDnsBlacklistDomains(),cfg.getDnsBlacklistPercentage(),peer_address))
|
|
||||||
{
|
|
||||||
hermes_status="blacklisted";
|
|
||||||
if(cfg.getAddStatusHeader())
|
|
||||||
code="250";
|
|
||||||
else
|
|
||||||
code=cfg.getReturnTempErrorOnReject()?"421":"550";
|
|
||||||
mechanism="dnsbl";
|
|
||||||
message=code+" You are listed on some DNS blacklists. Get delisted before trying to send us email.";
|
|
||||||
LINF("checking " + mechanism);
|
|
||||||
}
|
|
||||||
else if(cfg.getRejectNoReverseResolution()&&!authenticated&&""==resolvedname)
|
|
||||||
{
|
|
||||||
code=cfg.getReturnTempErrorOnReject()?"421":"550";
|
|
||||||
mechanism="no reverse resolution";
|
|
||||||
message=code+" Your IP address does not resolve to a hostname.";
|
|
||||||
LINF("checking " + mechanism);
|
|
||||||
}
|
|
||||||
else if(cfg.getCheckHeloAgainstReverse()&&!authenticated&&ehlostr!=resolvedname)
|
|
||||||
{
|
|
||||||
code=cfg.getReturnTempErrorOnReject()?"421":"550";
|
|
||||||
mechanism="helo differs from resolved name";
|
|
||||||
message=code+" Your IP hostname doesn't match your envelope hostname.";
|
|
||||||
LINF("checking " + mechanism);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
code="250";
|
|
||||||
|
|
||||||
if(""!=mechanism)
|
|
||||||
strlog.insert(0,"("+mechanism+") ");
|
|
||||||
strlog.insert(0,code+" ");
|
|
||||||
|
|
||||||
//log the connection
|
|
||||||
LINF(strlog);
|
|
||||||
|
|
||||||
//if we didn't accept the email, punish spammers
|
|
||||||
if("250"!=code)
|
|
||||||
{
|
|
||||||
inside.writeLine("QUIT");
|
|
||||||
inside.close(); //close the socket now and leave server alone
|
|
||||||
sleep(20);
|
|
||||||
outside.writeLine(message);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
last_state=SMTP_STATE_WAIT_FOR_DATA;
|
|
||||||
}
|
|
||||||
|
|
||||||
if("starttls"==Utils::strtolower(strtemp.substr(0,8)))
|
|
||||||
{
|
|
||||||
//if we have ssl then accept starttls, if not politely say fuck you
|
|
||||||
#ifdef HAVE_SSL
|
|
||||||
try
|
|
||||||
{
|
|
||||||
outside.prepareSSL(true);
|
|
||||||
LINF("STARTTLS issued by remote, TLS enabled");
|
|
||||||
outside.writeLine("220 You can speak now, line is secure!!");
|
|
||||||
outside.startSSL(true);
|
|
||||||
}
|
}
|
||||||
catch(Exception &e)
|
}
|
||||||
{
|
|
||||||
LINF("STARTTLS issued by remote, but enableSSL failed!");
|
if (cfg.getWhitelistedDisablesEverything() && Utils::whitelisted(cfg.getDatabaseFile(), peer_address)) {
|
||||||
LERR(e);
|
throttled = false;
|
||||||
outside.writeLine("454 Tried to enable SSL but failed");
|
authenticated = true;
|
||||||
|
} else {
|
||||||
|
if (!cfg.getAllowDataBeforeBanner()) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(cfg.getBannerDelayTime()));
|
||||||
|
|
||||||
|
// Check if data is waiting before server banner
|
||||||
|
boost::system::error_code ec;
|
||||||
|
size_t available = outside->lowest_layer().available(ec);
|
||||||
|
if (ec || available > 0) {
|
||||||
|
std::cout << std::format("421 (data_before_banner) (ip:{})\n", peer_address);
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(20));
|
||||||
|
|
||||||
|
// Write rejection message
|
||||||
|
std::string rejection_msg = "421 Stop sending data before we show you the banner\r\n";
|
||||||
|
boost::asio::write(outside->lowest_layer(), boost::asio::buffer(rejection_msg), ec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#else
|
|
||||||
outside.writeLine("454 TLS temporarily not available");
|
|
||||||
LINF("STARTTLS issued by remote, TLS was not enabled because this build lacks SSL support");
|
|
||||||
#endif //HAVE_SSL
|
|
||||||
strtemp="";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(strtemp.length())
|
// Connect to the inside server
|
||||||
inside.writeLine(strtemp);
|
boost::asio::ip::tcp::resolver resolver(io_service_);
|
||||||
}
|
boost::asio::ip::tcp::resolver::results_type endpoints =
|
||||||
|
resolver.resolve(cfg.getServerHost(), std::to_string(cfg.getServerPort()));
|
||||||
|
|
||||||
if(inside.canRead(0.2)) //server wants to send something to client
|
boost::asio::connect(inside.lowest_layer(), endpoints);
|
||||||
{
|
|
||||||
strtemp=inside.readLine();
|
|
||||||
if(inside.isClosed())
|
|
||||||
return;
|
|
||||||
string code=strtemp.substr(0,3); //all responses by the server start with a code
|
|
||||||
|
|
||||||
if("354"==code) //354 -> you can start sending data, unthrottle now and read binary-safe
|
// SSL setup
|
||||||
{
|
if (cfg.getOutgoingSsl()) {
|
||||||
string endofdata="";
|
inside.set_verify_mode(boost::asio::ssl::verify_none);
|
||||||
ssize_t bytes_read=0;
|
inside.handshake(boost::asio::ssl::stream_base::client);
|
||||||
char buffer[4097];
|
|
||||||
|
|
||||||
outside.writeLine(strtemp);
|
|
||||||
strtemp="";
|
|
||||||
string ssltls="";
|
|
||||||
#ifdef HAVE_SSL
|
|
||||||
if (outside.is_ssl_enabled())
|
|
||||||
ssltls=" (SSL/TLS)";
|
|
||||||
#endif //HAVE_SSL
|
|
||||||
|
|
||||||
if(cfg.getAddHeaders())
|
|
||||||
{
|
|
||||||
inside.writeLine("Received: from "+ehlostr+" ("+peer_address+")");
|
|
||||||
inside.writeLine(" by "+Utils::gethostname(outside.getFD())+" with "+(esmtp?"ESTMP":"SMTP")+ssltls+" via TCP; "+Utils::rfc2821_date());
|
|
||||||
inside.writeLine("X-Anti-Spam-Proxy: Proxied by Hermes [www.hermes-project.com]");
|
|
||||||
if(cfg.getAddStatusHeader())
|
|
||||||
inside.writeLine("X-Hermes-Status: "+hermes_status);
|
|
||||||
}
|
|
||||||
do
|
|
||||||
{
|
|
||||||
bytes_read=outside.readBytes(buffer,sizeof(buffer)-1);
|
|
||||||
if(bytes_read<1)
|
|
||||||
throw NetworkException("Problem reading DATA contents, recv returned "+Utils::inttostr(bytes_read),__FILE__,__LINE__);
|
|
||||||
buffer[bytes_read]='\0';
|
|
||||||
inside.writeBytes(buffer,bytes_read);
|
|
||||||
if(bytes_read<5)
|
|
||||||
endofdata+=string(buffer);
|
|
||||||
else
|
|
||||||
endofdata=string(buffer+bytes_read-5);
|
|
||||||
if(endofdata.length()>5)
|
|
||||||
endofdata=endofdata.substr(endofdata.length()-5);
|
|
||||||
}
|
|
||||||
while(endofdata!="\r\n.\r\n"/*&&endofdata.length()>3&&endofdata.substr(2)!="\n.\n"&&endofdata.substr(2)!="\r.\r"*/);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if("235"==code) //235 -> you are correctly authenticated, unthrottle & authenticate
|
if (cfg.getIncomingSsl()) {
|
||||||
{
|
outside->set_verify_mode(boost::asio::ssl::verify_none);
|
||||||
throttled=false;
|
outside->handshake(boost::asio::ssl::stream_base::server);
|
||||||
authenticated=true;
|
|
||||||
hermes_status="authenticated";
|
|
||||||
}
|
|
||||||
if("250-pipelining"==Utils::strtolower(strtemp)||"250-chunking"==Utils::strtolower(strtemp)) //this solves our problems with pipelining-enabled servers
|
|
||||||
strtemp="";
|
|
||||||
|
|
||||||
//this is a special case, we can't just ignore the line if it's the last line (doesn't have the dash after the code)
|
|
||||||
//so we just say we support an imaginary extension (noextension).
|
|
||||||
//caveat: this makes us identificable, so, if you can, configure your smtp server to either don't support pipelining
|
|
||||||
//or to not advertise it as the last capability.
|
|
||||||
if("250 pipelining"==Utils::strtolower(strtemp)||"250 chunking"==Utils::strtolower(strtemp))
|
|
||||||
strtemp="250 x-noextension";
|
|
||||||
|
|
||||||
//try to annoy spammers who send us too many senseless commands by delaying their connection a lot
|
|
||||||
if("502"==code) //502 unimplemented -> count them, if bigger than a certain number, terminate connection
|
|
||||||
{
|
|
||||||
if(cfg.getNumberOfUnimplementedCommandsAllowed()!=-1&&++unimplemented_requests>cfg.getNumberOfUnimplementedCommandsAllowed())
|
|
||||||
{
|
|
||||||
inside.writeLine("QUIT");
|
|
||||||
inside.close(); //close the socket now and leave server alone
|
|
||||||
sleep(60);
|
|
||||||
outside.writeLine("502 Too many unimplemented commands, closing connection");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(strtemp.length())
|
// Communication buffers
|
||||||
outside.writeLine(strtemp);
|
std::vector<char> read_buffer(4096);
|
||||||
}
|
boost::system::error_code ec;
|
||||||
|
|
||||||
if(throttled)
|
// Main loop for communication
|
||||||
sleep(cfg.getThrottlingTime()); //we take 1 second between each command to make spammers angry
|
while (!outside->lowest_layer().is_open() || !inside.lowest_layer().is_open()) {
|
||||||
|
// Check if the client wants to send something to the server
|
||||||
|
size_t client_available = outside->lowest_layer().available(ec);
|
||||||
|
if (client_available > 0) {
|
||||||
|
size_t bytes_read = outside->read_some(boost::asio::buffer(read_buffer), ec);
|
||||||
|
strtemp = std::string(read_buffer.begin(), read_buffer.begin() + bytes_read);
|
||||||
|
|
||||||
|
if (strtemp.length() > 10 && "mail from:" == Utils::strtolower(strtemp.substr(0, 10))) {
|
||||||
|
from = Utils::getmail(strtemp);
|
||||||
|
last_state = SMTP_STATE_WAIT_FOR_RCPTTO;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("ehlo" == Utils::strtolower(strtemp.substr(0, 4))) esmtp = true;
|
||||||
|
|
||||||
|
if (strtemp.length() > 4 && ("ehlo" == Utils::strtolower(strtemp.substr(0, 4)) ||
|
||||||
|
"helo" == Utils::strtolower(strtemp.substr(0, 4)))) {
|
||||||
|
ehlostr = Utils::trim(strtemp.substr(5));
|
||||||
|
last_state = SMTP_STATE_WAIT_FOR_MAILFROM;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RCPT TO handling with comprehensive checks
|
||||||
|
if (strtemp.length() > 8 && "rcpt to:" == Utils::strtolower(strtemp.substr(0, 8))) {
|
||||||
|
std::string mechanism = "";
|
||||||
|
std::string message = "";
|
||||||
|
to = Utils::getmail(strtemp);
|
||||||
|
|
||||||
|
// Construct log string using std::format
|
||||||
|
std::string strlog = std::format(
|
||||||
|
"from {} (ip:{}, hostname:{}, {} {}:{}) -> to {}",
|
||||||
|
from,
|
||||||
|
peer_address,
|
||||||
|
resolvedname,
|
||||||
|
(esmtp ? "ehlo" : "helo"),
|
||||||
|
ehlostr,
|
||||||
|
to
|
||||||
|
);
|
||||||
|
|
||||||
|
// Greylisting check
|
||||||
|
std::string code = "250";
|
||||||
|
if (cfg.getGreylist() && !authenticated &&
|
||||||
|
Utils::greylist(cfg.getDatabaseFile(), peer_address, from, to)) {
|
||||||
|
code = "421";
|
||||||
|
mechanism = "greylist";
|
||||||
|
message = std::format("{} Greylisted!! Please try again in a few minutes.", code);
|
||||||
|
std::cout << std::format("checking {}\n", mechanism);
|
||||||
|
}
|
||||||
|
// SPF Check
|
||||||
|
#ifdef HAVE_SPF
|
||||||
|
else if (cfg.getQuerySpf() && !authenticated &&
|
||||||
|
!spf_checker.query(peer_address, ehlostr, from)) {
|
||||||
|
code = cfg.getAddStatusHeader() ? "250" :
|
||||||
|
(cfg.getReturnTempErrorOnReject() ? "421" : "550");
|
||||||
|
mechanism = "spf";
|
||||||
|
message = std::format(
|
||||||
|
"{} You do not seem to be allowed to send email for that particular domain.",
|
||||||
|
code
|
||||||
|
);
|
||||||
|
std::cout << std::format("checking {}\n", mechanism);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
// Blacklist check
|
||||||
|
else if (!authenticated &&
|
||||||
|
Utils::blacklisted(cfg.getDatabaseFile(), peer_address, to)) {
|
||||||
|
code = cfg.getReturnTempErrorOnReject() ? "421" : "550";
|
||||||
|
mechanism = "allowed-domain-per-ip";
|
||||||
|
message = std::format(
|
||||||
|
"{} You do not seem to be allowed to send email to that particular domain from that address.",
|
||||||
|
code
|
||||||
|
);
|
||||||
|
std::cout << std::format("checking {}\n", mechanism);
|
||||||
|
}
|
||||||
|
// DNS Blacklist check
|
||||||
|
else if (!cfg.getDnsBlacklistDomains().empty() && !authenticated &&
|
||||||
|
Utils::listed_on_dns_lists(cfg.getDnsBlacklistDomains(),
|
||||||
|
cfg.getDnsBlacklistPercentage(),
|
||||||
|
peer_address)) {
|
||||||
|
code = cfg.getAddStatusHeader() ? "250" :
|
||||||
|
(cfg.getReturnTempErrorOnReject() ? "421" : "550");
|
||||||
|
mechanism = "dnsbl";
|
||||||
|
message = std::format(
|
||||||
|
"{} You are listed on some DNS blacklists. Get delisted before trying to send us email.",
|
||||||
|
code
|
||||||
|
);
|
||||||
|
std::cout << std::format("checking {}\n", mechanism);
|
||||||
|
}
|
||||||
|
// Reverse DNS check
|
||||||
|
else if (cfg.getRejectNoReverseResolution() && !authenticated && resolvedname.empty()) {
|
||||||
|
code = cfg.getReturnTempErrorOnReject() ? "421" : "550";
|
||||||
|
mechanism = "no reverse resolution";
|
||||||
|
message = std::format(
|
||||||
|
"{} Your IP address does not resolve to a hostname.",
|
||||||
|
code
|
||||||
|
);
|
||||||
|
std::cout << std::format("checking {}\n", mechanism);
|
||||||
|
}
|
||||||
|
// HELO/Reverse name check
|
||||||
|
else if (cfg.getCheckHeloAgainstReverse() && !authenticated && ehlostr != resolvedname) {
|
||||||
|
code = cfg.getReturnTempErrorOnReject() ? "421" : "550";
|
||||||
|
mechanism = "helo differs from resolved name";
|
||||||
|
message = std::format(
|
||||||
|
"{} Your IP hostname doesn't match your envelope hostname.",
|
||||||
|
code
|
||||||
|
);
|
||||||
|
std::cout << std::format("checking {}\n", mechanism);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare log message
|
||||||
|
if (!mechanism.empty()) {
|
||||||
|
strlog = std::format("({}) {}", mechanism, strlog);
|
||||||
|
}
|
||||||
|
strlog = std::format("{} {}", code, strlog);
|
||||||
|
std::cout << strlog << "\n";
|
||||||
|
|
||||||
|
// Handle rejection
|
||||||
|
if (code != "250") {
|
||||||
|
// Close inside connection
|
||||||
|
inside.lowest_layer().close();
|
||||||
|
|
||||||
|
// Delay to annoy spammers
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(20));
|
||||||
|
|
||||||
|
// Send rejection message
|
||||||
|
std::string rejection_msg = message + "\r\n";
|
||||||
|
boost::asio::write(outside->lowest_layer(), boost::asio::buffer(rejection_msg), ec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
last_state = SMTP_STATE_WAIT_FOR_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send to inside server
|
||||||
|
boost::asio::write(inside.lowest_layer(), boost::asio::buffer(strtemp), ec);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the server wants to send something to the client
|
||||||
|
size_t server_available = inside.lowest_layer().available(ec);
|
||||||
|
if (server_available > 0) {
|
||||||
|
size_t bytes_read = inside.read_some(boost::asio::buffer(read_buffer), ec);
|
||||||
|
strtemp = std::string(read_buffer.begin(), read_buffer.begin() + bytes_read);
|
||||||
|
|
||||||
|
// Send to outside socket
|
||||||
|
boost::asio::write(outside->lowest_layer(), boost::asio::buffer(strtemp), ec);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Throttling
|
||||||
|
if (throttled) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(cfg.getThrottlingTime()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (const boost::system::system_error& e) {
|
||||||
|
std::cerr << std::format("Boost.Asio error: {}", e.what()) << std::endl;
|
||||||
|
}
|
||||||
|
catch (const std::exception& e) {
|
||||||
|
std::cerr << std::format("Standard exception: {}", e.what()) << std::endl;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch(Exception &e) //any exception will close both connections
|
|
||||||
{
|
|
||||||
LERR(e);
|
|
||||||
if(last_state<SMTP_STATE_WAIT_FOR_DATA)
|
|
||||||
LINF("421 (probably-throttling) from "+(""==from?"no-from":from)+" (ip:"+peer_address+", hostname:"+(""==resolvedname?"not-resolved":resolvedname)+", ehlo:"+(""==ehlostr?"no-ehlo":ehlostr)+") -> to "+(""==to?"no-to":to));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
61
src/Proxy.h
61
src/Proxy.h
|
@ -1,61 +0,0 @@
|
||||||
/**
|
|
||||||
* hermes antispam proxy
|
|
||||||
* Copyright (C) 2006, 2007 Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
|
||||||
*
|
|
||||||
* 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 2 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, write to the Free Software Foundation, Inc.,
|
|
||||||
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
||||||
*
|
|
||||||
* @author Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
|
||||||
*/
|
|
||||||
#ifndef PROXY_H
|
|
||||||
#define PROXY_H
|
|
||||||
|
|
||||||
#include "hermes.h"
|
|
||||||
#include <sys/param.h>
|
|
||||||
#ifdef WIN32
|
|
||||||
#include <winsock2.h>
|
|
||||||
#else
|
|
||||||
#include <sys/select.h>
|
|
||||||
#endif
|
|
||||||
#include <sys/time.h>
|
|
||||||
#include <sys/types.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
#include "Socket.h"
|
|
||||||
#include "Configfile.h"
|
|
||||||
#include "Utils.h"
|
|
||||||
#include "Logger.h"
|
|
||||||
#ifdef HAVE_SPF
|
|
||||||
#include "Spf.h"
|
|
||||||
#endif //HAVE_SPF
|
|
||||||
|
|
||||||
#define SMTP_STATE_WAIT_FOR_HELO 0
|
|
||||||
#define SMTP_STATE_WAIT_FOR_MAILFROM 1
|
|
||||||
#define SMTP_STATE_WAIT_FOR_RCPTTO 2
|
|
||||||
#define SMTP_STATE_WAIT_FOR_DATA 3
|
|
||||||
|
|
||||||
class Proxy
|
|
||||||
{
|
|
||||||
private:
|
|
||||||
Socket outside; //connection from someone sending mail
|
|
||||||
Socket inside; //connection to our inside smtp
|
|
||||||
public:
|
|
||||||
//Proxy():outside(NULL),inside(NULL){};
|
|
||||||
void setOutside(Socket&);
|
|
||||||
void run(string&);
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif //PROXY_H
|
|
51
src/SocketInterface.cpp
Normal file
51
src/SocketInterface.cpp
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
// BoostSocket.h
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include "SocketInterface.h"
|
||||||
|
|
||||||
|
class BoostSocket : public SocketInterface {
|
||||||
|
public:
|
||||||
|
BoostSocket() : socket_(io_service_) {}
|
||||||
|
|
||||||
|
void connect(const std::string& host, unsigned short port) override {
|
||||||
|
boost::asio::ip::tcp::resolver resolver(io_service_);
|
||||||
|
boost::asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, std::to_string(port));
|
||||||
|
boost::asio::connect(socket_, endpoints);
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeLine(const std::string& data) override {
|
||||||
|
boost::asio::write(socket_, boost::asio::buffer(data + "\r\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string readLine() override {
|
||||||
|
boost::asio::streambuf buf;
|
||||||
|
boost::asio::read_until(socket_, buf, "\r\n");
|
||||||
|
std::istream is(&buf);
|
||||||
|
std::string line;
|
||||||
|
std::getline(is, line);
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool canRead(double timeout) override {
|
||||||
|
// Implementation to check if data is available to read.
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isClosed() override {
|
||||||
|
return !socket_.is_open();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() override {
|
||||||
|
socket_.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
void prepareSSL(bool incoming) override {
|
||||||
|
// Implement SSL preparation here if needed.
|
||||||
|
}
|
||||||
|
|
||||||
|
void startSSL(bool incoming) override {
|
||||||
|
// Implement starting SSL here if needed.
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
boost::asio::io_service io_service_;
|
||||||
|
boost::asio::ip::tcp::socket socket_;
|
||||||
|
};
|
121
src/Spf.cpp
121
src/Spf.cpp
|
@ -4,11 +4,11 @@
|
||||||
*
|
*
|
||||||
* This program is free software; you can redistribute it and/or modify
|
* 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
|
* it under the terms of the GNU General Public License as published by
|
||||||
* the Free Software Foundation; version 2 of the License
|
* the Free Software Foundation; version 2 of the License.
|
||||||
*
|
*
|
||||||
* This program is distributed in the hope that it will be useful,
|
* This program is distributed in the hope that it will be useful,
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
* GNU General Public License for more details.
|
* GNU General Public License for more details.
|
||||||
*
|
*
|
||||||
* You should have received a copy of the GNU General Public License along
|
* You should have received a copy of the GNU General Public License along
|
||||||
|
@ -17,83 +17,90 @@
|
||||||
*
|
*
|
||||||
* @author Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
* @author Juan José Gutiérrez de Quevedo <juanjo@gutierrezdequevedo.com>
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "Spf.h"
|
#include "Spf.h"
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
SPF_server_t *Spf::spfserver=NULL;
|
SPF_server_t *Spf::spfserver = nullptr;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* it will create a spfserver if this is the first created object of the class.
|
* Initializes the SPF server if this is the first created object of the class.
|
||||||
* if it isn't, then we just create an spfrequest
|
|
||||||
*/
|
*/
|
||||||
Spf::Spf():spfrequest(NULL),spfresponse(NULL)
|
Spf::Spf() {
|
||||||
{
|
static std::once_flag initFlag; // To ensure thread-safe initialization
|
||||||
pthread_mutex_init(&mutex,NULL);
|
std::call_once(initFlag, []() {
|
||||||
if(NULL==spfserver)
|
spfserver = SPF_server_new(SPF_DNS_CACHE, 0);
|
||||||
if(NULL==(spfserver=SPF_server_new(SPF_DNS_CACHE,0)))
|
if (!spfserver) {
|
||||||
throw Exception(_("Can't initialize SPF library"),__FILE__,__LINE__);
|
throw std::runtime_error("Can't initialize SPF library");
|
||||||
|
}
|
||||||
if(NULL==(spfrequest=SPF_request_new(spfserver)))
|
});
|
||||||
throw Exception(_("Can't initialize SPF request"),__FILE__,__LINE__);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* destructor
|
* Destructor
|
||||||
*
|
*
|
||||||
* frees the memory of the spfrequest
|
* Frees the memory of the SPF server.
|
||||||
*/
|
*/
|
||||||
Spf::~Spf()
|
Spf::~Spf() {
|
||||||
{
|
deinitialize(); // Clean up resources
|
||||||
pthread_mutex_destroy(&mutex);
|
|
||||||
if(NULL!=spfrequest) SPF_request_free(spfrequest);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* frees all memory related to the spf class
|
* Frees all memory related to the SPF class.
|
||||||
*
|
*
|
||||||
* this is needed because the common things are only initialized
|
* This is needed because common resources are only initialized once (and are static).
|
||||||
* once (and are static), and when we close the program we need
|
|
||||||
* to deinitialize them
|
|
||||||
*/
|
*/
|
||||||
void Spf::deinitialize()
|
void Spf::deinitialize() {
|
||||||
{
|
if (spfserver) {
|
||||||
if(NULL!=spfserver)
|
SPF_server_free(spfserver);
|
||||||
SPF_server_free(spfserver);
|
spfserver = nullptr; // Optional: Avoid dangling pointer
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* make a query to the dns system for an spf record
|
* Makes a query to the DNS system for an SPF record.
|
||||||
*
|
*
|
||||||
* highly inspired from fakehermes' source
|
* @param ip The IP of the remote server
|
||||||
|
* @param helo The HELO string of the remote server
|
||||||
|
* @param from The envelope from address
|
||||||
*
|
*
|
||||||
* @param ip the ip of the remote server
|
* @returns true if the query is not incorrect
|
||||||
* @param helo the hello string of the remote server
|
|
||||||
* @param from the envelope from address
|
|
||||||
*
|
|
||||||
* @returns true if it is not incorrect
|
|
||||||
*/
|
*/
|
||||||
bool Spf::query(string ip,string helo,string from)
|
bool Spf::query(const std::string& ip, const std::string& helo, const std::string& from) {
|
||||||
{
|
SPF_request_t* spfrequest = SPF_request_new(spfserver); // Create request here
|
||||||
bool retval=false;
|
if (!spfrequest) {
|
||||||
|
throw std::runtime_error("Can't initialize SPF request");
|
||||||
|
}
|
||||||
|
|
||||||
if(SPF_request_set_ipv4_str(spfrequest,ip.c_str()))
|
// Set the values for the SPF request
|
||||||
throw Exception(_("Error configuring IP for SPF request"),__FILE__,__LINE__);
|
if (SPF_request_set_ipv4_str(spfrequest, ip.c_str())) {
|
||||||
if(SPF_request_set_helo_dom(spfrequest,helo.c_str()))
|
SPF_request_free(spfrequest); // Clean up on failure
|
||||||
throw Exception(_("Error configuring HELO for SPF request"),__FILE__,__LINE__);
|
throw std::runtime_error("Error configuring IP for SPF request");
|
||||||
if(SPF_request_set_env_from(spfrequest,from.c_str()))
|
}
|
||||||
throw Exception(_("Error configuring FROM for SPF request"),__FILE__,__LINE__);
|
if (SPF_request_set_helo_dom(spfrequest, helo.c_str())) {
|
||||||
|
SPF_request_free(spfrequest); // Clean up on failure
|
||||||
|
throw std::runtime_error("Error configuring HELO for SPF request");
|
||||||
|
}
|
||||||
|
if (SPF_request_set_env_from(spfrequest, from.c_str())) {
|
||||||
|
SPF_request_free(spfrequest); // Clean up on failure
|
||||||
|
throw std::runtime_error("Error configuring FROM for SPF request");
|
||||||
|
}
|
||||||
|
|
||||||
//make the actual query
|
// Make the actual query
|
||||||
pthread_mutex_lock(&mutex);
|
SPF_response_t* spfresponse = nullptr; // Local response variable
|
||||||
SPF_request_query_mailfrom(spfrequest,&spfresponse);
|
SPF_request_query_mailfrom(spfrequest, &spfresponse);
|
||||||
pthread_mutex_unlock(&mutex);
|
|
||||||
|
|
||||||
if(NULL!=spfresponse)
|
bool retval = false;
|
||||||
{
|
if (spfresponse) {
|
||||||
retval=(SPF_RESULT_FAIL==SPF_response_result(spfresponse)||SPF_RESULT_SOFTFAIL==SPF_response_result(spfresponse))?false:true;
|
retval = !(SPF_response_result(spfresponse) == SPF_RESULT_FAIL ||
|
||||||
SPF_response_free(spfresponse);
|
SPF_response_result(spfresponse) == SPF_RESULT_SOFTFAIL);
|
||||||
}
|
SPF_response_free(spfresponse); // Free the response
|
||||||
|
}
|
||||||
|
|
||||||
return retval;
|
SPF_request_free(spfrequest); // Free the request
|
||||||
|
return retval;
|
||||||
}
|
}
|
||||||
|
|
|
@ -332,38 +332,6 @@ void *cleaner_thread_run(void *)
|
||||||
{
|
{
|
||||||
LERR("Error cleaning the database: " + string(e));
|
LERR("Error cleaning the database: " + string(e));
|
||||||
}
|
}
|
||||||
if(spamcount>0&&cfg.getSubmitStats())
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Socket s;
|
|
||||||
string server_response;
|
|
||||||
|
|
||||||
s.init();
|
|
||||||
s.connect("stats.hermes-project.com",11125);
|
|
||||||
#ifdef HAVE_SSL
|
|
||||||
if(cfg.getSubmitStatsSsl())
|
|
||||||
{
|
|
||||||
s.writeLine("ssl");
|
|
||||||
s.prepareSSL(false);
|
|
||||||
s.startSSL(false);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
#endif //HAVE_SSL
|
|
||||||
s.writeLine("non-ssl");
|
|
||||||
s.writeLine(cfg.getSubmitStatsUsername());
|
|
||||||
s.writeLine(cfg.getSubmitStatsPassword());
|
|
||||||
s.writeLine(Utils::inttostr(spamcount));
|
|
||||||
server_response=s.readLine();
|
|
||||||
s.close();
|
|
||||||
if("OK"!=server_response)
|
|
||||||
throw Exception(server_response,__FILE__,__LINE__);
|
|
||||||
}
|
|
||||||
catch(Exception &e)
|
|
||||||
{
|
|
||||||
LDEB("Exception sending stats: "+string(e));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
if(false==cfg.getBackground())
|
if(false==cfg.getBackground())
|
||||||
|
|
14
test/CMakeLists.txt
Normal file
14
test/CMakeLists.txt
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
cmake_minimum_required(VERSION 3.31)
|
||||||
|
|
||||||
|
project(unittests)
|
||||||
|
|
||||||
|
find_package(GTest REQUIRED)
|
||||||
|
include_directories(${GTEST_INCLUDE_DIRS})
|
||||||
|
|
||||||
|
add_executable(spf_test tests/spf_test.cpp ../src/Spf.cpp) # Your test file
|
||||||
|
target_include_directories(spf_test PRIVATE ../include mocks)
|
||||||
|
target_link_libraries(spf_test ${GTEST_LIBRARIES} pthread)
|
||||||
|
|
||||||
|
add_executable(proxy_test tests/proxy_test.cpp ../src/Proxy.cpp) # Your test file
|
||||||
|
target_include_directories(proxy_test PRIVATE ../include mocks)
|
||||||
|
target_link_libraries(proxy_test ${GTEST_LIBRARIES} pthread)
|
96
test/mocks/libspf2_mock.h
Normal file
96
test/mocks/libspf2_mock.h
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
#ifndef LIBSPF2_MOCK_H
|
||||||
|
#define LIBSPF2_MOCK_H
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <string>
|
||||||
|
#include <spf2/spf.h>
|
||||||
|
|
||||||
|
// Control variables to adjust behavior of mocked functions
|
||||||
|
extern "C" {
|
||||||
|
static SPF_errcode_t spf_set_ipv4_result = SPF_E_SUCCESS;
|
||||||
|
static SPF_errcode_t spf_set_helo_result = SPF_E_SUCCESS;
|
||||||
|
static int spf_set_from_result;
|
||||||
|
static SPF_response_t* spf_mock_response = nullptr;
|
||||||
|
static SPF_errcode_t spf_request_query_result = SPF_E_SUCCESS;
|
||||||
|
|
||||||
|
// New control variables for SPF_server mocking
|
||||||
|
static SPF_server_t* spf_mock_server = nullptr;
|
||||||
|
static bool spf_server_new_should_fail = false;
|
||||||
|
|
||||||
|
SPF_server_t* SPF_server_new(SPF_server_dnstype_t dnstype,int debug)
|
||||||
|
{
|
||||||
|
if (spf_server_new_should_fail) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
return spf_mock_server ? spf_mock_server : new SPF_server_t();
|
||||||
|
}
|
||||||
|
|
||||||
|
void SPF_server_free(SPF_server_t* server) {
|
||||||
|
delete server;
|
||||||
|
}
|
||||||
|
|
||||||
|
SPF_request_t* SPF_request_new(SPF_server_t *server) {
|
||||||
|
return new SPF_request_t(); // Simply allocate and return new request
|
||||||
|
}
|
||||||
|
|
||||||
|
void SPF_request_free(SPF_request_t* request) {
|
||||||
|
delete request; // Deallocate request
|
||||||
|
}
|
||||||
|
|
||||||
|
SPF_errcode_t SPF_request_set_ipv4_str(SPF_request_t* request, const char* ip) {
|
||||||
|
return spf_set_ipv4_result; // Use controllable result
|
||||||
|
}
|
||||||
|
|
||||||
|
SPF_errcode_t SPF_request_set_helo_dom(SPF_request_t* request, const char* helo) {
|
||||||
|
return spf_set_helo_result; // Use controllable result
|
||||||
|
}
|
||||||
|
|
||||||
|
int SPF_request_set_env_from(SPF_request_t* request, const char* from) {
|
||||||
|
return spf_set_from_result; // Use controllable result
|
||||||
|
}
|
||||||
|
|
||||||
|
SPF_errcode_t SPF_request_query_mailfrom(SPF_request_t* request, SPF_response_t** response) {
|
||||||
|
*response = spf_mock_response;
|
||||||
|
return spf_request_query_result;
|
||||||
|
}
|
||||||
|
|
||||||
|
SPF_result_t SPF_response_result(SPF_response_t* response) {
|
||||||
|
return response->result; // Return the result
|
||||||
|
}
|
||||||
|
|
||||||
|
void SPF_response_free(SPF_response_t* response) {
|
||||||
|
delete response; // Deallocate response
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Functions to set return values for mocked functions
|
||||||
|
void SetSpfMockReturnIPv4Value(SPF_errcode_t value) {
|
||||||
|
spf_set_ipv4_result = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SetSpfMockReturnHeloValue(SPF_errcode_t value) {
|
||||||
|
spf_set_helo_result = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SetSpfMockReturnFromValue(int value) {
|
||||||
|
spf_set_from_result = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SetSpfRequestQueryResult(SPF_errcode_t value) {
|
||||||
|
spf_request_query_result = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SetSpfMockResponse(SPF_response_t* mockResponse) {
|
||||||
|
spf_mock_response = mockResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// New functions for SPF_server mocking
|
||||||
|
void SetSpfMockServer(SPF_server_t* mockServer) {
|
||||||
|
spf_mock_server = mockServer;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SetSpfServerNewShouldFail(bool shouldFail) {
|
||||||
|
spf_server_new_should_fail = shouldFail;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // LIBSPF2_MOCK_H
|
15
test/mocks/socket_mock.h
Normal file
15
test/mocks/socket_mock.h
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
// MockSocket.h
|
||||||
|
#include "SocketInterface.h"
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
|
||||||
|
class MockSocket : public SocketInterface {
|
||||||
|
public:
|
||||||
|
MOCK_METHOD(void, connect, (const std::string& host, unsigned short port), (override));
|
||||||
|
MOCK_METHOD(void, writeLine, (const std::string& data), (override));
|
||||||
|
MOCK_METHOD(std::string, readLine, (), (override));
|
||||||
|
MOCK_METHOD(bool, canRead, (double timeout), (override));
|
||||||
|
MOCK_METHOD(bool, isClosed, (), (override));
|
||||||
|
MOCK_METHOD(void, close, (), (override));
|
||||||
|
MOCK_METHOD(void, prepareSSL, (bool incoming), (override));
|
||||||
|
MOCK_METHOD(void, startSSL, (bool incoming), (override));
|
||||||
|
};
|
63
test/tests/proxy_test.cpp
Normal file
63
test/tests/proxy_test.cpp
Normal file
|
@ -0,0 +1,63 @@
|
||||||
|
// ProxyTest.cpp
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include "Proxy.h"
|
||||||
|
#include "socket_mock.h"
|
||||||
|
|
||||||
|
class ProxyTest : public ::testing::Test {
|
||||||
|
protected:
|
||||||
|
MockSocket mock_socket;
|
||||||
|
Proxy* proxy;
|
||||||
|
|
||||||
|
void SetUp() override {
|
||||||
|
proxy = new Proxy(&mock_socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
void TearDown() override {
|
||||||
|
delete proxy;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
TEST_F(ProxyTest, HandlesMailFromCommand) {
|
||||||
|
std::string peer_address = "127.0.0.1";
|
||||||
|
|
||||||
|
EXPECT_CALL(mock_socket, connect("server-host", 25));
|
||||||
|
EXPECT_CALL(mock_socket, canRead(0.2)).WillOnce(testing::Return(true));
|
||||||
|
EXPECT_CALL(mock_socket, readLine()).WillOnce(testing::Return("MAIL FROM:<test@example.com>"));
|
||||||
|
EXPECT_CALL(mock_socket, writeLine("MAIL FROM:<test@example.com>"));
|
||||||
|
EXPECT_CALL(mock_socket, writeLine("250 OK"));
|
||||||
|
|
||||||
|
proxy->run(peer_address);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(ProxyTest, HandlesRcptToCommand) {
|
||||||
|
std::string peer_address = "127.0.0.1";
|
||||||
|
|
||||||
|
EXPECT_CALL(mock_socket, connect("server-host", 25));
|
||||||
|
EXPECT_CALL(mock_socket, canRead(0.2)).WillRepeatedly(testing::Return(true));
|
||||||
|
EXPECT_CALL(mock_socket, readLine())
|
||||||
|
.WillOnce(testing::Return("MAIL FROM:<test@example.com>"))
|
||||||
|
.WillOnce(testing::Return("RCPT TO:<receiver@example.com>"))
|
||||||
|
.WillOnce(testing::Return(""));
|
||||||
|
|
||||||
|
EXPECT_CALL(mock_socket, writeLine("MAIL FROM:<test@example.com>"));
|
||||||
|
EXPECT_CALL(mock_socket, writeLine("RCPT TO:<receiver@example.com>"));
|
||||||
|
EXPECT_CALL(mock_socket, writeLine("250 OK"));
|
||||||
|
|
||||||
|
proxy->run(peer_address);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(ProxyTest, HandlesEmptyLine) {
|
||||||
|
std::string peer_address = "127.0.0.1";
|
||||||
|
|
||||||
|
EXPECT_CALL(mock_socket, connect("server-host", 25));
|
||||||
|
EXPECT_CALL(mock_socket, canRead(0.2)).WillOnce(testing::Return(true));
|
||||||
|
EXPECT_CALL(mock_socket, readLine()).WillOnce(testing::Return(""));
|
||||||
|
|
||||||
|
proxy->run(peer_address);
|
||||||
|
// Expect no further actions to occur
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
::testing::InitGoogleMock(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
98
test/tests/spf_test.cpp
Normal file
98
test/tests/spf_test.cpp
Normal file
|
@ -0,0 +1,98 @@
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include "Spf.h"
|
||||||
|
|
||||||
|
#include "libspf2_mock.h"
|
||||||
|
|
||||||
|
// Mock the SPF server responses for unit testing
|
||||||
|
class MockSPFServer {
|
||||||
|
public:
|
||||||
|
static void initialize() {
|
||||||
|
// Initialize any mock data here
|
||||||
|
}
|
||||||
|
|
||||||
|
static void cleanup() {
|
||||||
|
// Cleanup if needed
|
||||||
|
}
|
||||||
|
|
||||||
|
static SPF_response_t* mockResponse(SPF_result_t result) {
|
||||||
|
SPF_response_t* response = new SPF_response_t; // Replace with actual allocation
|
||||||
|
response->result = result; // Set the desired mock result
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Test Fixture for SPF tests
|
||||||
|
class SpfTest : public ::testing::Test {
|
||||||
|
protected:
|
||||||
|
Spf* spf;
|
||||||
|
|
||||||
|
void SetUp() override {
|
||||||
|
// Create a new Spf instance before each test
|
||||||
|
spf = new Spf();
|
||||||
|
}
|
||||||
|
|
||||||
|
void TearDown() override {
|
||||||
|
// Clean up after each test
|
||||||
|
delete spf;
|
||||||
|
spf->deinitialize();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Test the construction of the Spf object
|
||||||
|
TEST_F(SpfTest, Construction) {
|
||||||
|
EXPECT_NO_THROW({
|
||||||
|
Spf testSpf;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test SPF querying with valid parameters
|
||||||
|
TEST_F(SpfTest, QueryValidParameters) {
|
||||||
|
// Assuming the mocked SPF server is set up to return a valid response
|
||||||
|
MockSPFServer::initialize();
|
||||||
|
|
||||||
|
bool result = spf->query("192.0.2.1", "mail.example.com", "test@example.com");
|
||||||
|
EXPECT_TRUE(result);
|
||||||
|
|
||||||
|
MockSPFServer::cleanup();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test SPF querying with failed result
|
||||||
|
TEST_F(SpfTest, QueryFailResult) {
|
||||||
|
// Mock the response to return a fail result here
|
||||||
|
SPF_response_t* response = MockSPFServer::mockResponse(SPF_RESULT_FAIL);
|
||||||
|
|
||||||
|
bool result = spf->query("198.51.100.1", "fail.example.com", "test@fail.com");
|
||||||
|
EXPECT_FALSE(result);
|
||||||
|
|
||||||
|
delete response; // Clean up mocked response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test SPF querying with an empty HELO string
|
||||||
|
TEST_F(SpfTest, QueryEmptyHelo) {
|
||||||
|
EXPECT_THROW({
|
||||||
|
spf->query("192.0.2.1", "", "test@example.com");
|
||||||
|
}, std::runtime_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test SPF querying with invalid IP format
|
||||||
|
TEST_F(SpfTest, QueryInvalidIPAddress) {
|
||||||
|
EXPECT_THROW({
|
||||||
|
spf->query("invalid_ip", "mail.example.com", "test@example.com");
|
||||||
|
}, std::runtime_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test SPF request failure
|
||||||
|
TEST_F(SpfTest, QueryRequestFailure) {
|
||||||
|
// Here you might want to simulate a situation
|
||||||
|
// where the request cannot be created or fails due to some other reason.
|
||||||
|
spf->deinitialize(); // Ensure the server is cleaned up before running this.
|
||||||
|
|
||||||
|
EXPECT_THROW({
|
||||||
|
spf->query("192.0.2.1", "mail.example.com", "test@example.com");
|
||||||
|
}, std::runtime_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
::testing::InitGoogleTest(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue