1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package web 6 7 import ( 8 "errors" 9 "path/filepath" 10 "strings" 11 ) 12 13 func convertFileURLPath(host, path string) (string, error) { 14 if len(path) == 0 || path[0] != '/' { 15 return "", errNotAbsolute 16 } 17 18 path = filepath.FromSlash(path) 19 20 // We interpret Windows file URLs per the description in 21 // https://blogs.msdn.microsoft.com/ie/2006/12/06/file-uris-in-windows/. 22 23 // The host part of a file URL (if any) is the UNC volume name, 24 // but RFC 8089 reserves the authority "localhost" for the local machine. 25 if host != "" && host != "localhost" { 26 // A common "legacy" format omits the leading slash before a drive letter, 27 // encoding the drive letter as the host instead of part of the path. 28 // (See https://blogs.msdn.microsoft.com/freeassociations/2005/05/19/the-bizarre-and-unhappy-story-of-file-urls/.) 29 // We do not support that format, but we should at least emit a more 30 // helpful error message for it. 31 if filepath.VolumeName(host) != "" { 32 return "", errors.New("file URL encodes volume in host field: too few slashes?") 33 } 34 return `\\` + host + path, nil 35 } 36 37 // If host is empty, path must contain an initial slash followed by a 38 // drive letter and path. Remove the slash and verify that the path is valid. 39 if vol := filepath.VolumeName(path[1:]); vol == "" || strings.HasPrefix(vol, `\\`) { 40 return "", errors.New("file URL missing drive letter") 41 } 42 return path[1:], nil 43 } 44