Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Host file generation #29

Open
binyaminyblatt opened this issue Aug 21, 2024 · 0 comments
Open

Host file generation #29

binyaminyblatt opened this issue Aug 21, 2024 · 0 comments

Comments

@binyaminyblatt
Copy link

binyaminyblatt commented Aug 21, 2024

I wrote this script based on tailscale-hosts generate a file that I can import to AdAway in place of magicdns
It requires jq
It also requires that when you import it to adaway you enable redirections

#!/usr/bin/env bash

usage() {
  echo "Usage: $(basename "$0") [--cron] [-o FILE] [-6]"
}

echo_info() {
  [[ -n "$CRON" ]] || echo "🔵 $*" >&2
}

echo_success() {
  [[ -n "$CRON" ]] || echo "🟢 $*" >&2
}

echo_error() {
  echo "🔴 $*" >&2
}

get_ts_hosts() {
  local ip_index="$1"
  local tailscale_cmd="tailscale status --json"

  # Use sudo if running on Termux
  if command -v termux-setup-storage; then
    tailscale_cmd="sudo $tailscale_cmd"
  fi

  $tailscale_cmd | jq -r "[.Self, .Peer[]] | sort_by(.DNSName)[] | select(.DNSName != \"\") | select(.OS != \"js\") | 
  (.TailscaleIPs[$ip_index] + \" \" + ((.DNSName | split(\".\")[0]))), 
  (.TailscaleIPs[$ip_index] + \" \" + (.DNSName | .[:-1]))"
}

generate_hosts_file() {
  local ip_version="$1"
  local ip_index

  case "$ip_version" in
    4) ip_index=0 ;;
    6) ip_index=1 ;;
    *) echo_error "Invalid IP version: $ip_version"; return 1 ;;
  esac

  local hosts
  hosts="$(get_ts_hosts "$ip_index")"

  if [[ -z "$hosts" ]]; then
    echo_error "Failed to generate tailscale hosts file"
    return 1
  fi

  echo "$hosts"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  set -eu -o pipefail

  DEFAULT_OUTPUT="/proc/self/fd/1"
  IP_VERSION=4
  OUTPUT="${OUTPUT:-$DEFAULT_OUTPUT}"
  CRON="${CRON:-}"

  while [[ $# -gt 0 ]]; do
    case "$1" in
      help|h|-h|--help)
        usage
        exit 0
        ;;
      -c|--cron)
        CRON=1
        shift
        ;;
      -o|--output)
        OUTPUT="$2"
        shift 2
        ;;
      -6|--ipv6)
        IP_VERSION=6
        shift
        ;;
      *)
        usage >&2
        exit 2
        ;;
    esac
  done

  NEW_HOSTS=$(generate_hosts_file "$IP_VERSION")

  if [[ "$OUTPUT" == "$DEFAULT_OUTPUT" ]]; then
    echo "$NEW_HOSTS"
    exit 0
  fi

  if diff "$OUTPUT" - <<< "$NEW_HOSTS"; then
    echo_success "Hosts file did not change"
    exit 0
  fi

  echo "$NEW_HOSTS" > "$OUTPUT"
  echo_info "✏️ Wrote tailscale hosts file to $OUTPUT"
  exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant