diodemail/smtp/connection.go

92 lines
2.2 KiB
Go

/* diodemail - send-only smtp server
* Copyright (c) 2024 Gnarwhal
*
* This file is part of SSHare.
*
* SSHare 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.
*
* SSHare 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
* SSHare. If not, see <https://www.gnu.org/licenses/>.
*/
package smtp
import (
"net"
// "fmt"
"strings"
"github.com/rs/zerolog/log"
)
type Connection struct {
connection net.Conn
ReversePathBuffer *string
ForwardPathBuffer *string
MailBuffer *string
}
func NewConnection(connection net.Conn) Connection {
return Connection{
connection,
nil,
nil,
nil,
}
}
var buffer = [1024]byte{}
func (self Connection) Read(delimiter string) (string, error) {
var message string
for !strings.Contains(message, delimiter) {
num_read, err := self.connection.Read(buffer[:])
if err != nil {
return "", err
}
message += string(buffer[:num_read])
}
lines := strings.Split(message, "\n")
for index, line := range lines {
if index != len(lines) - 1 || line != "" {
if index == 0 {
log.Trace().Msgf("%v -> %v", self.RemoteAddr(), line)
} else {
log.Trace().Msgf("%v %v", self.RemoteAddr(), line)
}
}
}
return message[:len(message) - len(delimiter)], nil
}
func (self Connection) Write(message string) error {
lines := strings.Split(message, "\n")
for index, line := range lines {
if index != len(lines) - 1 || line != "" {
if index == 0 {
log.Trace().Msgf("%v <- %v", self.RemoteAddr(), line)
} else {
log.Trace().Msgf("%v %v", self.RemoteAddr(), line)
}
}
}
_, err := self.connection.Write([]byte(message))
return err
}
func (self Connection) Close() {
self.connection.Close()
}
func (self Connection) RemoteAddr() net.Addr {
return self.connection.RemoteAddr()
}