func()

in go/mqtt/env.go [156:219]


func (b *connectionProviderBuilder) build() (ConnectionProvider, error) {
	if b.hostname == "" {
		if b.port != 0 || b.useTLS != nil || b.hasTLS() {
			return nil, &InvalidArgumentError{
				message: "connection configuration provided without hostname",
			}
		}
		return nil, nil
	}

	if b.port == 0 {
		b.port = 8883
	}

	if b.useTLS != nil && !*b.useTLS {
		if b.hasTLS() {
			return nil, &InvalidArgumentError{
				message: "TLS configuration provided but not using TLS",
			}
		}
		return TCPConnection(b.hostname, b.port), nil
	}

	if (b.certFile != "") != (b.keyFile != "") {
		return nil, &InvalidArgumentError{
			message: "certificate file and key file must be provided together",
		}
	}

	var tlsOpts []TLSOption

	// Bypasses hostname check in TLS config when deliberately connecting to
	// localhost.
	if b.hostname == "localhost" {
		tlsOpts = append(tlsOpts, func(
			_ context.Context,
			cfg *tls.Config,
		) error {
			cfg.InsecureSkipVerify = true // #nosec G402
			return nil
		})
	}

	if b.certFile != "" {
		if b.passFile != "" {
			tlsOpts = append(tlsOpts, WithEncryptedX509(
				b.certFile,
				b.keyFile,
				b.passFile,
			))
		} else {
			tlsOpts = append(tlsOpts, WithX509(
				b.certFile,
				b.keyFile,
			))
		}
	}

	if b.caFile != "" {
		tlsOpts = append(tlsOpts, WithCA(b.caFile))
	}

	return TLSConnection(b.hostname, b.port, tlsOpts...), nil
}