| 1 |
package signal |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"crypto/tls" |
| 7 |
"encoding/json/v2" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"net" |
| 11 |
"net/http" |
| 12 |
"net/url" |
| 13 |
"strconv" |
| 14 |
"strings" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/nicholas-fedor/shoutrrr/internal/meta" |
| 18 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 19 |
) |
| 20 |
|
| 21 |
const ( |
| 22 |
contentType = "application/json" |
| 23 |
defaultHTTPTimeout = 30 * time.Second |
| 24 |
// maxResponseBodySize caps how much of a /v2/send body we buffer. |
| 25 |
maxResponseBodySize = 4 * 1024 |
| 26 |
) |
| 27 |
|
| 28 |
// buildAPIURL constructs the Signal API endpoint URL from the configuration. |
| 29 |
// |
| 30 |
// Parameters: |
| 31 |
// - config: the service configuration |
| 32 |
// |
| 33 |
// Returns: |
| 34 |
// - string: the full API endpoint URL |
| 35 |
func (s *Service) buildAPIURL(config *Config) string { |
| 36 |
scheme := "https" |
| 37 |
if config.DisableTLS { |
| 38 |
scheme = "http" |
| 39 |
} |
| 40 |
|
| 41 |
return (&url.URL{ |
| 42 |
Scheme: scheme, |
| 43 |
Host: net.JoinHostPort(config.Host, strconv.Itoa(config.Port)), |
| 44 |
Path: "/v2/send", |
| 45 |
}).String() |
| 46 |
} |
| 47 |
|
| 48 |
// createRequest builds the HTTP request for the Signal API. |
| 49 |
// |
| 50 |
// Parameters: |
| 51 |
// - config: the service configuration |
| 52 |
// - payload: the payload to send (passed as pointer for efficiency) |
| 53 |
// |
| 54 |
// Returns: |
| 55 |
// - *http.Request: the constructed HTTP request |
| 56 |
// - context.CancelFunc: a function to cancel the request context |
| 57 |
// - error: if request creation fails, nil otherwise |
| 58 |
func (s *Service) createRequest( |
| 59 |
config *Config, |
| 60 |
payload *sendMessagePayload, |
| 61 |
) (*http.Request, context.CancelFunc, error) { |
| 62 |
apiURL := s.buildAPIURL(config) |
| 63 |
|
| 64 |
jsonData, err := json.Marshal(payload) |
| 65 |
if err != nil { |
| 66 |
return nil, nil, fmt.Errorf("marshaling payload to JSON: %w", err) |
| 67 |
} |
| 68 |
|
| 69 |
ctx, cancel := context.WithTimeout( |
| 70 |
context.Background(), |
| 71 |
defaultHTTPTimeout, |
| 72 |
) |
| 73 |
|
| 74 |
req, err := http.NewRequestWithContext( |
| 75 |
ctx, |
| 76 |
http.MethodPost, |
| 77 |
apiURL, |
| 78 |
bytes.NewReader(jsonData), |
| 79 |
) |
| 80 |
if err != nil { |
| 81 |
cancel() |
| 82 |
|
| 83 |
return nil, nil, fmt.Errorf("creating HTTP request: %w", err) |
| 84 |
} |
| 85 |
|
| 86 |
req.Header.Set("Content-Type", contentType) |
| 87 |
req.Header.Set("User-Agent", meta.UserAgent()) |
| 88 |
s.setAuthentication(req, config) |
| 89 |
|
| 90 |
return req, cancel, nil |
| 91 |
} |
| 92 |
|
| 93 |
// newHTTPClient returns the default HTTP client for Signal requests. |
| 94 |
// |
| 95 |
// Parameters: |
| 96 |
// - skipTLSVerify: when true, skip certificate-chain and hostname verification |
| 97 |
// |
| 98 |
// Returns: |
| 99 |
// - An HTTP client with a 30s timeout, TLS 1.2 minimum, and optional skip-verify. |
| 100 |
func (s *Service) newHTTPClient(skipTLSVerify bool) types.HTTPClient { |
| 101 |
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} |
| 102 |
if skipTLSVerify { |
| 103 |
tlsConfig.InsecureSkipVerify = true |
| 104 |
|
| 105 |
s.Log("Warning: TLS verification is disabled, making connections insecure") |
| 106 |
} |
| 107 |
|
| 108 |
transport := &http.Transport{TLSClientConfig: tlsConfig} |
| 109 |
if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok { |
| 110 |
transport = defaultTransport.Clone() |
| 111 |
transport.TLSClientConfig = tlsConfig |
| 112 |
} |
| 113 |
|
| 114 |
return &http.Client{ |
| 115 |
Timeout: defaultHTTPTimeout, |
| 116 |
Transport: transport, |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// parseResponse logs the success timestamp from the Signal API body. |
| 121 |
// |
| 122 |
// Parameters: |
| 123 |
// - body: the raw response body |
| 124 |
func (s *Service) parseResponse(body []byte) { |
| 125 |
timestamp, err := parseTimestamp(body) |
| 126 |
if err != nil { |
| 127 |
s.Logf("Warning: failed to parse response: %v", err) |
| 128 |
|
| 129 |
return |
| 130 |
} |
| 131 |
|
| 132 |
s.Logf("Message sent successfully at timestamp %d", timestamp) |
| 133 |
} |
| 134 |
|
| 135 |
// parseTimestamp reads a numeric or quoted JSON timestamp from a 2xx body. |
| 136 |
// |
| 137 |
// Parameters: |
| 138 |
// - body: the raw response body |
| 139 |
// |
| 140 |
// Returns: |
| 141 |
// - int64: the timestamp value |
| 142 |
// - error: if neither form can be parsed |
| 143 |
func parseTimestamp(body []byte) (int64, error) { |
| 144 |
var numeric struct { |
| 145 |
Timestamp *int64 `json:"timestamp"` |
| 146 |
} |
| 147 |
if err := json.Unmarshal(body, &numeric); err == nil && numeric.Timestamp != nil { |
| 148 |
return *numeric.Timestamp, nil |
| 149 |
} |
| 150 |
|
| 151 |
var quoted struct { |
| 152 |
Timestamp string `json:"timestamp"` |
| 153 |
} |
| 154 |
if err := json.Unmarshal(body, "ed); err != nil { |
| 155 |
return 0, fmt.Errorf("decoding timestamp: %w", err) |
| 156 |
} |
| 157 |
|
| 158 |
n, err := strconv.ParseInt(quoted.Timestamp, 10, 64) |
| 159 |
if err != nil { |
| 160 |
return 0, fmt.Errorf("parsing timestamp %q: %w", quoted.Timestamp, err) |
| 161 |
} |
| 162 |
|
| 163 |
return n, nil |
| 164 |
} |
| 165 |
|
| 166 |
// sendRequest executes the HTTP request and processes the response. |
| 167 |
// |
| 168 |
// Parameters: |
| 169 |
// - req: the HTTP request to execute |
| 170 |
// - config: the per-send configuration used to select the HTTP client |
| 171 |
// |
| 172 |
// Returns: |
| 173 |
// - error: if the request fails or returns a non-success status, nil otherwise |
| 174 |
func (s *Service) sendRequest(req *http.Request, config *Config) error { |
| 175 |
client := s.httpClientFor(config) |
| 176 |
|
| 177 |
resp, err := client.Do(req) |
| 178 |
if err != nil { |
| 179 |
return fmt.Errorf("sending HTTP request: %w", err) |
| 180 |
} |
| 181 |
|
| 182 |
defer func() { _ = resp.Body.Close() }() |
| 183 |
|
| 184 |
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize+1)) |
| 185 |
if err != nil { |
| 186 |
return fmt.Errorf("reading response body: %w", err) |
| 187 |
} |
| 188 |
|
| 189 |
truncated := len(body) > maxResponseBodySize |
| 190 |
if truncated { |
| 191 |
body = body[:maxResponseBodySize] |
| 192 |
} |
| 193 |
|
| 194 |
if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 195 |
return formatSendError(resp.StatusCode, body, truncated) |
| 196 |
} |
| 197 |
|
| 198 |
s.parseResponse(body) |
| 199 |
|
| 200 |
return nil |
| 201 |
} |
| 202 |
|
| 203 |
// httpClientFor returns the client for this send. |
| 204 |
// An injected client is used as-is. The default client matches config.SkipTLSVerify. |
| 205 |
// |
| 206 |
// Parameters: |
| 207 |
// - config: the per-send configuration |
| 208 |
// |
| 209 |
// Returns: |
| 210 |
// - types.HTTPClient: the client used for this request |
| 211 |
func (s *Service) httpClientFor(config *Config) types.HTTPClient { |
| 212 |
if s.injectedHTTPClient && s.httpClient != nil { |
| 213 |
return s.httpClient |
| 214 |
} |
| 215 |
|
| 216 |
skip := config != nil && config.SkipTLSVerify |
| 217 |
initializedSkip := s.Config != nil && s.Config.SkipTLSVerify |
| 218 |
|
| 219 |
if s.httpClient != nil && skip == initializedSkip { |
| 220 |
return s.httpClient |
| 221 |
} |
| 222 |
|
| 223 |
return s.newHTTPClient(skip) |
| 224 |
} |
| 225 |
|
| 226 |
// setAuthentication configures HTTP authentication headers on the request. |
| 227 |
// disabletls and skiptlsverify send Bearer or Basic credentials over an |
| 228 |
// unverified or cleartext transport. Use those modes only on trusted networks. |
| 229 |
// |
| 230 |
// Parameters: |
| 231 |
// - req: the HTTP request to modify |
| 232 |
// - config: the service configuration containing credentials |
| 233 |
func (s *Service) setAuthentication(req *http.Request, config *Config) { |
| 234 |
if config.Token != "" { |
| 235 |
req.Header.Set("Authorization", "Bearer "+config.Token) |
| 236 |
} else if config.User != "" { |
| 237 |
req.SetBasicAuth(config.User, config.Password) |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
// formatSendError builds an error from a non-success API response. |
| 242 |
// |
| 243 |
// Parameters: |
| 244 |
// - statusCode: the HTTP status code |
| 245 |
// - body: the raw response body |
| 246 |
// - truncated: whether the body was cut at maxResponseBodySize |
| 247 |
// |
| 248 |
// Returns: |
| 249 |
// - error: ErrSendFailed wrapped with status and API details |
| 250 |
func formatSendError(statusCode int, body []byte, truncated bool) error { |
| 251 |
suffix := "" |
| 252 |
if truncated { |
| 253 |
suffix = " [truncated]" |
| 254 |
} |
| 255 |
|
| 256 |
var apiErr sendErrorResponse |
| 257 |
if err := json.Unmarshal(body, &apiErr); err == nil && apiErr.Error != "" { |
| 258 |
var details []string |
| 259 |
if apiErr.Account != "" { |
| 260 |
details = append(details, "account "+apiErr.Account) |
| 261 |
} |
| 262 |
|
| 263 |
if len(apiErr.ChallengeTokens) > 0 { |
| 264 |
details = append(details, "challenge tokens: "+strings.Join(apiErr.ChallengeTokens, ",")) |
| 265 |
} |
| 266 |
|
| 267 |
if len(details) > 0 { |
| 268 |
return fmt.Errorf( |
| 269 |
"%w: server returned status %d: %s (%s)%s", |
| 270 |
ErrSendFailed, |
| 271 |
statusCode, |
| 272 |
apiErr.Error, |
| 273 |
strings.Join(details, "; "), |
| 274 |
suffix, |
| 275 |
) |
| 276 |
} |
| 277 |
|
| 278 |
return fmt.Errorf("%w: server returned status %d: %s%s", ErrSendFailed, statusCode, apiErr.Error, suffix) |
| 279 |
} |
| 280 |
|
| 281 |
if len(body) > 0 { |
| 282 |
return fmt.Errorf( |
| 283 |
"%w: server returned status %d: %s%s", |
| 284 |
ErrSendFailed, |
| 285 |
statusCode, |
| 286 |
bytes.TrimSpace(body), |
| 287 |
suffix, |
| 288 |
) |
| 289 |
} |
| 290 |
|
| 291 |
return fmt.Errorf("%w: server returned status %d%s", ErrSendFailed, statusCode, suffix) |
| 292 |
} |