package main import ( "fmt" "io" "net" "net/http" "os" "strings" ) // UnauthorizedIfNotLocal is a middleware that returns unauthorized if not // being accessed from loopback, as a basic form of host authentication. func UnauthorizedIfNotLocal(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !isLocal(r.RemoteAddr) { http.Error(w, "Unauthorized", http.StatusUnauthorized) Logger.Printf("Unauthorized request from: %s for %s", r.RemoteAddr, r.RequestURI) return } h.ServeHTTP(w, r) }) } var isLocalCIDR = "127.0.0.1/8" func isLocal(addr string) bool { if strings.Contains(isLocalCIDR, ",") { for _, cidr := range strings.Split(isLocalCIDR, ",") { _, localNet, err := net.ParseCIDR(cidr) if err != nil { panic(err) } if localNet.Contains(net.ParseIP(strings.Split(addr, ":")[0])) { return true } } return false } else { _, localNet, err := net.ParseCIDR(isLocalCIDR) if err != nil { panic(err) } return localNet.Contains(net.ParseIP(strings.Split(addr, ":")[0])) } } var shareLink = "" func getShareLink() string { if shareLink != "" { return shareLink } return fmt.Sprintf("http://%s:%s/", GetHostIP(), getPort()) } func getPort() string { s := strings.Split(Listen, ":") if len(s) != 2 { return Listen } return s[1] } // ServeSelf tries to locate the currently running executable and serve // it down to the client. func ServeSelf(w http.ResponseWriter, r *http.Request) { s, err := os.Executable() if err != nil { Logger.Println("While trying to get my executable path: ", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } fh, err := os.Open(s) if err != nil { Logger.Println("While opening my own executable for reading: ", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } _, err = io.Copy(w, fh) fh.Close() return }