This fix makes sure that generated message IDs via SetMessageID() are truly random and unique
This commit is contained in:
Winni Neessen 2022-10-26 11:59:03 +02:00
parent c321aeeccc
commit 021e003e78
Signed by: wneessen
GPG key ID: 5F3AF39B820C119D
2 changed files with 24 additions and 4 deletions

8
msg.go
View file

@ -357,12 +357,12 @@ func (m *Msg) SetMessageID() {
if err != nil { if err != nil {
hn = "localhost.localdomain" hn = "localhost.localdomain"
} }
ct := time.Now().Unix() ct := time.Now().UnixNano()
r := rand.New(rand.NewSource(ct)) r := rand.New(rand.NewSource(ct))
rn := r.Int() rn := r.Int63()
pid := os.Getpid() pid := os.Getpid()
cts := fmt.Sprintf("%d", ct)
mid := fmt.Sprintf("%d.%d.%d@%s", pid, rn, ct, hn) mid := fmt.Sprintf("%d.%d.%s@%s", pid, rn, cts[:15], hn)
m.SetMessageIDWithValue(mid) m.SetMessageIDWithValue(mid)
} }

View file

@ -695,6 +695,26 @@ func TestMsg_SetMessageIDWithValue(t *testing.T) {
} }
} }
// TestMsg_SetMessageIDRandomness tests the randomness of Msg.SetMessageID methods
func TestMsg_SetMessageIDRandomness(t *testing.T) {
var mids []string
for i := 0; i < 100; i++ {
m := NewMsg()
m.SetMessageID()
mid := m.GetGenHeader(HeaderMessageID)
mids = append(mids, mid[0])
}
c := make(map[string]int)
for i := range mids {
c[mids[i]]++
}
for k, v := range c {
if v > 1 {
t.Errorf("MessageID randomness not give. MessageID %q was generated %d times", k, v)
}
}
}
// TestMsg_FromFormat tests the FromFormat and EnvelopeFrom methods for the Msg object // TestMsg_FromFormat tests the FromFormat and EnvelopeFrom methods for the Msg object
func TestMsg_FromFormat(t *testing.T) { func TestMsg_FromFormat(t *testing.T) {
tests := []struct { tests := []struct {