acme/autocert: use standard functions to pick the cache directory

acme/autocert currently has ad-hoc logic to find a reasonable default
for a cache directory.

Since that logic was written (in 2017), new functions were added to the
os package to provide that functionality (in Go 1.13, 2019-09):
`os.UserCacheDir` and `os.UserHomeDir`.

This patch replaces the ad-hoc logic with a call to `os.UserCacheDir`.

The fallback to `/` is kept, since it may be relied upon in some
environments.

Change-Id: I3bf692ca670b87bf3d329e5d3684eee15ed374aa
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/440195
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sean Liao <sean@liao.dev>
diff --git a/acme/autocert/listener.go b/acme/autocert/listener.go
index 9d62f8c..460133e 100644
--- a/acme/autocert/listener.go
+++ b/acme/autocert/listener.go
@@ -10,7 +10,6 @@
 	"net"
 	"os"
 	"path/filepath"
-	"runtime"
 	"time"
 )
 
@@ -124,32 +123,13 @@
 	return ln.tcpListener.Close()
 }
 
-func homeDir() string {
-	if runtime.GOOS == "windows" {
-		return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
-	}
-	if h := os.Getenv("HOME"); h != "" {
-		return h
-	}
-	return "/"
-}
-
 func cacheDir() string {
 	const base = "golang-autocert"
-	switch runtime.GOOS {
-	case "darwin":
-		return filepath.Join(homeDir(), "Library", "Caches", base)
-	case "windows":
-		for _, ev := range []string{"APPDATA", "CSIDL_APPDATA", "TEMP", "TMP"} {
-			if v := os.Getenv(ev); v != "" {
-				return filepath.Join(v, base)
-			}
-		}
-		// Worst case:
-		return filepath.Join(homeDir(), base)
+	cache, err := os.UserCacheDir()
+	if err != nil {
+		// Fall back to the root directory.
+		cache = "/.cache"
 	}
-	if xdg := os.Getenv("XDG_CACHE_HOME"); xdg != "" {
-		return filepath.Join(xdg, base)
-	}
-	return filepath.Join(homeDir(), ".cache", base)
+
+	return filepath.Join(cache, base)
 }