dt.iki.fi
11.10.2023 2022-05-01 sailfish os, systemd

AdBlocking on Sailfish OS via /etc/hosts

There are some apps in Openrepos which do not seem to work anymore for SFOS 4.x. But you don’t really need an app, all you need is a systemd timer & service and a simplistic shell script.

Gain command line access to your phone and become root.

> cd /etc/systemd/system
> nano hosts.timer hosts.service
> systemctl enable hosts.timer

hosts.timer:

[Unit]
Description=Update /etc/hosts

[Timer]
WakeSystem=false
OnCalendar=Sat *-*-* 16:00:00
RandomizedDelaySec=1h
AccuracySec=1h
Persistent=true

[Install]
WantedBy=timers.target

So once a week on Saturday at roughly 16:00. Adjust to your liking. See man systemd.timer for further options.

hosts.service:

[Unit]
Description=Update /etc/hosts

[Service]
ExecStart=/usr/local/bin/hostsupdate

The script can be found here or here.

It removes some useless fluff and then combines this data with hosts.head into the new hosts file. /etc/hosts is only overwritten after all this succeeds.

Make sure that - /usr/local/bin/hostsupdate is marked executable: chmod +x /usr/local/bin/hostsupdate - The file /etc/hosts.head exists and contains the default contents of /etc/hosts (before any manipulation). Here it is:

127.0.0.1       localhost.localdomain localhost
::1     localhost6.localdomain6 localhost6

Caveat

It seems that a full reboot is required for the new hosts file to take effect for the sailfish-browser.

Android App Support

It is possible to use the same hosts file under AAS. Create /usr/libexec/appsupport/alien-generate-extra-config.sh with the following content, and make it executable:

#!/bin/sh

echo ">>> $0" >&2
echo ">>> \$1 $1" >&2
echo ">>> \$2 $2" >&2

[ "$#" -gt 1 ] && shift

echo "lxc.mount.entry = /etc/hosts system/etc/hosts none bind,create=file 0 0" > "$1/29-hosts_config"

You should now also add the alias Android uses for ipv6 to /etc/hosts.head:

127.0.0.1       localhost.localdomain localhost
::1     localhost6.localdomain6 localhost6 ip6-localhost

Next time you start AAS you can check if the script ran with systemctl status aliendalvik-prepare. I checked some of the sites from /etc/hosts on an Android browser without adblocking, and they all return a connection refused error, as it should be. I also checked with devel-su appsupport-attach cat /system/etc/hosts. Definitely the same file.