Debian Codegraph @

pkg/services/push/mqtt/mqtt_service.go

raw
1 package mqtt
2
3 import (
4 "context"
5 "crypto/tls"
6 "fmt"
7 "net"
8 "net/url"
9 "sync"
10 "time"
11
12 "github.com/eclipse/paho.golang/autopaho"
13 "github.com/eclipse/paho.golang/packets"
14 "github.com/eclipse/paho.golang/paho"
15
16 "github.com/nicholas-fedor/shoutrrr/pkg/format"
17 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
18 "github.com/nicholas-fedor/shoutrrr/pkg/types"
19 )
20
21 // Service implements the notification service interface for MQTT brokers.
22 // It manages the connection lifecycle and message publishing to MQTT topics.
23 type Service struct {
24 // Standard provides base service functionality including logging.
25 standard.Standard
26
27 // Config holds the MQTT connection and publishing settings.
28 Config *Config
29 // pkr resolves property keys for configuration updates from URL parameters.
30 pkr format.PropKeyResolver
31 // connectionManager is the underlying MQTT connection manager for broker communication.
32 connectionManager ConnectionManager
33 // dialContext, if non-nil, is used for the MQTT TCP dial via AttemptConnection.
34 dialContext types.DialContextFunc
35 // clientMutex protects the connection initialization to ensure thread-safe
36 // lazy initialization while allowing retry on transient failures.
37 clientMutex sync.Mutex
38 // connectionInitialized indicates whether the MQTT client has been successfully
39 // initialized. This is set to true only after connectionManager is assigned.
40 connectionInitialized bool
41 // ctx is the context for managing the connection lifecycle.
42 // This is required to ensure that cancel() properly terminates the connection
43 // used by autopaho. The context is created alongside the cancel function in
44 // getCancel() and used in initClient() for the connection manager.
45 //
46 //nolint:containedctx // Required for proper cancellation wiring with autopaho
47 ctx context.Context
48 // cancel is the cancel function for cleaning up the connection.
49 cancel context.CancelFunc
50 // cancelOnce ensures the cancel function is initialized exactly once.
51 cancelOnce sync.Once
52 // closeOnce ensures the Close method is called exactly once.
53 closeOnce sync.Once
54 // closeErr stores any error from the close operation for return on subsequent calls.
55 closeErr error
56 // urlScheme stores the URL scheme from the config URL for scheme detection.
57 // This allows the scheme (mqtt or mqtts) to be used as the primary determinant
58 // for TLS handling, with port as secondary.
59 urlScheme string
60 }
61
62 // publishTimeout defines the maximum time in seconds to wait for message publication.
63 // This prevents indefinite blocking when the broker is unresponsive during publish operations.
64 const publishTimeout = 10
65
66 // keepAliveInterval defines the interval in seconds between keep-alive packets.
67 // This maintains the connection and detects dead peers.
68 const keepAliveInterval = 20
69
70 // sessionExpiryInterval defines the session expiry interval in seconds for MQTT v5.
71 // After this period, the broker will discard session state.
72 const sessionExpiryInterval = 60
73
74 // disconnectTimeout defines the maximum time in seconds to wait for graceful disconnection.
75 // This prevents indefinite blocking when the broker is unresponsive during close operations.
76 const disconnectTimeout = 5
77
78 var _ types.DialContextSetter = (*Service)(nil)
79
80 // Close gracefully shuts down the MQTT service by disconnecting from the broker
81 // and canceling the connection context.
82 //
83 // This method is idempotent - multiple calls are safe and will not cause panics
84 // or errors. The first call performs the actual cleanup; subsequent calls return
85 // the same result as the first call.
86 //
87 // The shutdown process:
88 // 1. Disconnects the connection manager with a 5-second timeout
89 // 2. Cancels the context to signal termination to any goroutines
90 //
91 // Returns an error if the disconnect fails, wrapped with context about the failure.
92 // Returns nil on successful cleanup or if already closed without error.
93 func (s *Service) Close() error {
94 s.closeOnce.Do(func() {
95 // Disconnect the connection manager if it was initialized.
96 if s.connectionManager != nil {
97 // Create a context with timeout for the disconnect operation.
98 ctx, cancel := context.WithTimeout(
99 context.Background(),
100 disconnectTimeout*time.Second,
101 )
102 defer cancel()
103
104 // Attempt to disconnect from the broker.
105 if err := s.connectionManager.Disconnect(ctx); err != nil {
106 s.closeErr = fmt.Errorf("disconnecting from MQTT broker: %w", err)
107
108 return
109 }
110 }
111
112 // Cancel the context to signal termination.
113 // The cancel function is initialized by getCancel(), which is called
114 // during initClient(). If the client was never initialized, cancel is nil.
115 if s.cancel != nil {
116 s.cancel()
117 }
118 })
119
120 return s.closeErr
121 }
122
123 // GetID returns the service identifier used for registration and URL scheme matching.
124 // This identifier is used to route URLs to the correct service implementation.
125 //
126 // Returns the MQTT scheme constant "mqtt".
127 func (s *Service) GetID() string {
128 return Scheme
129 }
130
131 // Initialize configures the MQTT service with settings from a URL and sets up logging.
132 // The URL format is: mqtt://[username:password@]host[:port]/topic[?options]
133 //
134 // The MQTT client is lazily initialized on the first call to Send, allowing runtime
135 // configuration changes via UpdateConfigFromParams to take effect before the client
136 // connection is established. This means Host, Port, Username, Password, and TLS
137 // settings can be modified through params in the first Send call.
138 //
139 // Parameters:
140 // - serviceURL: The configuration URL containing broker address, credentials, and topic
141 // - logger: The logger instance for recording service events and errors
142 //
143 // Returns an error if URL parsing fails or required fields are missing.
144 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
145 // Set up logging for the service
146 s.SetLogger(logger)
147
148 // Store the URL scheme for use in initClient()
149 // This allows the scheme (mqtt or mqtts) to be used as the primary
150 // determinant for TLS handling
151 s.urlScheme = serviceURL.Scheme
152
153 // Initialize the configuration struct with default values
154 s.Config = &Config{}
155
156 // Create a property key resolver for mapping URL parameters to config fields
157 s.pkr = format.NewPropKeyResolver(s.Config)
158
159 // Apply default values from struct tags to the configuration
160 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
161 return fmt.Errorf("setting default config properties: %w", err)
162 }
163
164 // Parse the configuration URL and populate the config struct
165 if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
166 return fmt.Errorf("parsing configuration URL: %w", err)
167 }
168
169 // Note: The MQTT client is lazily initialized on the first Send call,
170 // allowing runtime configuration changes to take effect before connection.
171
172 return nil
173 }
174
175 // Send delivers a message to the configured MQTT topic.
176 // It handles connection establishment if needed and publishes the message
177 // with the configured QoS level and retention settings.
178 //
179 // On the first call, this method triggers lazy initialization of the MQTT client,
180 // applying any configuration changes from params before creating the client. This allows
181 // Host, Port, Username, Password, and TLS settings to be overridden at runtime.
182 // Subsequent calls reuse the existing client; config changes after the first Send
183 // only affect message-related settings (Topic, QoS, Retained), not connection settings.
184 //
185 // Parameters:
186 // - message: The notification message to publish to the topic
187 // - params: Optional runtime parameters to override config settings
188 //
189 // Returns an error if connection fails or publishing encounters an error.
190 func (s *Service) Send(message string, params *types.Params) error {
191 // Apply any runtime parameter overrides to the configuration
192 if err := s.pkr.UpdateConfigFromParams(s.Config, params); err != nil {
193 return fmt.Errorf("updating config from params: %w", err)
194 }
195
196 // Validate QoS value is within MQTT protocol range (0-2)
197 if !s.Config.QoS.IsValid() {
198 return fmt.Errorf(
199 "validating QoS value %d: %w",
200 s.Config.QoS,
201 ErrInvalidQoS,
202 )
203 }
204
205 // Ensure the MQTT client is initialized.
206 // This now returns an error that can be retried on transient failures.
207 if err := s.initClient(); err != nil {
208 return fmt.Errorf("initializing MQTT client: %w", err)
209 }
210
211 // Create a context with timeout for the publish operation
212 ctx, cancel := context.WithTimeout(
213 context.Background(),
214 publishTimeout*time.Second,
215 )
216 defer cancel()
217
218 // Wait for connection to be established
219 if err := s.connectionManager.AwaitConnection(ctx); err != nil {
220 return fmt.Errorf("connecting to MQTT broker: %w", err)
221 }
222
223 // Publish the message to the configured topic with QoS and retention settings
224 //nolint:exhaustruct_v5 // paho.Publish PacketID is auto-generated, Properties optional for MQTT v5
225 resp, err := s.connectionManager.Publish(
226 ctx,
227 &paho.Publish{
228 Topic: s.Config.Topic,
229 QoS: byte(s.Config.QoS), //nolint:gosec // QoS validated to 0-2
230 Retain: s.Config.Retained,
231 Payload: []byte(message),
232 },
233 )
234 if err != nil {
235 return fmt.Errorf(
236 "publishing to MQTT topic %q: %w",
237 s.Config.Topic,
238 err,
239 )
240 }
241
242 // Handle MQTT v5 reason codes from the publish response.
243 // Per MQTT v5 spec, reason codes >= 0x80 indicate failures that should be
244 // returned as errors, while codes 0x01-0x7F are non-fatal warnings.
245 if resp != nil && resp.ReasonCode != 0 {
246 if IsFailureCode(resp.ReasonCode) {
247 // Failure codes (>= 0x80) should be returned as errors to the caller
248 return PublishError{
249 ReasonCode: resp.ReasonCode,
250 ReasonString: resp.Properties.ReasonString,
251 }
252 }
253
254 // Non-fatal codes (> 0 but < 0x80) are logged as warnings but don't fail
255 s.Logf("Warning: Publish completed with reason code %d", resp.ReasonCode)
256 }
257
258 // Log successful publication for debugging and monitoring
259 s.Logf("Successfully published message to topic %q", s.Config.Topic)
260
261 return nil
262 }
263
264 // SetConnectionManager sets the connection manager for the service.
265 //
266 // Parameters:
267 // - cm: The ConnectionManager implementation to use
268 //
269 // This method should only be called before any Send operations to avoid
270 // race conditions with lazy initialization.
271 func (s *Service) SetConnectionManager(cm ConnectionManager) {
272 s.connectionManager = cm
273 s.connectionInitialized = cm != nil
274 }
275
276 // SetDialContext sets a custom dial function for MQTT TCP connections.
277 //
278 // TLS wrapping for mqtts still happens after the TCP dial.
279 // A nil dial restores the default autopaho dialer, including all_proxy handling.
280 // This method should only be called before any Send operations to avoid
281 // race conditions with lazy initialization.
282 //
283 // Parameters:
284 // - dial: The dial function. Must be safe for concurrent use when non-nil.
285 func (s *Service) SetDialContext(dial types.DialContextFunc) {
286 s.dialContext = dial
287 }
288
289 // attemptConnection dials the MQTT broker using [Service.dialContext] and
290 // optionally wraps the connection in TLS.
291 //
292 // Parameters:
293 // - ctx: Context that bounds dialing and the TLS handshake.
294 // - cfg: Autopaho client configuration providing TLS settings.
295 // - serverURL: Broker URL whose host and port are dialed.
296 //
297 // Returns:
298 // - A connected [net.Conn], TLS-wrapped when cfg.TlsCfg is set, always
299 // wrapped for thread-safe writes.
300 // - An error if the custom dialer is unset, dialing fails, or the handshake fails.
301 func (s *Service) attemptConnection(
302 ctx context.Context,
303 cfg autopaho.ClientConfig, //nolint:gocritic // hugeParam: matches autopaho.AttemptConnection
304 serverURL *url.URL,
305 ) (net.Conn, error) {
306 if s.dialContext == nil {
307 return nil, ErrNoDialContext
308 }
309
310 conn, err := s.dialContext(ctx, "tcp", serverURL.Host)
311 if err != nil {
312 return nil, fmt.Errorf("dialing MQTT broker %q: %w", serverURL.Host, err)
313 }
314
315 if cfg.TlsCfg == nil {
316 return packets.NewThreadSafeConn(conn), nil
317 }
318
319 tlsCfg := cfg.TlsCfg.Clone()
320 if tlsCfg.ServerName == "" {
321 tlsCfg.ServerName = serverURL.Hostname()
322 }
323
324 tlsConn := tls.Client(conn, tlsCfg)
325 if err := tlsConn.HandshakeContext(ctx); err != nil {
326 _ = conn.Close()
327
328 return nil, fmt.Errorf("TLS handshake with MQTT broker %q: %w", serverURL.Host, err)
329 }
330
331 return packets.NewThreadSafeConn(tlsConn), nil
332 }
333
334 // createTLSConfig builds a TLS configuration based on the service settings.
335 // It enforces TLS 1.2 as the minimum version and optionally skips certificate
336 // verification when DisableTLSVerification is set (useful for testing or
337 // self-signed certificates).
338 //
339 // Returns a *tls.Config ready for use with the MQTT client.
340 func (s *Service) createTLSConfig() *tls.Config {
341 // Start with a base config requiring TLS 1.2 or higher
342 config := &tls.Config{
343 MinVersion: tls.VersionTLS12,
344 }
345
346 // Skip certificate verification if explicitly disabled
347 // Warning: This makes the connection vulnerable to man-in-the-middle attacks
348 if s.Config.DisableTLSVerification {
349 config.InsecureSkipVerify = true
350
351 // Log a warning about the security implications
352 s.Log("Warning: TLS verification is disabled, making connections insecure")
353 }
354
355 return config
356 }
357
358 // getCancel returns the cancel function, initializing both the context and cancel
359 // function exactly once. The context is stored in s.ctx for use by initClient,
360 // ensuring that calling s.cancel() will properly cancel the connection lifecycle.
361 //
362 // Returns the cancel function for connection cleanup.
363 func (s *Service) getCancel() context.CancelFunc {
364 s.cancelOnce.Do(func() {
365 // Create a cancellable context for managing the connection lifecycle.
366 // Both ctx and cancel are stored so that cancel() can terminate
367 // operations using this context.
368 s.ctx, s.cancel = context.WithTimeout(
369 context.Background(),
370 publishTimeout*time.Second,
371 )
372 })
373
374 return s.cancel
375 }
376
377 // getDefaultPortForScheme returns the standard port number for a given MQTT scheme.
378 // This is used for automatic scheme detection when the port matches a known default.
379 //
380 // Parameters:
381 // - scheme: The MQTT scheme ("mqtt" or "mqtts")
382 //
383 // Returns the default port number (1883 for mqtt, 8883 for mqtts).
384 func (s *Service) getDefaultPortForScheme(scheme string) int {
385 switch scheme {
386 case SchemeTLS:
387 // Return the secure MQTT port for mqtts scheme
388 return DefaultTLSPort
389 default:
390 // Return the standard MQTT port for all other schemes
391 return DefaultPort
392 }
393 }
394
395 // initClient creates and configures the MQTT client using a mutex-protected pattern.
396 // This ensures thread-safe lazy initialization while allowing retry on transient failures.
397 //
398 // Unlike sync.Once, this pattern allows initialization to be retried if it fails,
399 // preventing permanent failure states when transient errors occur during url.Parse
400 // or autopaho.NewConnection.
401 //
402 // The client is lazily initialized on the first call to Send, not during Initialize.
403 // This allows runtime configuration changes (Host, Port, Username, Password, TLS settings)
404 // to be applied via UpdateConfigFromParams before the client is created.
405 //
406 // Once successfully initialized, the client is reused for all subsequent Send calls.
407 // The mutex-protected pattern ensures that:
408 // - Only one goroutine can attempt initialization at a time
409 // - Successful initialization is recorded via connectionInitialized flag
410 // - Failed initialization can be retried on subsequent calls
411 //
412 // The client is configured with:
413 // - Broker URL (with automatic scheme detection based on TLS settings)
414 // - Authentication credentials if provided
415 // - Connection timeout and callbacks for logging
416 // - TLS configuration for secure connections
417 //
418 // Returns an error if initialization fails, allowing callers to retry.
419 func (s *Service) initClient() error {
420 // Lock the mutex to ensure thread-safe initialization
421 s.clientMutex.Lock()
422 defer s.clientMutex.Unlock()
423
424 // Check if already successfully initialized
425 if s.connectionInitialized {
426 return nil
427 }
428
429 // Ensure cancel function and context are initialized.
430 // This stores both s.ctx and s.cancel for connection lifecycle management.
431 _ = s.getCancel()
432
433 // Determine the connection scheme based on URL scheme and port configuration.
434 // The URL scheme is the primary determinant, with port-based defaults as fallback.
435 // User-specified port overrides the default; scheme determines TLS handling.
436 scheme := s.urlScheme
437 port := s.Config.Port
438
439 // Apply default scheme if URL scheme is not set or is invalid
440 if scheme == "" {
441 scheme = Scheme
442 }
443
444 // Apply default port based on scheme if user didn't specify one
445 // Default: 1883 for mqtt, 8883 for mqtts
446 defaultPort := s.getDefaultPortForScheme(scheme)
447 if port == 0 {
448 port = defaultPort
449 }
450
451 // Handle scheme/port mismatches with warnings (but don't change the scheme)
452 if scheme == SchemeTLS && !s.Config.DisableTLS && port == DefaultPort {
453 // MQTTS scheme on non-TLS port (1883) - warn but keep MQTTS scheme
454 s.Logf("Warning: Using MQTTS scheme with non-TLS port %d; TLS will be attempted", port)
455 } else if scheme == Scheme && port == DefaultTLSPort {
456 // MQTT scheme on TLS port (8883) - warn but keep MQTT scheme
457 s.Logf("Warning: Using MQTT scheme with TLS port %d; TLS will not be used", port)
458 }
459
460 // Enable TLS when using secure scheme and TLS is not disabled
461 useTLS := scheme == SchemeTLS && !s.Config.DisableTLS
462
463 // Build the broker URL
464 brokerURL := fmt.Sprintf(
465 "%s://%s:%d",
466 scheme,
467 s.Config.Host,
468 port,
469 )
470
471 // Parse the broker URL for autopaho
472 serverURL, err := url.Parse(brokerURL)
473 if err != nil {
474 return fmt.Errorf(
475 "parsing broker URL %q: %w",
476 brokerURL,
477 err,
478 )
479 }
480
481 // Use the service's context for connection lifecycle management.
482 // This ensures that calling s.cancel() will properly terminate
483 // the connection when shutdown is requested.
484 ctx := s.ctx
485
486 // Create autopaho client configuration
487 //nolint:exhaustruct_v5 // autopaho.ClientConfig has many optional fields with library defaults
488 cliCfg := autopaho.ClientConfig{
489 ServerUrls: []*url.URL{serverURL},
490 KeepAlive: keepAliveInterval,
491 CleanStartOnInitialConnection: s.Config.CleanSession,
492 SessionExpiryInterval: sessionExpiryInterval,
493 //nolint:exhaustruct_v5 // remaining fields use library defaults
494 ClientID: s.Config.ClientID,
495 OnServerDisconnect: func(disconnect *paho.Disconnect) {
496 s.Logf("Server disconnected: reason code %d", disconnect.ReasonCode)
497 },
498 OnConnectionUp: func(_ *autopaho.ConnectionManager, _ *paho.Connack) {
499 s.Logf("Connected to MQTT broker at %s", brokerURL)
500 },
501 OnConnectError: func(err error) {
502 s.Logf("Connection error: %v", err)
503 },
504 }
505
506 // Set authentication credentials if username is provided
507 if s.Config.Username != "" {
508 cliCfg.ConnectUsername = s.Config.Username
509
510 // Set password if provided alongside username
511 if s.Config.Password != "" {
512 cliCfg.ConnectPassword = []byte(s.Config.Password)
513 }
514 } else if s.Config.Password != "" {
515 // Password without username creates invalid MQTT auth state
516 s.Log("Warning: Password provided without username; skipping password authentication")
517 }
518
519 // Configure TLS based on scheme and DisableTLS setting
520 if useTLS {
521 cliCfg.TlsCfg = s.createTLSConfig()
522 }
523
524 if s.dialContext != nil {
525 cliCfg.AttemptConnection = s.attemptConnection
526 }
527
528 // Create the connection manager
529 connectionManager, err := autopaho.NewConnection(ctx, cliCfg)
530 if err != nil {
531 return fmt.Errorf("creating MQTT connection: %w", err)
532 }
533
534 // Only set connectionManager and mark as initialized on success
535 s.connectionManager = connectionManager
536 s.connectionInitialized = true
537
538 return nil
539 }