local-dns 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. ipv4_regex='^[.0-9]\+$'
  4. ipv6_regex='^[:0-9a-f]\+$'
  5. function _unbound {
  6. sudo unbound-control -c /var/lib/unbound/unbound.conf "$@"
  7. }
  8. function _helper_list_local_zones {
  9. _unbound list_local_zones | grep 'transparent$' | cut -f1 -d' '
  10. }
  11. function _alias {
  12. domain="$1"
  13. shift 1
  14. records=$(while [ $# -gt 0 ]; do
  15. target="$1"
  16. if echo "$target" | grep -q "$ipv4_regex"; then
  17. echo "$domain A $target"
  18. elif echo "$target" | grep -q "$ipv6_regex"; then
  19. echo "$domain AAAA $target"
  20. else
  21. if ! dig +noall +answer +nottlid "$target" \
  22. | grep '\<\(A\|AAAA\)\>' \
  23. | sed "s/^.*IN/$domain/" \
  24. ; then
  25. echo "Could not resolve $target" >&2
  26. exit 1
  27. fi
  28. fi
  29. shift 1
  30. done)
  31. _unbound -q local_zone_remove "$domain"
  32. if [ ! -z "$records" ]; then
  33. echo "$records" | _unbound -q local_datas
  34. fi
  35. if output=$(_unbound list_local_data | grep "$domain"); then
  36. echo "Put the following records:"
  37. echo "$output"
  38. else
  39. echo "Removed aliases for $domain"
  40. fi
  41. }
  42. function _delegate {
  43. domain="$1"
  44. server="$2"
  45. _unbound forward_add "$domain" "$server"
  46. }
  47. function _reset {
  48. _unbound reload
  49. }
  50. function _list {
  51. zones=$(_helper_list_local_zones)
  52. for domain in $zones; do
  53. _unbound list_local_data | grep "$domain"
  54. done
  55. }
  56. function _help {
  57. cat <<EOF
  58. Usage: $(basename $0) <command> <options>
  59. Commands:
  60. list - show custom records
  61. alias <domain> <target> ... - aliases a domain to another domain
  62. delegate <domain> <server> - forwards all DNS requests under domain to the target server
  63. reset - resets all configuration
  64. EOF
  65. exit 1
  66. }
  67. if [ $# -lt 1 ]; then
  68. _help
  69. fi
  70. command="$1"
  71. shift 1
  72. case "$command" in
  73. list)
  74. _list "$@"
  75. ;;
  76. alias)
  77. _alias "$@"
  78. ;;
  79. delegate)
  80. _delegate "$@"
  81. ;;
  82. reset)
  83. _reset "$@"
  84. ;;
  85. *)
  86. _help
  87. ;;
  88. esac