100 lines
2.5 KiB
Go
100 lines
2.5 KiB
Go
/* diodemail - send-only smtp server
|
|
* Copyright (c) 2024 Gnarwhal
|
|
*
|
|
* This file is part of diodemail.
|
|
*
|
|
* diodemail 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,
|
|
* either version 3 of the License, or (at your option) any later version.
|
|
*
|
|
* diodemail 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
|
|
* diodemail. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
package smtp
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"crypto/tls"
|
|
"sync"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func handle(connection net.Conn, host string, password_hash string, tls_config tls.Config) {
|
|
log.Info().Msgf(
|
|
"New connection %v. Starting session.",
|
|
connection.RemoteAddr(),
|
|
)
|
|
defer connection.Close()
|
|
|
|
session := MakeSMTPSession(connection, host, password_hash, tls_config)
|
|
err := session.Run()
|
|
if err != nil {
|
|
log.Error().Msgf(
|
|
"Session %v exited with error: %v",
|
|
connection.RemoteAddr(),
|
|
err,
|
|
)
|
|
} else {
|
|
log.Info().Msgf(
|
|
"Session %v exited successfully",
|
|
connection.RemoteAddr(),
|
|
)
|
|
}
|
|
}
|
|
|
|
func Run(
|
|
host string,
|
|
password_hash string,
|
|
plain_port string,
|
|
tls_port string,
|
|
tls_config tls.Config,
|
|
) error {
|
|
var wait_group sync.WaitGroup
|
|
if plain_port != "disabled" {
|
|
listener, err := net.Listen("tcp", fmt.Sprintf(":%v", plain_port))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
log.Info().Msgf("Plain text server started on port %v for host %v", plain_port, host)
|
|
wait_group.Add(1)
|
|
go Listen(wait_group, host, password_hash, tls_config, listener)
|
|
}
|
|
if tls_port != "disabled" {
|
|
listener, err := tls.Listen("tcp", fmt.Sprintf(":%v", tls_port), &tls_config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
log.Info().Msgf("TLS server started on port %v for host %v", tls_port, host)
|
|
wait_group.Add(1)
|
|
go Listen(wait_group, host, password_hash, tls_config, listener)
|
|
}
|
|
wait_group.Wait()
|
|
|
|
return nil
|
|
}
|
|
|
|
func Listen(
|
|
wait_group sync.WaitGroup,
|
|
host string,
|
|
password_hash string,
|
|
tls_config tls.Config,
|
|
listener net.Listener,
|
|
) {
|
|
defer wait_group.Done()
|
|
for {
|
|
connection, err := listener.Accept()
|
|
if err != nil {
|
|
log.Error().Msgf("Failed to accept client: %v", err)
|
|
} else {
|
|
go handle(connection, host, password_hash, tls_config)
|
|
}
|
|
}
|
|
}
|