| 1 |
package xmpp |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/tls" |
| 6 |
"encoding/xml" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"net" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"mellium.im/sasl" |
| 14 |
"mellium.im/xmpp/jid" |
| 15 |
"mellium.im/xmpp/muc" |
| 16 |
"mellium.im/xmpp/stanza" |
| 17 |
|
| 18 |
mxmpp "mellium.im/xmpp" |
| 19 |
xmux "mellium.im/xmpp/mux" |
| 20 |
) |
| 21 |
|
| 22 |
// Session is a connected XMPP session used to send notifications. |
| 23 |
type Session interface { |
| 24 |
// Close ends the session and the underlying connection. |
| 25 |
Close() error |
| 26 |
// SendChat sends a type=chat message to to. |
| 27 |
SendChat(ctx context.Context, to, body string) error |
| 28 |
// SendToRoom joins room, sends a groupchat message, and leaves. |
| 29 |
SendToRoom(ctx context.Context, room, nick, password, body string) error |
| 30 |
} |
| 31 |
|
| 32 |
// SessionFactory constructs an XMPP session over an existing TCP connection. |
| 33 |
type SessionFactory func(ctx context.Context, cfg *Config, conn net.Conn) (Session, error) |
| 34 |
|
| 35 |
// messageBody is the XML payload encoded for chat and groupchat stanzas. |
| 36 |
type messageBody struct { |
| 37 |
XMLName xml.Name `xml:"message"` |
| 38 |
To string `xml:"to,attr"` |
| 39 |
Type string `xml:"type,attr"` |
| 40 |
Body string `xml:"body"` |
| 41 |
} |
| 42 |
|
| 43 |
// melliumSession implements [Session] with mellium over an existing connection. |
| 44 |
type melliumSession struct { |
| 45 |
session *mxmpp.Session |
| 46 |
mucClient *muc.Client |
| 47 |
} |
| 48 |
|
| 49 |
var _ io.Closer = (*melliumSession)(nil) |
| 50 |
|
| 51 |
// newMelliumSession negotiates an XMPP client session over conn. |
| 52 |
// |
| 53 |
// Implicit TLS is applied for xmpps://. STARTTLS is negotiated for xmpp:// |
| 54 |
// unless disabletls is set. A Serve goroutine is started so MUC join can |
| 55 |
// receive presence. |
| 56 |
// |
| 57 |
// Parameters: |
| 58 |
// - ctx: Parent context for handshake and stream negotiation. |
| 59 |
// - cfg: Session TLS, SASL, and JID settings. |
| 60 |
// - conn: The TCP connection to wrap. |
| 61 |
// |
| 62 |
// Returns: |
| 63 |
// - A [Session] ready to send chat and MUC messages. |
| 64 |
// - An error if TLS, SASL, or stream negotiation fails. |
| 65 |
func newMelliumSession(ctx context.Context, cfg *Config, conn net.Conn) (Session, error) { |
| 66 |
local, domain, err := splitJID(cfg.authJIDString()) |
| 67 |
if err != nil { |
| 68 |
return nil, err |
| 69 |
} |
| 70 |
|
| 71 |
origin, err := jid.New(local, domain, Resource) |
| 72 |
if err != nil { |
| 73 |
return nil, fmt.Errorf("parsing auth JID: %w", err) |
| 74 |
} |
| 75 |
|
| 76 |
var stream io.ReadWriter = conn |
| 77 |
|
| 78 |
features := []mxmpp.StreamFeature{} |
| 79 |
|
| 80 |
if cfg.implicitTLS() { |
| 81 |
tlsConn := tls.Client(conn, newTLSConfig(cfg)) |
| 82 |
if err := tlsConn.HandshakeContext(ctx); err != nil { |
| 83 |
return nil, fmt.Errorf("TLS handshake: %w", err) |
| 84 |
} |
| 85 |
|
| 86 |
stream = tlsConn |
| 87 |
} else if cfg.useTLS() { |
| 88 |
features = append(features, mxmpp.StartTLS(newTLSConfig(cfg))) |
| 89 |
} |
| 90 |
|
| 91 |
saslFeature := mxmpp.SASL("", cfg.Password, |
| 92 |
sasl.ScramSha256Plus, |
| 93 |
sasl.ScramSha256, |
| 94 |
sasl.ScramSha1Plus, |
| 95 |
sasl.ScramSha1, |
| 96 |
sasl.Plain, |
| 97 |
) |
| 98 |
if cfg.DisableTLS { |
| 99 |
// Mellium's SASL feature requires a secured stream by default. Plaintext |
| 100 |
// is an explicit opt-in, so allow SASL before TLS. |
| 101 |
saslFeature.Necessary = 0 |
| 102 |
} |
| 103 |
|
| 104 |
features = append(features, saslFeature, mxmpp.BindResource()) |
| 105 |
|
| 106 |
session, err := mxmpp.NewClientSession(ctx, origin, stream, features...) |
| 107 |
if err != nil { |
| 108 |
return nil, wrapNegotiateError(err) |
| 109 |
} |
| 110 |
|
| 111 |
mucClient := &muc.Client{} |
| 112 |
handler := xmux.New(stanza.NSClient, muc.HandleClient(mucClient)) |
| 113 |
clientSession := &melliumSession{session: session, mucClient: mucClient} |
| 114 |
|
| 115 |
go func() { |
| 116 |
if serveErr := session.Serve(handler); serveErr != nil { |
| 117 |
return |
| 118 |
} |
| 119 |
}() |
| 120 |
|
| 121 |
return clientSession, nil |
| 122 |
} |
| 123 |
|
| 124 |
// newTLSConfig builds a TLS config from cfg. |
| 125 |
// |
| 126 |
// TLS 1.2 is the minimum version. [Config.SkipTLSVerify] is copied onto |
| 127 |
// InsecureSkipVerify for self-signed or internal servers. |
| 128 |
// |
| 129 |
// Parameters: |
| 130 |
// - cfg: The service configuration supplying Host and SkipTLSVerify. |
| 131 |
// |
| 132 |
// Returns: |
| 133 |
// - A TLS config with TLS 1.2 as the minimum version. |
| 134 |
func newTLSConfig(cfg *Config) *tls.Config { |
| 135 |
return &tls.Config{ |
| 136 |
ServerName: cfg.Host, |
| 137 |
MinVersion: tls.VersionTLS12, |
| 138 |
InsecureSkipVerify: cfg.SkipTLSVerify, |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
func wrapNegotiateError(err error) error { |
| 143 |
if isAuthFailure(err) { |
| 144 |
return fmt.Errorf("%w: %w", ErrAuthenticationFailed, err) |
| 145 |
} |
| 146 |
|
| 147 |
return fmt.Errorf("negotiating XMPP session: %w", err) |
| 148 |
} |
| 149 |
|
| 150 |
func isAuthFailure(err error) bool { |
| 151 |
text := strings.ToLower(err.Error()) |
| 152 |
|
| 153 |
return strings.Contains(text, "not-authorized") || |
| 154 |
strings.Contains(text, "invalid username") || |
| 155 |
strings.Contains(text, "invalid-authzid") || |
| 156 |
strings.Contains(text, "credentials-expired") || |
| 157 |
strings.Contains(text, "account-disabled") || |
| 158 |
strings.Contains(text, "mechanism-too-weak") || |
| 159 |
strings.Contains(text, "temporary-auth-failure") |
| 160 |
} |
| 161 |
|
| 162 |
// Close ends the XMPP session and the underlying connection. |
| 163 |
// |
| 164 |
// Returns: |
| 165 |
// - Combined close errors, or nil when the session is already unset. |
| 166 |
func (s *melliumSession) Close() error { |
| 167 |
if s.session == nil { |
| 168 |
return nil |
| 169 |
} |
| 170 |
|
| 171 |
err := s.session.Close() |
| 172 |
if conn := s.session.Conn(); conn != nil { |
| 173 |
err = errors.Join(err, conn.Close()) |
| 174 |
} |
| 175 |
|
| 176 |
return err |
| 177 |
} |
| 178 |
|
| 179 |
// SendChat sends a type=chat message to to. |
| 180 |
// |
| 181 |
// Parameters: |
| 182 |
// - ctx: Parent context for encoding the stanza. |
| 183 |
// - to: Recipient JID. |
| 184 |
// - body: Message body. |
| 185 |
// |
| 186 |
// Returns: |
| 187 |
// - An error if the JID is invalid or encoding fails. |
| 188 |
func (s *melliumSession) SendChat(ctx context.Context, to, body string) error { |
| 189 |
toJID, err := jid.Parse(to) |
| 190 |
if err != nil { |
| 191 |
return fmt.Errorf("%w: %s", ErrInvalidRecipientJID, to) |
| 192 |
} |
| 193 |
|
| 194 |
msg := messageBody{ |
| 195 |
XMLName: xml.Name{Space: "", Local: "message"}, |
| 196 |
To: toJID.String(), |
| 197 |
Type: string(stanza.ChatMessage), |
| 198 |
Body: body, |
| 199 |
} |
| 200 |
if err := s.session.Encode(ctx, msg); err != nil { |
| 201 |
return fmt.Errorf("sending chat message: %w", err) |
| 202 |
} |
| 203 |
|
| 204 |
return nil |
| 205 |
} |
| 206 |
|
| 207 |
// SendToRoom joins room, sends a groupchat message, and leaves. |
| 208 |
// |
| 209 |
// Join waits for self-presence before the message is sent. password is used |
| 210 |
// only for protected rooms. |
| 211 |
// |
| 212 |
// Parameters: |
| 213 |
// - ctx: Parent context for join, send, and leave. |
| 214 |
// - room: MUC room JID. |
| 215 |
// - nick: Nickname used when joining. |
| 216 |
// - password: Optional room password. |
| 217 |
// - body: Message body. |
| 218 |
// |
| 219 |
// Returns: |
| 220 |
// - An error if join, send, or leave fails. |
| 221 |
func (s *melliumSession) SendToRoom(ctx context.Context, room, nick, password, body string) error { |
| 222 |
roomJID, err := jid.Parse(room) |
| 223 |
if err != nil { |
| 224 |
return fmt.Errorf("%w: %s", ErrInvalidRoomJID, room) |
| 225 |
} |
| 226 |
|
| 227 |
occupancy, err := roomJID.WithResource(nick) |
| 228 |
if err != nil { |
| 229 |
return fmt.Errorf("joining MUC %s: %w", room, err) |
| 230 |
} |
| 231 |
|
| 232 |
opts := []muc.Option{muc.MaxHistory(0)} |
| 233 |
if password != "" { |
| 234 |
opts = append(opts, muc.Password(password)) |
| 235 |
} |
| 236 |
|
| 237 |
channel, err := s.mucClient.Join(ctx, occupancy, s.session, opts...) |
| 238 |
if err != nil { |
| 239 |
return fmt.Errorf("joining MUC %s: %w", room, err) |
| 240 |
} |
| 241 |
|
| 242 |
msg := messageBody{ |
| 243 |
XMLName: xml.Name{Space: "", Local: "message"}, |
| 244 |
To: roomJID.Bare().String(), |
| 245 |
Type: string(stanza.GroupChatMessage), |
| 246 |
Body: body, |
| 247 |
} |
| 248 |
if err := s.session.Encode(ctx, msg); err != nil { |
| 249 |
leaveErr := channel.Leave(ctx, "") |
| 250 |
|
| 251 |
return errors.Join(fmt.Errorf("sending groupchat message: %w", err), leaveErr) |
| 252 |
} |
| 253 |
|
| 254 |
if err := channel.Leave(ctx, ""); err != nil { |
| 255 |
return fmt.Errorf("leaving MUC %s: %w", room, err) |
| 256 |
} |
| 257 |
|
| 258 |
return nil |
| 259 |
} |