local-dns 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. sudo nscd -i hosts
  42. }
  43. function _delegate {
  44. domain="$1"
  45. server="$2"
  46. _unbound forward_add "$domain" "$server"
  47. sudo nscd -i hosts
  48. }
  49. function _reset {
  50. _unbound reload
  51. sudo nscd -i hosts
  52. }
  53. function _list {
  54. zones=$(_helper_list_local_zones)
  55. for domain in $zones; do
  56. _unbound list_local_data | grep "$domain"
  57. done
  58. }
  59. function _help {
  60. cat <<EOF
  61. Usage: $(basename $0) <command> <options>
  62. Commands:
  63. list - show custom records
  64. alias <domain> <target> ... - aliases a domain to another domain
  65. delegate <domain> <server> - forwards all DNS requests under domain to the target server
  66. reset - resets all configuration
  67. EOF
  68. exit 1
  69. }
  70. if [ $# -lt 1 ]; then
  71. _help
  72. fi
  73. command="$1"
  74. shift 1
  75. case "$command" in
  76. list)
  77. _list "$@"
  78. ;;
  79. alias)
  80. _alias "$@"
  81. ;;
  82. delegate)
  83. _delegate "$@"
  84. ;;
  85. reset)
  86. _reset "$@"
  87. ;;
  88. *)
  89. _help
  90. ;;
  91. esac