1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// homescreen-install signs the launcher APK and installs it on a device.
//
// The work that cannot live in the Nix derivation is here: the signing key
// belongs outside the store (the repository is published, and this key signs an
// application allowed to enumerate every installed app), and finding the device
// is a question about the world rather than about the build.
//
// The tool paths come from the environment, set by the wrapper in default.nix,
// so that the Nix store paths of apksigner, keytool, adb and avahi-browse are
// fixed at build time rather than looked up in $PATH at run time.
package main

import (
	"errors"
	"flag"
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// A local sideloading key protects nothing that the file permissions do not
// already protect: a passphrase would have to be stored next to the key for
// installation to stay non-interactive. It is spelled out here rather than
// prompted for, so that the threat model is visible instead of implied.
const storePass = "homescreen"

const keyAlias = "homescreen"

// Paths to the tools, injected by the Nix wrapper.
type tools struct {
	apksigner   string
	keytool     string
	adb         string
	avahiBrowse string
	apk         string
	appID       string
}

func toolsFromEnv() (tools, error) {
	t := tools{
		apksigner:   os.Getenv("HOMESCREEN_APKSIGNER"),
		keytool:     os.Getenv("HOMESCREEN_KEYTOOL"),
		adb:         os.Getenv("HOMESCREEN_ADB"),
		avahiBrowse: os.Getenv("HOMESCREEN_AVAHI_BROWSE"),
		apk:         os.Getenv("HOMESCREEN_APK"),
		appID:       os.Getenv("HOMESCREEN_APPLICATION_ID"),
	}
	var missing []string
	for name, v := range map[string]string{
		"HOMESCREEN_APKSIGNER":      t.apksigner,
		"HOMESCREEN_KEYTOOL":        t.keytool,
		"HOMESCREEN_ADB":            t.adb,
		"HOMESCREEN_AVAHI_BROWSE":   t.avahiBrowse,
		"HOMESCREEN_APK":            t.apk,
		"HOMESCREEN_APPLICATION_ID": t.appID,
	} {
		if v == "" {
			missing = append(missing, name)
		}
	}
	if len(missing) > 0 {
		return t, fmt.Errorf("unset: %s\n(this program is meant to be run through its Nix wrapper)",
			strings.Join(missing, ", "))
	}
	return t, nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintf(os.Stderr, "homescreen-install: %v\n", err)
		os.Exit(1)
	}
}

func run() error {
	var (
		wireless     = flag.Bool("wireless", false, "skip USB and find the device over mDNS")
		setDefault   = flag.Bool("set-default", false, "also make homescreen the default home screen")
		unsetDefault = flag.String("unset-default", "", "hand the home screen back to this package and exit")
		printAPK     = flag.String("print-apk", "", "sign the APK to this path and exit without installing")
		serial       = flag.String("serial", "", "install to this adb device")
	)
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, `Usage: homescreen-install [flags]

Signs the launcher APK and installs it.

Without -serial, a device attached over USB is preferred and mDNS discovery is
used only if there is none: USB requires physical access, wireless debugging
does not. See homescreen(1), CAVEATS.

Installing does not change the home screen. The launcher also appears in the
app drawer, which is the way to try it without giving up the one you have.

Flags:
`)
		flag.PrintDefaults()
		fmt.Fprintf(os.Stderr, `
To hand the home screen back:
  homescreen-install -unset-default com.google.android.apps.nexuslauncher

The signing key is created on first run at
  %s
Keep it: Android refuses to update an application whose signature changed, so
losing it means uninstalling and losing whatever the app stores.
`, defaultKeystorePath())
	}
	flag.Parse()

	t, err := toolsFromEnv()
	if err != nil {
		return err
	}

	// Handing the home screen back is a recovery path: it must work when the
	// launcher is too broken to build, so it happens before signing anything.
	if *unsetDefault != "" {
		device := *serial
		if device == "" {
			device, err = findDevice(t, *wireless)
			if err != nil {
				return err
			}
		}
		fmt.Fprintf(os.Stderr, "handing the home screen to %s\n", *unsetDefault)
		if err := runTool(t.adb, "-s", device,
			"shell", "cmd", "role", "add-role-holder",
			"android.app.role.HOME", *unsetDefault); err != nil {
			return fmt.Errorf("could not set the home role: %w", err)
		}
		fmt.Fprintln(os.Stderr, "done. Press Home.")
		return nil
	}

	keystore := defaultKeystorePath()
	if err := ensureKeystore(t, keystore); err != nil {
		return err
	}

	signed, cleanup, err := signAPK(t, keystore, *printAPK)
	if err != nil {
		return err
	}
	defer cleanup()

	if *printAPK != "" {
		fmt.Println(signed)
		return nil
	}

	device := *serial
	if device == "" {
		device, err = findDevice(t, *wireless)
		if err != nil {
			return err
		}
	}

	fmt.Fprintf(os.Stderr, "installing to %s\n", device)
	// -r replaces the existing installation, keeping app data. It fails if the
	// signature changed, which is the keystore warning made concrete.
	if err := runTool(t.adb, "-s", device, "install", "-r", signed); err != nil {
		return fmt.Errorf("install failed: %w", err)
	}

	grantUsageStats(t, device)

	if *setDefault {
		fmt.Fprintf(os.Stderr, "setting %s as the default home screen\n", t.appID)
		if err := runTool(t.adb, "-s", device,
			"shell", "cmd", "role", "add-role-holder",
			"android.app.role.HOME", t.appID); err != nil {
			return fmt.Errorf("could not set the home role: %w", err)
		}
		fmt.Fprintf(os.Stderr, `done. Press Home.

To hand it back:
  homescreen-install -unset-default com.google.android.apps.nexuslauncher
`)
		return nil
	}

	fmt.Fprintf(os.Stderr, `installed.

It is not the default home screen, and it does not need to be: it is in the app
drawer as "homescreen", which is the way to look at it without losing the
launcher you have.

To make it the home screen anyway:
  homescreen-install -set-default
`)
	return nil
}

// grantUsageStats switches on the app op behind PACKAGE_USAGE_STATS, which is
// what lets the launcher order the grid by what has actually been used.
//
// The permission is declared in the manifest but is not granted by installing:
// it is an app op, normally switched on by hand in Settings > Apps > Special
// app access > Usage access. `appops set` does the same thing without leaving
// the terminal, but only once the permission is declared -- before that it
// reports success and silently leaves the op at "default", so the result is
// read back rather than trusted.
//
// A failure here is not fatal: the launcher falls back to sorting
// alphabetically, which is worse but not broken.
func grantUsageStats(t tools, device string) {
	if err := exec.Command(t.adb, "-s", device,
		"shell", "appops", "set", t.appID, "GET_USAGE_STATS", "allow").Run(); err != nil {
		fmt.Fprintf(os.Stderr, "could not grant usage access: %v\n", err)
		return
	}
	out, err := exec.Command(t.adb, "-s", device,
		"shell", "appops", "get", t.appID, "GET_USAGE_STATS").Output()
	if err != nil || !strings.Contains(string(out), "allow") {
		fmt.Fprintf(os.Stderr, `could not grant usage access; the grid will be
sorted alphabetically instead of by use. Grant it by hand under
  Settings > Apps > Special app access > Usage access
`)
	}
}

func defaultKeystorePath() string {
	if p := os.Getenv("HOMESCREEN_KEYSTORE"); p != "" {
		return p
	}
	dir := os.Getenv("XDG_CONFIG_HOME")
	if dir == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			// Falling back to the working directory would scatter key material
			// wherever the tool happened to be run; refusing is safer, and the
			// caller can always pass HOMESCREEN_KEYSTORE.
			return ""
		}
		dir = filepath.Join(home, ".config")
	}
	return filepath.Join(dir, "homescreen", "keystore.jks")
}

// ensureKeystore creates the signing key if it does not exist yet.
func ensureKeystore(t tools, keystore string) error {
	if keystore == "" {
		return errors.New("cannot determine the keystore path; set HOMESCREEN_KEYSTORE")
	}
	if _, err := os.Stat(keystore); err == nil {
		return nil
	} else if !errors.Is(err, os.ErrNotExist) {
		return fmt.Errorf("checking %s: %w", keystore, err)
	}

	fmt.Fprintf(os.Stderr, "creating signing key at %s\n", keystore)
	if err := os.MkdirAll(filepath.Dir(keystore), 0o700); err != nil {
		return err
	}
	// 10000 days: an expired key cannot sign an update, and this key exists
	// only to keep the signature stable across updates.
	if err := runTool(t.keytool,
		"-genkeypair",
		"-keystore", keystore,
		"-alias", keyAlias,
		"-keyalg", "RSA", "-keysize", "4096",
		"-validity", "10000",
		"-storepass", storePass,
		"-keypass", storePass,
		"-dname", "CN=homescreen, O=Profpatsch, C=DE",
	); err != nil {
		return fmt.Errorf("could not create the signing key: %w", err)
	}
	return os.Chmod(keystore, 0o600)
}

// signAPK copies the APK out of the read-only store and signs it in place.
// When dest is empty the signed APK goes to a temporary directory, and the
// returned cleanup removes it.
func signAPK(t tools, keystore, dest string) (path string, cleanup func(), err error) {
	cleanup = func() {}
	if dest == "" {
		dir, err := os.MkdirTemp("", "homescreen-")
		if err != nil {
			return "", cleanup, err
		}
		cleanup = func() { os.RemoveAll(dir) }
		dest = filepath.Join(dir, "homescreen.apk")
	}

	if err := copyFile(t.apk, dest); err != nil {
		cleanup()
		return "", func() {}, err
	}

	if err := runTool(t.apksigner, "sign",
		"--ks", keystore,
		"--ks-key-alias", keyAlias,
		"--ks-pass", "pass:"+storePass,
		"--key-pass", "pass:"+storePass,
		dest,
	); err != nil {
		cleanup()
		return "", func() {}, fmt.Errorf("signing failed: %w", err)
	}
	return dest, cleanup, nil
}

func copyFile(src, dst string) error {
	b, err := os.ReadFile(src)
	if err != nil {
		return err
	}
	// The source lives in the store and is read-only; apksigner needs to write.
	return os.WriteFile(dst, b, 0o600)
}

// findDevice returns an adb device specifier, preferring USB.
func findDevice(t tools, wirelessOnly bool) (string, error) {
	if !wirelessOnly {
		devices, err := usbDevices(t)
		if err != nil {
			return "", err
		}
		if len(devices) > 1 {
			return "", fmt.Errorf("several USB devices attached (%s); pick one with -serial",
				strings.Join(devices, ", "))
		}
		if len(devices) == 1 {
			return devices[0], nil
		}
		fmt.Fprintln(os.Stderr, "no device on USB, looking for one over mDNS")
	}

	addr, err := discoverWireless(t)
	if err != nil {
		return "", err
	}
	fmt.Fprintf(os.Stderr, "found %s\n", addr)
	if err := runTool(t.adb, "connect", addr); err != nil {
		return "", fmt.Errorf("could not connect to %s: %w", addr, err)
	}
	return addr, nil
}

// usbDevices lists ready devices attached over USB. Network transports are
// named host:port, so a specifier without a colon came in over USB.
func usbDevices(t tools) ([]string, error) {
	out, err := exec.Command(t.adb, "devices").Output()
	if err != nil {
		return nil, fmt.Errorf("adb devices: %w", err)
	}
	var devices []string
	for _, line := range strings.Split(string(out), "\n") {
		fields := strings.Fields(line)
		if len(fields) != 2 || fields[1] != "device" {
			continue
		}
		if strings.Contains(fields[0], ":") {
			continue
		}
		devices = append(devices, fields[0])
	}
	return devices, nil
}

// discoverWireless finds a device advertising adb over mDNS.
//
// `adb mdns services` would be the obvious way, but the adb in nixpkgs is built
// without mDNS support and answers "unknown host service 'mdns:services'", so
// discovery goes through avahi instead. The port is randomised every time
// wireless debugging is toggled and must never be remembered.
func discoverWireless(t tools) (string, error) {
	// -r resolve, -p parseable, -t terminate once the cache is exhausted.
	out, err := exec.Command(t.avahiBrowse, "-rpt", "_adb-tls-connect._tcp").Output()
	if err != nil {
		return "", fmt.Errorf("avahi-browse: %w", err)
	}
	for _, line := range strings.Split(string(out), "\n") {
		// Resolved records start with '=' and are semicolon-separated:
		// =;wlp3s0;IPv4;adb-SERIAL-xxx;_adb-tls-connect._tcp;local;host;ADDR;PORT;"txt"
		if !strings.HasPrefix(line, "=;") {
			continue
		}
		f := strings.Split(line, ";")
		if len(f) < 9 || f[2] != "IPv4" {
			continue
		}
		return net.JoinHostPort(f[7], f[8]), nil
	}
	return "", errors.New("no device found.\n" +
		"Connect one over USB, or enable Wireless debugging on the phone")
}

// runTool runs a command, passing its output through to the terminal.
func runTool(name string, args ...string) error {
	cmd := exec.Command(name, args...)
	cmd.Stdout = os.Stderr
	cmd.Stderr = os.Stderr
	return cmd.Run()
}