anasfanani / Magisk-Tailscaled

Magisk/KernelSU module for running Tailscale on rooted Android devices. The easiest, most secure way to use WireGuard and 2FA.
https://t.me/systembinsh/158
Other
220 stars 25 forks source link

Host file generation #29

Open binyaminyblatt opened 2 months ago

binyaminyblatt commented 2 months ago

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