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