rs232

adblock

Oct 22nd, 2021 (edited)
779
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/sh -x
  2. # Ads/Domains block FreshTomato GUI back-end
  3. ver="v2.45 - 11/21" # rs232
  4. PID=$$
  5. pidfile=/var/run/adblock.pid
  6. alias logi="logger -p INFO -t adblock[$PID]"
  7. alias logn="logger -p NOTICE -t adblock[$PID]"
  8. alias loge="logger -p ERROR -t adblock[$PID]"
  9. alias domain="grep -Eo '((([a-zA-Z]{1,2})|([0-9]{1,2})|([a-zA-Z0-9]{1,2})|([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]))\.)+[a-zA-Z]{2,6}'"
  10. alias notin="grep -Ev '^#.*|^!.*|^::|^\s*?$|^([a-f0-9:]+:+)+[a-f0-9]+'"
  11. PREFIX="/tmp/adblock"
  12. mkdir -p $PREFIX && cd $PREFIX
  13. pixelserv=$(which pixelserv-tls)
  14. ENABLE=$(nvram get adblock_enable)
  15. FINAL="/etc/dnsmasq.adblock"
  16. BLACK="/etc/dnsmasq.adblock.custom"
  17. TMP="/tmp/adblock/adblock.temp"
  18. # TMP2="/tmp/adblock/adblock.slice"
  19. CHK_FILE="/tmp/adblock.time"
  20. USERAGENT="Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/91.0"
  21. #WGET="/usr/bin/wget --no-check-certificate -T 15" # 2021.8+ only
  22. WGET="/usr/bin/wget -T 15"
  23. sizeLimit=$(( $( echo $(cat /proc/meminfo | grep MemTotal | awk '{print $2}')) * 1000 / ( 70 / 10 ) ))
  24. BLACKLIST=$(nvram get adblock_blacklist)
  25. WHITELIST=$(nvram get adblock_whitelist)
  26. CUSTOM=$(nvram get adblock_blacklist_custom)
  27.  
  28. findFreeIp() {
  29.     local e=$1
  30.     local a=1
  31.     while [ $a -ge 1 ]; do
  32.         [ $e -le "$(nvram get dhcpd_endip | cut -f4- -d. )" -a $e -ge "$(nvram get dhcpd_startip | cut -f4- -d.)" ] && continue
  33.         echo $(nvram get dhcpd_static | grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])") | grep -q "$e" && continue
  34.         HOST=$NETWORK$e
  35.         /usr/sbin/arping -q -c1 -w1 -I br0 $HOST > /dev/null 2>&1
  36.         PIXIP=$(ifconfig br0 | awk '/inet addr/{print $3}' | awk -F":" '{print $2}' | sed -e "s/255/$e/")
  37.         usleep 200
  38.         a=$(arp | grep $PIXIP | wc -l)
  39.         e=$((e-1))
  40.     done
  41.     echo $PIXIP
  42. }
  43.  
  44. checkRam() {
  45.     [ -n "$3" ] && sub="_$3"
  46.     # limit=$(cat /proc/meminfo | grep CommitLimit: | awk '{print $2}') # in KB
  47.     # used=$(cat /proc/meminfo | grep Committed_AS: | awk '{print $2}') # in KB
  48.     # freeram=$((limit-used))
  49.     # freeram=$(free | grep -E ^Mem: | awk '{print $4}')
  50.     freeram=$(( $(free | grep Mem: | awk '{print $2}' ) - $(free | grep Mem: | awk '{print $3}') ))
  51.     $WGET -U "$USERAGENT" "$2" -q -O /dev/null -S -o "$PREFIX/header_$1$sub"
  52.     listsize=$(cat "$PREFIX/header_$1$sub" | grep -Ev 'Content-Length: 0$' | grep Content-Length | awk '{print $2}') # in Bytes
  53.     [ -z "${listsize}" ] && { echo 1; } || {
  54.         [ $(($freeram - ($listsize / 512) )) -le 0 ] && echo 0 || echo 1 ;
  55.     }
  56. }
  57.  
  58. # freeRam() {
  59. # usedram=$(free | grep buffers | awk '{print $4}')
  60. # [ $(($totram - $usedram)) -lt 1500 ] && echo 0 || echo 1
  61. # }
  62.  
  63. # freeRamPer() {
  64. # [ $(awk -v u="$usedram" -v t="$totram" 'BEGIN{ print int((u/t)*100) }') -lt 5 ] && echo 0 || echo 1
  65. # }
  66.  
  67. download() {
  68.     COUNT=1
  69.     SUBLIST=1
  70.     ENTRIES=0
  71.    
  72.     logi "[0] ⚽ Kick off"
  73.  
  74.     rm -rf $PREFIX/*
  75.     rm -f /etc/dnsmasq.ad*
  76.     rm -f $CHK_FILE
  77.  
  78.     for i in $(echo $BLACKLIST | grep -Ev '^$' | tr " " "_" | tr ">" "\n"); do
  79.         ENBL=$(echo $i | cut -d "<" -f1)
  80.         URL=$(echo $i | cut -d "<" -f2)
  81.  
  82.         [ "$ENBL" -eq "1" ] && {
  83.             logi "[$COUNT][$URL] 🔻 Downloading blacklist"
  84.             [ $(checkRam $COUNT $URL) -eq 0 ] && {
  85.                 logn "[$COUNT][$URL] Not enough RAM to store this list. Skipping..."
  86.                 continue
  87.             }
  88.             $WGET -U "$USERAGENT" "$URL" -O "./_list_$COUNT" 1>/dev/null
  89.             usleep 200
  90.             [ ! -f "./_list_$COUNT" ] && {
  91.                 loge "[$COUNT][$URL] ⛔ Download error! Please check the URL"
  92.             } || {
  93.                     [ $(cat ./_list_$COUNT | grep -E '^https?://' | wc -l ) -gt 0 ] && {
  94.                         # List of lists    
  95.                         logi "[$COUNT][$URL] List-of-lists (List of URLs] format >> Parsing..."
  96.                         cat ./_list_$COUNT | grep -E '^https?://' | awk '{print $1 }'| while read u; do        
  97.                                 subfile="_list_${COUNT}"
  98.                                 subfile=$subfile"_${SUBLIST}"
  99.                                 logi "[$COUNT][$SUBLIST][$u] 🔻 Downloading black(sub)list"
  100.                                 [ $(checkRam $COUNT $u $SUBLIST) -eq 0 ] && {
  101.                                     logn "[$COUNT][$SUBLIST][$u] Not enough RAM to store this (sub)list. Skipping..."
  102.                                     continue
  103.                                 }
  104.                                 echo "$u\n" >> $PREFIX/white.url
  105.                                 $WGET -U "$USERAGENT" "$u" -O "$subfile" 1>/dev/null
  106.                                 sleep 1
  107.                                 [[ ! -f $subfile ]] && {
  108.                                 loge "[$COUNT][$SUBLIST][$u] ⛔ Sublist download error! Please verify the URL"
  109.                                     } || {
  110.                                 ENTRIES=$(cat ./$subfile | notin | wc -l)
  111.                                 logi "[$COUNT][$SUBLIST][$u] Found 🔍 $ENTRIES 🔍 entries"
  112.                                 # logi "parsefile $subfile $u $COUNT $SUBLIST"
  113.                                 # sleep 60
  114.                                 parsefile "$subfile" "$u" "$COUNT" "$SUBLIST"
  115.                                             }
  116.                                 SUBLIST=$((SUBLIST+1))        
  117.                         done
  118.                         continue
  119.                         }
  120.                 ENTRIES=$(cat ./_list_$COUNT | notin | wc -l)
  121.                 logi "[$COUNT][$URL] Found 🔍 $ENTRIES 🔍 entries"
  122.                 parsefile "_list_$COUNT" "$URL" "$COUNT"
  123.                 }
  124.             COUNT=$((COUNT+1))
  125.         } || {
  126.         logi "[$COUNT][$URL] 🚩 Disabled."
  127.         COUNT=$((COUNT+1))
  128.         }
  129.     done
  130.  
  131.     # Adding custom blacklist
  132.     [ "$(echo "$CUSTOM" | wc -w)" -ne "0" ] && {
  133.         echo $CUSTOM | tr " " "\n" | while read i; do
  134.         [ $(echo "$i" | grep -E '^/.*' | wc -l ) -gt 0 ] && {
  135.         cat "$i" | while read l; do
  136.                     echo "$l" >> $BLACK
  137.             done  
  138.         } || {
  139.         echo "$i" >> $BLACK
  140.         }
  141.         done
  142.         COUNT_CUSTOM=$(wc -l < $BLACK)
  143.         logi "[a] Added 🔍 $COUNT_CUSTOM 🔍 custom-blacklist domains"    
  144.         # Append custom blacklist to FINAL
  145.         cat $BLACK >> $FINAL && rm $BLACK
  146.         # cat $FINAL >> $BLACK && mv $BLACK $FINAL
  147.         # Merge BLACK at the beginning of FINAL
  148.         # echo -e "$BLACK\n$FINAL" > $PREFIX/list.txt
  149.         # while read line; do echo -n . ; dd if="$line" of=out status=none conv=notrunc oflag=append; done < /tmp/list.txt
  150.     }
  151.     # logi "[a] Added $COUNT_CUSTOM custom-blacklist domains"
  152.     logi "[b] Populating dnsmasq.adblock"
  153.     # Removing duplicates
  154.     cat $FINAL | awk '!_[$1]++' > $TMP && mv -f $TMP $FINAL
  155. # WHITELISTING
  156.     # Hardcoded whitelisting:
  157.         logi "[c] ⚡ Removing hardcoded whitelisted domains"
  158.         # System domains:
  159.         subsed="freshtomato.org groov.pl"
  160.         # TTB
  161.         subsed="$subsed tomatothemebase.eu"
  162.         for i in $(nvram get "ttb_url" | tr " " "\n" | domain); do subsed="$subsed ${i}"; done
  163.         # OpenVPN/PPTP/Tinc
  164.         subsed="$subsed $(nvram get vpn_client1_addr | domain)"
  165.         subsed="$subsed $(nvram get vpn_client2_addr | domain)"
  166.         subsed="$subsed $(nvram get vpn_client3_addr | domain)"
  167.         subsed="$subsed $(nvram get pptp_client_srvip | domain)"
  168.         for i in $(nvram get tinc_hosts | tr "<>" "\n" | domain); do subsed="$subsed ${i}"; done
  169.         # NTP & Stubby
  170.         for i in $(nvram get ntp_server | tr " " "\n" | domain); do subsed="$subsed ${i}"; done
  171.         for i in $(nvram get stubby_resolvers | tr ">" "\n" | domain); do subsed="$subsed ${i}"; done
  172.         # DDNS and mwan test
  173.         # sed -i -e "/$(cat /www/basic-ddns.asp | grep "\['"$(nvram get ddnsx0 | grep -Eo "^[a-zA-Z0-9]*")"'" 2>/dev/null | domain | head -1)/d" $FINAL 2>/dev/null
  174.         # sed -i -e "/$(cat /www/basic-ddns.asp | grep "\['"$(nvram get ddnsx1 | grep -Eo "^[a-zA-Z0-9]*")"'" 2>/dev/null | domain | head -1)/d" $FINAL 2>/dev/null
  175. #       sed -i -e "/$(nvram get ddnsx0 | domain | head -1) 2>/dev/null)/d" $FINAL 2>/dev/null
  176. #       sed -i -e "/nvram get ddnsx1 | domain | head -1) 2>/dev/null)/d" $FINAL 2>/dev/null
  177.         [ $(nvram get ddnsx0 | grep -Eo "^[a-zA-Z0-9]*") == "custom" ] && subsed="$subsed $(nvram get ddnsx0 | domain)" || subsed="$subsed $(cat /www/basic-ddns.asp | grep "\['"$(nvram get ddnsx0 | grep -Eo "^[a-zA-Z0-9]*")"'" 2>/dev/null | domain | head -1)"
  178.         [ $(nvram get ddnsx1 | grep -Eo "^[a-zA-Z0-9]*") == "custom" ] && subsed="$subsed $(nvram get ddnsx1 | domain)" || subsed="$subsed $(cat /www/basic-ddns.asp | grep "\['"$(nvram get ddnsx1 | grep -Eo "^[a-zA-Z0-9]*")"'" 2>/dev/null | domain | head -1)"
  179.         [ $(nvram get ddnsx_ip) == "@" ] && subsed="$subsed checkip.dyndns.org dynamic.zoneedit.com ip1.dynupdate.no-ip.com myip.dnsomatic.com myip.pairnic.com ip.changeip.com"
  180.         for i in  $(nvram get mwan_ckdst | tr "," "\n" | domain); do subsed="$subsed ${i}"; done
  181.     # User-defined whitelisting:
  182.         [ "$(echo "$WHITELIST" | wc -l)" -gt 0 ] && {
  183.             logi "[c] ⚡ Removing user-defined whitelisted domains"
  184.             echo $WHITELIST | tr " " "\n" | while read i; do
  185.                 [ $(echo "$i" | grep -E '^/.*' | wc -l ) -gt 0 ] && {
  186.             cat "$i" | while read l; do subsed="$subsed ${l}"; done
  187.             } || {
  188.             subsed="$subsed ${i}"
  189.             }
  190.             done
  191.         }
  192.         # Whitelist domains from list providers defined
  193.         logi "[c] ⚡ Removing whitelisted domains defined in Blacklist URL"
  194.         for i in $(echo $BLACKLIST | tr "<" "\n" | grep -E 'https?' | grep -Eo '((([a-zA-Z]{1,2})|([0-9]{1,2})|([a-zA-Z0-9]{1,2})|([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]))\.)+[a-zA-Z]{2,6}\s*/\s*' | tr "/" " "); do
  195.             subsed="$subsed ${i}"
  196.         done
  197.         # Whitelist domains defined in list-of-lists content
  198.         [[ -f $PREFIX/white.url ]] && {
  199.         logi "[c] ⚡ Removing whitelisted domains found in list-of-lists URLs"
  200.         for i in $(cat $PREFIX/white.url | grep -Eo '((([a-zA-Z]{1,2})|([0-9]{1,2})|([a-zA-Z0-9]{1,2})|([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]))\.)+[a-zA-Z]{2,6}\s*/\s*' | tr "/" " "); do
  201.             subsed="$subsed ${i}"
  202.         done
  203.         }
  204.         # Remove references to localhost
  205.     #   sed -i -e '/^address=\/localhost\/.*/d;}' $FINAL
  206.         subsed="$subsed ^address=\/localhost\/.*"
  207. #Debug only
  208. #echo $subsed | sed 's/ /\\|/g' > /tmp/subsed
  209.     # Removing whitelisted domains and formatting the file for dnsmasq
  210.     sed -i -e "/$(echo $subsed | sed 's/ /\\|/g')/d" -e "s/.*/address=\/&\/$PIXIP/" $FINAL 2>/dev/null
  211.     # sleep 30
  212.     # sed -i "s/.*/address=\/&\/$PIXIP/" $FINAL
  213.     # Trim down to the hard limit (trim from the top) the adblock file
  214.     # cp /mnt/sda1/DNSMASQ.2M $FINAL   
  215.     [ $(wc -c < $FINAL) -gt $sizeLimit ] && {
  216.         loge "❌ RECOVERY! $(cat $FINAL | wc -c ) bytes are too much for me -> trimming down to the hardcoded limit: $sizeLimit bytes"
  217.        loge "❌ Please consider defining fewer and/or smaller lists of domains"
  218.         # bytes=$(($(wc -c < $FINAL) - sizeLimit))
  219.         # dd if="$FINAL" bs="$bytes" count=1 skip=0 conv=notrunc of="$FINAL"
  220.         tail -c$sizeLimit $FINAL | sed '1d'  > $TMP
  221.         # dirt=$(head -1 $FINAL | wc -c)
  222.         # dd if=$FINAL bs="$dirt" count=1 skip=0 conv=notrunc of=$TMP status=none
  223.         mv $TMP $FINAL
  224.     }
  225.     # Adding pixelserv name resolution if relevant
  226.     [[ -f "$pixelserv" ]] && {
  227.         d="pixelserv.$(nvram get wan_domain),"
  228.         echo "host-record=pixelserv,$d$PIXIP" >> $FINAL
  229. #       sed -i "1s/^/host-record=pixelserv,$d$PIXIP\n/" $FINAL
  230.     }
  231.     # cleaning after myself
  232.    rm -rf $PREFIX/*
  233.    # Final verification
  234.    [ -f "$FINAL" -a "$ENTRIES" -gt 0 ] || [ "$COUNT_CUSTOM" -ne 0 ] && {
  235.        # count entries
  236.        COUNT=$(($(wc -l < $FINAL)))
  237.        logi "[d] Protecting against a total of 💣 $COUNT 💣 domains"
  238.        touch "$CHK_FILE"
  239.        cru d adblockDL
  240.    } || {
  241.        # for some reason we cannot download at least 1 blacklist
  242.        # so we will try in 5 mins once again
  243.        cru a adblockDL "*/5 * * * * /usr/sbin/adblock"
  244.        loge "No internet, will try again in 5 minutes"
  245.    }    
  246. }
  247.  
  248. parsefile(){
  249.    [ -n "$4" ] && S="[$4]"
  250. #    logi "[$3]$S[$2] Parsing... "
  251.    if [ $(head -200 "$1" | notin | grep -iE '<html>|<head>|<body' | wc -l ) -gt 0 ]; then
  252.        # Skip loop if CheckHTML is matched
  253.        loge "[$3]$S[$2] ⛔ Content not understood (HTML?). Skipping..."
  254.        continue
  255.    elif [ $(head -200 $1 | notin | grep -E '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$' | wc -l ) -gt 0 ]; then
  256.        # Skip loop if IP-only is matched
  257.        loge "[$3]$S[$2] ⛔ Content not understood (IP-only?). Skipping..."
  258.         continue
  259.     elif [ $(head -200 $1 | notin | domain | wc -l ) -gt 0 ]; then
  260.        # Extract domain only
  261.        logi "[$3]$S[$2] Extracting domains from list >> Parsing..."
  262.        cat $1 | notin | domain >> $FINAL
  263.     else
  264.         logi "[$3]$S[$2] ⛔ I don't understand the content of this list. Skipping..."
  265.     fi
  266.     rm "$1"
  267. }
  268.  
  269. cronAdd() {
  270.    [ "$(cru l | grep adblockJob | wc -l)" -eq "0" ] && {
  271.        MINS=$(($RANDOM % 59))
  272.         HOUR=$((4 + $RANDOM % 2)) # Between 4:00 and 5:59
  273.        cru a adblockJob "$MINS $HOUR * * * /usr/sbin/adblock"
  274.         logn "[y] ⌛ Added cron job"  
  275.    }
  276. }
  277.  
  278. cronDel() {
  279.    [ "$(cru l | grep adblockJob | wc -l)" -eq "1" ] && {
  280.        cru d adblockJob
  281.        logn "[x] ⌛ Removed cron job"
  282.    }
  283. }
  284.  
  285. pxStart() {
  286.    if ps | grep "[p]ixelserv-tls $PIXIP"; then
  287.        logn "[p] 🔥 pixelserv-tls already running, skipping"
  288.        else
  289.        logn "[p] 🔥 Setting up pixelserv-tls on br0.adblk $PIXIP"
  290.        iptables -nvL INPUT | grep -Eq 'br0.*multiport dports 80,443' || {
  291.            iptables -I INPUT -i br0 -p all -d $PIXIP -j DROP
  292.            iptables -I INPUT -i br0 -p tcp -d $PIXIP --match multiport --dports 80,443 -j ACCEPT
  293.             iptables -I INPUT -d $PIXIP -i br0 -p icmp --icmp-type echo-request -j ACCEPT
  294.             iptables
  295.        }
  296.        iptables -nvL FORWARD | grep -Eq 'br0.*multiport dports 80,443' || {
  297.        iptables -I FORWARD -i br+ -o br0 -d $PIXIP -p tcp --match multiport --dports 80,443 -j ACCEPT
  298.         iptables -I FORWARD -i br+ -o br0 -d $PIXIP -p icmp --icmp-type echo-request -j ACCEPT
  299.        }
  300.        ifconfig br0:adblk $PIXIP netmask $(nvram get lan_netmask) up
  301.        $pixelserv $PIXIP -p 80 -k 443 #-l 5
  302.    fi
  303. }
  304.  
  305. pxStop() {
  306.    PIXIPS=$(iptables -nvL INPUT | grep -E 'br0.*multiport dports 80,443' | awk '{print $9}')
  307.    ( iptables -D FORWARD -i br+ -o br0 -d $PIXIPS -p tcp --match multiport --dports 80,443 -j ACCEPT
  308.     iptables -D FORWARD -i br+ -o br0 -d $PIXIPS -p icmp --icmp-type echo-request -j ACCEPT
  309.    iptables -D INPUT -i br0 -p tcp -d $PIXIPS --match multiport --dports 80,443 -j ACCEPT
  310.     iptables -D INPUT -d $PIXIPS -i br0 -p icmp --icmp-type echo-request -j ACCEPT
  311.    killall pixelserv-tls
  312.    ifconfig br0:adblk down
  313.    iptables -D INPUT -i br0 -p all -d $PIXIPS -j DROP ) >/dev/null 2>&1
  314.    logn "[p] Disabled pixelserv-tls on br0.adblk $PIXIP"
  315. }
  316.  
  317. safeDnsmasqRestart() {
  318.    TRIM=$(echo $(( ( $(cat $FINAL | wc -l ) / 100 ) * 10  )))
  319.    [ ! -z "$(pidof dnsmasq)" ] && service dnsmasq stop || loge "Dnsmasq was not running...?"
  320.     # cp /mnt/sda1/DNSMASQ.2M /etc/dnsmasq.adblock
  321.    service dnsmasq start
  322.    sleep 10
  323.    # If owner is still at root after 10 seconds enter the loop
  324.    while [ -z "$(ps | grep '[d]nsmasq' | awk '{print $2}')" -o "$(ps | grep '[d]nsmasq' | awk '{print $2}')" != "nobody" ]; do
  325.        loge "❌ RECOVERY! $(cat $FINAL | wc -l ) domains are too much for me -> trimming down to $(($(cat $FINAL | wc -l) - $TRIM ))"
  326.        loge "❌ Please consider defining fewer and/or smaller lists of domains"
  327.        service dnsmasq stop
  328.        sleep 1
  329.        # SIZE=$(($(wc -l < $FINAL)-$TRIM))
  330.        # bytes=$(head -$SIZE "$FINAL" | wc -c)
  331.        # dd if="$FINAL" bs="$bytes" count=1 skip=0 conv=notrunc of="$TMP" status=none
  332.         tail +$TRIM $FINAL > $TMP
  333.         mv $TMP $FINAL
  334.         # #remove "dirty first line"
  335.         # dirt=$(head -1 $FINAL | wc -c)
  336.         # dd if=$FINAL bs="$dirt" skip=1 of=$FINAL status=none
  337.        sleep 1
  338.        service dnsmasq start
  339.        sleep 10
  340.    done
  341. }
  342.  
  343. adExit() {
  344.    logn "[z] 💢 Exiting $@"
  345.     # echo 75 > /proc/sys/vm/overcommit_ratio
  346.     rm -rf $PREFIX/* >/dev/null 2>&1
  347.    rm $pidfile >/dev/null 2>&1
  348.     [ $1 -eq 0 ] && safeDnsmasqRestart
  349.     [ $1 -eq 1 ] && {
  350.             rm -f $FINAL
  351.             service dnsmasq restart
  352.         }
  353.    exit $@
  354. }
  355.  
  356. # STARTS HERE --------------------------------------------------------------------------------
  357.  
  358. # Skip execution (and stop adblock if running) if internal DNS is disabled
  359. [ $(nvram get dhcpd_dmdns) -eq 0 -a $ENABLE -eq 1 ] && {
  360.     loge "[x] 🛑 Internal dns is disabled! Adblock is enabled but can't run. Exiting..."
  361.     [[ -f "$pixelserv" ]] && pxStop
  362.     cronDel
  363.     adExit 2
  364. }
  365.  
  366. if [ "$1" == "status" ]; then
  367.     echo $(($(date +%s)-$(date -r "$FINAL" +%s)))
  368. echo -e "###########################################
  369. Domain blocking $ver - FreshTomato
  370.  
  371. DnsMasq ===================================
  372. Running = $(echo $([ -f /var/run/dnsmasq.pid ] && echo "Yes" || echo "No"))
  373.   Owner = $(ps | grep '[d]nsmasq' | awk '{print $2}')
  374. Adblock = $(echo $(cat /etc/dnsmasq.conf | grep conf-file=/etc/dnsmasq.adblock >/dev/null 2>&1 && echo "Present" || echo "Missing"))
  375.  
  376. Blockfile =================================
  377.    Refs = $(echo $(cat $FINAL | wc -l) lines)
  378.    Size = $(echo $(ls -lah /etc/dnsmasq.adblock | awk '{print $5}'))
  379.    Date = $(echo $(ls -lah /etc/dnsmasq.adblock | awk '{print $8" "$6" "$7}')) ~ $((($(date +%s)-$(date -r "$FINAL" +%s))/60)) mins ago
  380.  
  381. ###########################################"
  382. exit
  383. elif [ "$1" == "stop" ]; then
  384.    [[ -f "$pixelserv" ]] && pxStop
  385.    cronDel
  386.     logi "[x] 🛑 AdBlock stopped"
  387.    adExit 1
  388. elif [ "$1" == "start" ] || [ -z $1 ]; then
  389.    [ "$ENABLE" -eq "1" ] && {
  390.     [ -s $pidfile ] && { loge "[x] ⛔ AdBlock already running. Skipping execution..." && exit ; } || { echo $PID > $pidfile ; }
  391.         #Skip execution if dnsmasq.adblock was updated less than 10 min ago
  392.         [ -f "$FINAL" ] && {
  393.             TIME_FILE=$(date -r "$FINAL" +%s)
  394.             TIME_DIFF=$(($(date +%s)-(10*60))) # 10 minutes - change 10 to modify the number of minutes
  395.                 [ "$TIME_FILE" -gt "$TIME_DIFF" ] && {
  396.                 logn "[t] ⛔ blacklist file updated less than 10min ago. Probably a false positive call. Skipping execution this time..."
  397.                 exit
  398.                 }
  399.         }
  400.         # Tweak kernel parameter for memory allocation
  401.         [ $(cat /proc/sys/vm/overcommit_ratio) -le 90 ] && echo 90 > /proc/sys/vm/overcommit_ratio
  402.         # pixelserve-tls is found let's use it
  403.         [ -f "$pixelserv" ] && {
  404.             logi "[0] 🔥 pixelserv-tls found"
  405.             PIXIP=$(nvram get pixel_ip)
  406.             [ -z "${PIXIP}" ] && {
  407.                 NETWORK=$(ifconfig br0 | grep inet | awk '{print $2}' | grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3})*")
  408.                 ip=$(nvram get lan_ipaddr)
  409.                 mask=$(nvram get lan_netmask)
  410.                 i4=$(echo $ip | awk -F"." '{print $4}')
  411.                 m4=$(echo $mask | awk -F"." '{print $4}')
  412.                 NETEND=$(((i4 & m4 | 255-m4)-1))
  413.                 findFreeIp $NETEND $NETWORK
  414.             }
  415.            
  416.             # Do we need the certificates to be installed?
  417.             [ ! -s /opt/var/cache/pixelserv/ca.crt ] && {
  418.                 alias openssl='/usr/sbin/openssl'
  419.                 logn "[p] 🔥 Setting-up pixelserv-tls and certificates"  
  420.                 mkdir /root/tmp/
  421.                 mkdir /opt/var/cache/pixelserv/prefetch
  422.                 chown -R nobody /opt/var/cache/pixelserv   
  423.                 chmod -R 666 /opt/var/cache/pixelserv
  424.                 cd /opt/var/cache/pixelserv
  425.                 umask 0002
  426.                 openssl genrsa -out ./ca.key 2048
  427.                 openssl req -key ./ca.key -new -x509 -days 365 -sha256 -extensions v3_ca -out ./ca.crt -subj "/CN=Pixelserv CA"
  428.             }
  429.            
  430.             # Workaround if pixelserv is on the same port as wan remote
  431.             [[ $(nvram get http_wanport) == "80" || $(nvram get http_wanport) == "443" ]] && {
  432.             iptables -C INPUT -p tcp -m tcp --dport $(nvram get http_wanport) -m state --state NEW -j wwwlimit && {
  433.                     line=$(iptables -L INPUT --line-number | grep -E '.*wwwlimit.*NEW$' | awk '{print $1}')
  434.                     add=$(iptables --list-rules INPUT | grep -E '^-A.*wwwlimit' | sed "s/-A INPUT -p/! -d $PIXIP -p/g")
  435.                     iptables -R INPUT $line $add
  436.                 }
  437.             }
  438.         } || {
  439.             PIXIP="#"
  440.             logi "[0] 🔥 pixelserv-tls not found. We'll use an alternative method"
  441.         }  
  442.    
  443.         [ "$1" == "update" ] && {
  444.             logn "[0] 💢 Updating lists only"
  445.             download
  446.         } || {
  447.             # do not download blacklists, if they're already successfully downloaded in less than 2 hours
  448.             [ -f "$CHK_FILE" -a -s "$FINAL" ] && {
  449.                 TIME_FILE=$(date -r "$CHK_FILE" +%s)
  450.                 TIME_2HRS=$(($(date +%s)-(120/60))) # 120 minutes
  451.                 [ "$TIME_FILE" -lt "$TIME_2HRS" ] && {
  452.                     download
  453.                 } || {
  454.                     COUNT=$(wc -l < $FINAL)
  455.                     logn "[t] ⌛ blacklists already downloaded (less than 2 hours ago) and activated 💣 $COUNT 💣 entries"
  456.                     cru d adblockDL
  457.                 }
  458.             } || {
  459.                 download
  460.             }
  461.         }
  462.     [[ -f "$pixelserv" ]] && pxStart
  463.         cronAdd
  464.     }
  465. fi
  466. adExit 0
RAW Paste Data