| 1 |
package autoconfig |
| 2 |
|
| 3 |
import ( |
| 4 |
"cmp" |
| 5 |
"context" |
| 6 |
"net" |
| 7 |
"slices" |
| 8 |
"strings" |
| 9 |
"sync" |
| 10 |
|
| 11 |
"git.sr.ht/~rjarry/aerc/lib/log" |
| 12 |
) |
| 13 |
|
| 14 |
func guessMX(ctx context.Context, localpart, domain string, result chan *Config) { |
| 15 |
defer log.PanicHandler() |
| 16 |
defer close(result) |
| 17 |
|
| 18 |
res := make(chan *Config) |
| 19 |
go func(res chan *Config) { |
| 20 |
defer log.PanicHandler() |
| 21 |
defer close(res) |
| 22 |
|
| 23 |
var imapConfig, smtpConfig *Credentials |
| 24 |
var wg sync.WaitGroup |
| 25 |
|
| 26 |
records, err := lookupMX(domain) |
| 27 |
if err != nil || len(records) == 0 { |
| 28 |
return |
| 29 |
} |
| 30 |
|
| 31 |
slices.SortFunc(records, func(a, b *net.MX) int { |
| 32 |
return cmp.Compare(a.Pref, b.Pref) |
| 33 |
}) |
| 34 |
|
| 35 |
mailserver := records[0].Host |
| 36 |
mailserver = strings.TrimSuffix(mailserver, ".") |
| 37 |
|
| 38 |
wg.Add(2) |
| 39 |
|
| 40 |
go func() { |
| 41 |
defer log.PanicHandler() |
| 42 |
defer wg.Done() |
| 43 |
imapConfig = tryPort(mailserver, []portEncryption{{143, EncryptionSTARTTLS}, {993, EncryptionTLS}}) |
| 44 |
}() |
| 45 |
|
| 46 |
go func() { |
| 47 |
defer log.PanicHandler() |
| 48 |
defer wg.Done() |
| 49 |
smtpConfig = tryPort(mailserver, []portEncryption{{587, EncryptionSTARTTLS}, {465, EncryptionTLS}}) |
| 50 |
}() |
| 51 |
wg.Wait() |
| 52 |
|
| 53 |
if imapConfig == nil || smtpConfig == nil { |
| 54 |
return |
| 55 |
} |
| 56 |
log.Debugf("found MX records: %v %v", imapConfig, smtpConfig) |
| 57 |
|
| 58 |
imapConfig.Username = localpart + "@" + domain |
| 59 |
smtpConfig.Username = localpart + "@" + domain |
| 60 |
|
| 61 |
res <- &Config{ |
| 62 |
Found: ProtocolIMAP, |
| 63 |
IMAP: *imapConfig, |
| 64 |
SMTP: *smtpConfig, |
| 65 |
} |
| 66 |
}(res) |
| 67 |
|
| 68 |
select { |
| 69 |
case r, next := <-res: |
| 70 |
if next { |
| 71 |
result <- r |
| 72 |
} |
| 73 |
case <-ctx.Done(): |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
var lookupMX = net.LookupMX |