@@ -3,9 +3,10 @@ package tcp
3
3
import (
4
4
"bufio"
5
5
"context"
6
+ "crypto/rand"
6
7
"fmt"
7
8
"log/slog"
8
- "math/rand "
9
+ "math/big "
9
10
"net"
10
11
"regexp"
11
12
"strings"
@@ -34,13 +35,15 @@ func (c *Client) read() (string, error) {
34
35
return c .bufin .ReadString ('\n' )
35
36
}
36
37
37
- func rwait () {
38
- // makes the process sleep for random time
39
- rand .Seed (time .Now ().Unix ())
38
+ func randomSleep () error {
40
39
// between 0.5 - 1.5 seconds
41
- rtime := rand .Intn (1500 ) + 500
42
- duration := time .Duration (rtime ) * time .Millisecond
40
+ rtime , err := rand .Int (rand .Reader , big .NewInt (1500 ))
41
+ if err != nil {
42
+ return err
43
+ }
44
+ duration := time .Duration (rtime .Int64 ()+ 500 ) * time .Millisecond
43
45
time .Sleep (duration )
46
+ return nil
44
47
}
45
48
func validateMail (query string ) bool {
46
49
email := regexp .MustCompile ("^MAIL FROM:<.+@.+>$" ) // naive regex
@@ -64,7 +67,9 @@ func HandleSMTP(ctx context.Context, conn net.Conn, md connection.Metadata, logg
64
67
bufin : bufio .NewReader (conn ),
65
68
bufout : bufio .NewWriter (conn ),
66
69
}
67
- rwait ()
70
+ if err := randomSleep (); err != nil {
71
+ return err
72
+ }
68
73
client .w ("220 Welcome!" )
69
74
70
75
for {
@@ -78,13 +83,19 @@ func HandleSMTP(ctx context.Context, conn net.Conn, md connection.Metadata, logg
78
83
query := strings .Trim (data , "\r \n " )
79
84
logger .Info (fmt .Sprintf ("[smtp ] Payload : %q" , query ))
80
85
if strings .HasPrefix (query , "HELO " ) {
81
- rwait ()
86
+ if err := randomSleep (); err != nil {
87
+ return err
88
+ }
82
89
client .w ("250 Hello! Pleased to meet you." )
83
90
} else if validateMail (query ) {
84
- rwait ()
91
+ if err := randomSleep (); err != nil {
92
+ return err
93
+ }
85
94
client .w ("250 OK" )
86
95
} else if validateRCPT (query ) {
87
- rwait ()
96
+ if err := randomSleep (); err != nil {
97
+ return err
98
+ }
88
99
client .w ("250 OK" )
89
100
} else if strings .Compare (query , "DATA" ) == 0 {
90
101
client .w ("354 End data with <CRLF>.<CRLF>" )
@@ -104,7 +115,9 @@ func HandleSMTP(ctx context.Context, conn net.Conn, md connection.Metadata, logg
104
115
break
105
116
}
106
117
}
107
- rwait ()
118
+ if err := randomSleep (); err != nil {
119
+ return err
120
+ }
108
121
client .w ("250 OK" )
109
122
} else if strings .Compare (query , "QUIT" ) == 0 {
110
123
client .w ("Bye" )
0 commit comments