bare_host.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package routerstore
  2. import (
  3. "database/sql"
  4. "log"
  5. "net"
  6. "regexp"
  7. "strings"
  8. )
  9. // bareHostRe is the contract the unit form applies to a host
  10. // (httpapi.validateHost): an IP or a hostname, never a URL.
  11. var bareHostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
  12. // BareHost reduces the host typed in an integration form to the address of a
  13. // router unit. The integration keeps the full URL because the pusher needs it,
  14. // but the unit only accepts an IP or a hostname: the unit form rejects a scheme
  15. // and the ping probe cannot resolve one (#1968). When the address is not
  16. // usable, the input comes back untouched, so an odd value keeps failing where
  17. // it already failed instead of turning into something else.
  18. func BareHost(raw string) string {
  19. h := strings.TrimSpace(raw)
  20. if i := strings.Index(h, "://"); i >= 0 {
  21. h = h[i+3:]
  22. }
  23. if i := strings.LastIndex(h, "@"); i >= 0 {
  24. h = h[i+1:]
  25. }
  26. if i := strings.IndexAny(h, "/?#"); i >= 0 {
  27. h = h[:i]
  28. }
  29. if host, _, err := net.SplitHostPort(h); err == nil {
  30. h = host
  31. }
  32. h = strings.Trim(h, "[]")
  33. if h == "" || !bareHostRe.MatchString(h) {
  34. return strings.TrimSpace(raw)
  35. }
  36. return h
  37. }
  38. // NormalizeExternalHosts rewrites the host of the external units created before
  39. // #1968, which stored the integration URL and could not be edited afterwards.
  40. // It returns how many rows changed and is safe to run on every start.
  41. func NormalizeExternalHosts(db *sql.DB) int {
  42. rows, err := db.Query(`SELECT id, host FROM routers WHERE type = 'external' AND host LIKE '%://%'`)
  43. if err != nil {
  44. log.Printf("[netpulse] warning: could not read the host of external routers: %v", err)
  45. return 0
  46. }
  47. type pending struct {
  48. id string
  49. host string
  50. }
  51. var fixes []pending
  52. for rows.Next() {
  53. var p pending
  54. if err := rows.Scan(&p.id, &p.host); err != nil {
  55. continue
  56. }
  57. if bare := BareHost(p.host); bare != p.host {
  58. p.host = bare
  59. fixes = append(fixes, p)
  60. }
  61. }
  62. rows.Close()
  63. for _, f := range fixes {
  64. if _, err := db.Exec(`UPDATE routers SET host = ? WHERE id = ?`, f.host, f.id); err != nil {
  65. log.Printf("[netpulse] warning: could not normalize the host of %s: %v", f.id, err)
  66. }
  67. }
  68. return len(fixes)
  69. }