all: encode hrefs, replace hrefs with path in public API

Closes: https://github.com/emersion/go-webdav/issues/14
Closes: https://github.com/emersion/go-webdav/issues/16
This commit is contained in:
Simon Ser 2020-01-22 11:07:30 +01:00
parent 72c96af206
commit 6eeeccb96e
No known key found for this signature in database
GPG Key ID: 0FDE7BE0E88F5E48
11 changed files with 96 additions and 92 deletions

View File

@ -8,7 +8,7 @@ import (
) )
type AddressBook struct { type AddressBook struct {
Href string Path string
Name string Name string
Description string Description string
MaxResourceSize int64 MaxResourceSize int64
@ -19,11 +19,11 @@ type AddressBookQuery struct {
} }
type AddressBookMultiGet struct { type AddressBookMultiGet struct {
Hrefs []string Paths []string
Props []string Props []string
} }
type AddressObject struct { type AddressObject struct {
Href string Path string
Card vcard.Card Card vcard.Card
} }

View File

@ -81,7 +81,7 @@ func (c *Client) FindAddressBookHomeSet(principal string) (string, error) {
return "", err return "", err
} }
return prop.Href, nil return prop.Href.Path, nil
} }
func (c *Client) FindAddressBooks(addressBookHomeSet string) ([]AddressBook, error) { func (c *Client) FindAddressBooks(addressBookHomeSet string) ([]AddressBook, error) {
@ -98,7 +98,7 @@ func (c *Client) FindAddressBooks(addressBookHomeSet string) ([]AddressBook, err
l := make([]AddressBook, 0, len(ms.Responses)) l := make([]AddressBook, 0, len(ms.Responses))
for _, resp := range ms.Responses { for _, resp := range ms.Responses {
href, err := resp.Href() path, err := resp.Path()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -130,7 +130,7 @@ func (c *Client) FindAddressBooks(addressBookHomeSet string) ([]AddressBook, err
} }
l = append(l, AddressBook{ l = append(l, AddressBook{
Href: href, Path: path,
Name: dispName.Name, Name: dispName.Name,
Description: desc.Description, Description: desc.Description,
MaxResourceSize: maxResSize.Size, MaxResourceSize: maxResSize.Size,
@ -143,7 +143,7 @@ func (c *Client) FindAddressBooks(addressBookHomeSet string) ([]AddressBook, err
func decodeAddressList(ms *internal.Multistatus) ([]AddressObject, error) { func decodeAddressList(ms *internal.Multistatus) ([]AddressObject, error) {
addrs := make([]AddressObject, 0, len(ms.Responses)) addrs := make([]AddressObject, 0, len(ms.Responses))
for _, resp := range ms.Responses { for _, resp := range ms.Responses {
href, err := resp.Href() path, err := resp.Path()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -160,7 +160,7 @@ func decodeAddressList(ms *internal.Multistatus) ([]AddressObject, error) {
} }
addrs = append(addrs, AddressObject{ addrs = append(addrs, AddressObject{
Href: href, Path: path,
Card: card, Card: card,
}) })
} }
@ -198,7 +198,7 @@ func (c *Client) QueryAddressBook(addressBook string, query *AddressBookQuery) (
return decodeAddressList(ms) return decodeAddressList(ms)
} }
func (c *Client) MultiGetAddressBook(href string, multiGet *AddressBookMultiGet) ([]AddressObject, error) { func (c *Client) MultiGetAddressBook(path string, multiGet *AddressBookMultiGet) ([]AddressObject, error) {
var addrDataReq addressDataReq var addrDataReq addressDataReq
if multiGet != nil { if multiGet != nil {
for _, name := range multiGet.Props { for _, name := range multiGet.Props {
@ -213,13 +213,17 @@ func (c *Client) MultiGetAddressBook(href string, multiGet *AddressBookMultiGet)
addressbookMultiget := addressbookMultiget{Prop: propReq} addressbookMultiget := addressbookMultiget{Prop: propReq}
if multiGet == nil || len(multiGet.Hrefs) == 0 { if multiGet == nil || len(multiGet.Paths) == 0 {
addressbookMultiget.Hrefs = []string{href} href := internal.Href{Path: path}
addressbookMultiget.Hrefs = []internal.Href{href}
} else { } else {
addressbookMultiget.Hrefs = multiGet.Hrefs addressbookMultiget.Hrefs = make([]internal.Href, len(multiGet.Paths))
for i, p := range multiGet.Paths {
addressbookMultiget.Hrefs[i] = internal.Href{Path: p}
}
} }
req, err := c.ic.NewXMLRequest("REPORT", href, &addressbookMultiget) req, err := c.ic.NewXMLRequest("REPORT", path, &addressbookMultiget)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -26,7 +26,7 @@ var (
// https://tools.ietf.org/html/rfc6352#section-6.2.3 // https://tools.ietf.org/html/rfc6352#section-6.2.3
type addressbookHomeSet struct { type addressbookHomeSet struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:carddav addressbook-home-set"` XMLName xml.Name `xml:"urn:ietf:params:xml:ns:carddav addressbook-home-set"`
Href string `xml:"href"` Href internal.Href `xml:"href"`
} }
type addressbookDescription struct { type addressbookDescription struct {
@ -63,7 +63,7 @@ type addressbookQuery struct {
// https://tools.ietf.org/html/rfc6352#section-8.7 // https://tools.ietf.org/html/rfc6352#section-8.7
type addressbookMultiget struct { type addressbookMultiget struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:carddav addressbook-multiget"` XMLName xml.Name `xml:"urn:ietf:params:xml:ns:carddav addressbook-multiget"`
Hrefs []string `xml:"DAV: href"` Hrefs []internal.Href `xml:"DAV: href"`
Prop *internal.Prop `xml:"DAV: prop,omitempty"` Prop *internal.Prop `xml:"DAV: prop,omitempty"`
// TODO: DAV:allprop | DAV:propname // TODO: DAV:allprop | DAV:propname
} }

View File

@ -99,7 +99,7 @@ func (h *Handler) handleQuery(w http.ResponseWriter, query *addressbookQuery) er
func (h *Handler) handleMultiget(w http.ResponseWriter, multiget *addressbookMultiget) error { func (h *Handler) handleMultiget(w http.ResponseWriter, multiget *addressbookMultiget) error {
var resps []internal.Response var resps []internal.Response
for _, href := range multiget.Hrefs { for _, href := range multiget.Hrefs {
ao, err := h.Backend.GetAddressObject(href) ao, err := h.Backend.GetAddressObject(href.Path)
if err != nil { if err != nil {
return err // TODO: create internal.Response with error return err // TODO: create internal.Response with error
} }
@ -225,11 +225,11 @@ func (b *backend) propfindAddressBook(propfind *internal.Propfind, ab *AddressBo
}, },
// TODO: this is a principal property // TODO: this is a principal property
addressBookHomeSetName: func(*internal.RawXMLValue) (interface{}, error) { addressBookHomeSetName: func(*internal.RawXMLValue) (interface{}, error) {
return &addressbookHomeSet{Href: "/"}, nil return &addressbookHomeSet{Href: internal.Href{Path: "/"}}, nil
}, },
// TODO: this should be set on all resources // TODO: this should be set on all resources
internal.CurrentUserPrincipalName: func(*internal.RawXMLValue) (interface{}, error) { internal.CurrentUserPrincipalName: func(*internal.RawXMLValue) (interface{}, error) {
return &internal.CurrentUserPrincipal{Href: "/"}, nil return &internal.CurrentUserPrincipal{Href: internal.Href{Path: "/"}}, nil
}, },
} }
@ -258,7 +258,7 @@ func (b *backend) propfindAddressObject(propfind *internal.Propfind, ao *Address
// TODO: getlastmodified, getetag // TODO: getlastmodified, getetag
} }
return internal.NewPropfindResponse(ao.Href, propfind, props) return internal.NewPropfindResponse(ao.Path, propfind, props)
} }
func (b *backend) Proppatch(r *http.Request, update *internal.Propertyupdate) (*internal.Response, error) { func (b *backend) Proppatch(r *http.Request, update *internal.Propertyupdate) (*internal.Response, error) {

View File

@ -42,16 +42,16 @@ func (c *Client) FindCurrentUserPrincipal() (string, error) {
return "", fmt.Errorf("webdav: unauthenticated") return "", fmt.Errorf("webdav: unauthenticated")
} }
return prop.Href, nil return prop.Href.Path, nil
} }
func fileInfoFromResponse(resp *internal.Response) (*FileInfo, error) { func fileInfoFromResponse(resp *internal.Response) (*FileInfo, error) {
href, err := resp.Href() path, err := resp.Path()
if err != nil { if err != nil {
return nil, err return nil, err
} }
fi := &FileInfo{Href: href} fi := &FileInfo{Path: path}
var resType internal.ResourceType var resType internal.ResourceType
if err := resp.DecodeProp(&resType); err != nil { if err := resp.DecodeProp(&resType); err != nil {
@ -193,12 +193,7 @@ func (c *Client) CopyAll(name, dest string, overwrite bool) error {
return err return err
} }
dest, err = c.ic.ResolveHref(dest) req.Header.Set("Destination", c.ic.ResolveHref(dest).String())
if err != nil {
return err
}
req.Header.Set("Destination", dest)
req.Header.Set("Overwrite", internal.FormatOverwrite(overwrite)) req.Header.Set("Overwrite", internal.FormatOverwrite(overwrite))
_, err = c.ic.Do(req) _, err = c.ic.Do(req)
@ -211,12 +206,7 @@ func (c *Client) MoveAll(name, dest string, overwrite bool) error {
return err return err
} }
dest, err = c.ic.ResolveHref(dest) req.Header.Set("Destination", c.ic.ResolveHref(dest).String())
if err != nil {
return err
}
req.Header.Set("Destination", dest)
req.Header.Set("Overwrite", internal.FormatOverwrite(overwrite)) req.Header.Set("Overwrite", internal.FormatOverwrite(overwrite))
_, err = c.ic.Do(req) _, err = c.ic.Do(req)

View File

@ -14,7 +14,7 @@ import (
type LocalFileSystem string type LocalFileSystem string
func (fs LocalFileSystem) path(name string) (string, error) { func (fs LocalFileSystem) localPath(name string) (string, error) {
if (filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0) || strings.Contains(name, "\x00") { if (filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0) || strings.Contains(name, "\x00") {
return "", internal.HTTPErrorf(http.StatusBadRequest, "webdav: invalid character in path") return "", internal.HTTPErrorf(http.StatusBadRequest, "webdav: invalid character in path")
} }
@ -25,36 +25,35 @@ func (fs LocalFileSystem) path(name string) (string, error) {
return filepath.Join(string(fs), filepath.FromSlash(name)), nil return filepath.Join(string(fs), filepath.FromSlash(name)), nil
} }
func (fs LocalFileSystem) href(path string) (string, error) { func (fs LocalFileSystem) externalPath(name string) (string, error) {
rel, err := filepath.Rel(string(fs), path) rel, err := filepath.Rel(string(fs), name)
if err != nil { if err != nil {
return "", err return "", err
} }
href := "/" + filepath.ToSlash(rel) return "/" + filepath.ToSlash(rel), nil
return href, nil
} }
func (fs LocalFileSystem) Open(name string) (io.ReadCloser, error) { func (fs LocalFileSystem) Open(name string) (io.ReadCloser, error) {
p, err := fs.path(name) p, err := fs.localPath(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return os.Open(p) return os.Open(p)
} }
func fileInfoFromOS(href string, fi os.FileInfo) *FileInfo { func fileInfoFromOS(p string, fi os.FileInfo) *FileInfo {
return &FileInfo{ return &FileInfo{
Href: href, Path: p,
Size: fi.Size(), Size: fi.Size(),
ModTime: fi.ModTime(), ModTime: fi.ModTime(),
IsDir: fi.IsDir(), IsDir: fi.IsDir(),
// TODO: fallback to http.DetectContentType? // TODO: fallback to http.DetectContentType?
MIMEType: mime.TypeByExtension(path.Ext(href)), MIMEType: mime.TypeByExtension(path.Ext(p)),
} }
} }
func (fs LocalFileSystem) Stat(name string) (*FileInfo, error) { func (fs LocalFileSystem) Stat(name string) (*FileInfo, error) {
p, err := fs.path(name) p, err := fs.localPath(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -66,7 +65,7 @@ func (fs LocalFileSystem) Stat(name string) (*FileInfo, error) {
} }
func (fs LocalFileSystem) Readdir(name string, recursive bool) ([]FileInfo, error) { func (fs LocalFileSystem) Readdir(name string, recursive bool) ([]FileInfo, error) {
p, err := fs.path(name) p, err := fs.localPath(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -77,7 +76,7 @@ func (fs LocalFileSystem) Readdir(name string, recursive bool) ([]FileInfo, erro
return err return err
} }
href, err := fs.href(p) href, err := fs.externalPath(p)
if err != nil { if err != nil {
return err return err
} }
@ -93,7 +92,7 @@ func (fs LocalFileSystem) Readdir(name string, recursive bool) ([]FileInfo, erro
} }
func (fs LocalFileSystem) Create(name string) (io.WriteCloser, error) { func (fs LocalFileSystem) Create(name string) (io.WriteCloser, error) {
p, err := fs.path(name) p, err := fs.localPath(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -101,7 +100,7 @@ func (fs LocalFileSystem) Create(name string) (io.WriteCloser, error) {
} }
func (fs LocalFileSystem) RemoveAll(name string) error { func (fs LocalFileSystem) RemoveAll(name string) error {
p, err := fs.path(name) p, err := fs.localPath(name)
if err != nil { if err != nil {
return err return err
} }
@ -116,7 +115,7 @@ func (fs LocalFileSystem) RemoveAll(name string) error {
} }
func (fs LocalFileSystem) Mkdir(name string) error { func (fs LocalFileSystem) Mkdir(name string) error {
p, err := fs.path(name) p, err := fs.localPath(name)
if err != nil { if err != nil {
return err return err
} }

View File

@ -33,38 +33,27 @@ func (c *Client) SetBasicAuth(username, password string) {
c.password = password c.password = password
} }
func (c *Client) ResolveHref(href string) (string, error) { func (c *Client) ResolveHref(p string) *url.URL {
hrefURL, err := url.Parse(href) return &url.URL{
if err != nil {
return "", fmt.Errorf("webdav: failed to parse href %q: %v", href, err)
}
u := url.URL{
Scheme: c.endpoint.Scheme, Scheme: c.endpoint.Scheme,
User: c.endpoint.User, User: c.endpoint.User,
Host: c.endpoint.Host, Host: c.endpoint.Host,
Path: path.Join(c.endpoint.Path, hrefURL.Path), Path: path.Join(c.endpoint.Path, p),
RawQuery: hrefURL.RawQuery,
} }
return u.String(), nil
} }
func (c *Client) NewRequest(method string, href string, body io.Reader) (*http.Request, error) { func (c *Client) NewRequest(method string, path string, body io.Reader) (*http.Request, error) {
href, err := c.ResolveHref(href) return http.NewRequest(method, c.ResolveHref(path).String(), body)
if err != nil {
return nil, err
}
return http.NewRequest(method, href, body)
} }
func (c *Client) NewXMLRequest(method string, href string, v interface{}) (*http.Request, error) { func (c *Client) NewXMLRequest(method string, path string, v interface{}) (*http.Request, error) {
var buf bytes.Buffer var buf bytes.Buffer
buf.WriteString(xml.Header) buf.WriteString(xml.Header)
if err := xml.NewEncoder(&buf).Encode(v); err != nil { if err := xml.NewEncoder(&buf).Encode(v); err != nil {
return nil, err return nil, err
} }
req, err := c.NewRequest(method, href, &buf) req, err := c.NewRequest(method, path, &buf)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -101,8 +90,8 @@ func (c *Client) DoMultiStatus(req *http.Request) (*Multistatus, error) {
return &ms, nil return &ms, nil
} }
func (c *Client) Propfind(href string, depth Depth, propfind *Propfind) (*Multistatus, error) { func (c *Client) Propfind(path string, depth Depth, propfind *Propfind) (*Multistatus, error) {
req, err := c.NewXMLRequest("PROPFIND", href, propfind) req, err := c.NewXMLRequest("PROPFIND", path, propfind)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -113,11 +102,11 @@ func (c *Client) Propfind(href string, depth Depth, propfind *Propfind) (*Multis
} }
// PropfindFlat performs a PROPFIND request with a zero depth. // PropfindFlat performs a PROPFIND request with a zero depth.
func (c *Client) PropfindFlat(href string, propfind *Propfind) (*Response, error) { func (c *Client) PropfindFlat(path string, propfind *Propfind) (*Response, error) {
ms, err := c.Propfind(href, DepthZero, propfind) ms, err := c.Propfind(path, DepthZero, propfind)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return ms.Get(href) return ms.Get(path)
} }

View File

@ -4,6 +4,7 @@ import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"net/http" "net/http"
"net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -66,6 +67,26 @@ func (s *Status) Err() error {
return nil return nil
} }
type Href url.URL
func (h *Href) String() string {
u := (*url.URL)(h)
return u.String()
}
func (h *Href) MarshalText() ([]byte, error) {
return []byte(h.String()), nil
}
func (h *Href) UnmarshalText(b []byte) error {
u, err := url.Parse(string(b))
if err != nil {
return err
}
*h = Href(*u)
return nil
}
// https://tools.ietf.org/html/rfc4918#section-14.16 // https://tools.ietf.org/html/rfc4918#section-14.16
type Multistatus struct { type Multistatus struct {
XMLName xml.Name `xml:"DAV: multistatus"` XMLName xml.Name `xml:"DAV: multistatus"`
@ -77,23 +98,23 @@ func NewMultistatus(resps ...Response) *Multistatus {
return &Multistatus{Responses: resps} return &Multistatus{Responses: resps}
} }
func (ms *Multistatus) Get(href string) (*Response, error) { func (ms *Multistatus) Get(path string) (*Response, error) {
for i := range ms.Responses { for i := range ms.Responses {
resp := &ms.Responses[i] resp := &ms.Responses[i]
for _, h := range resp.Hrefs { for _, h := range resp.Hrefs {
if h == href { if h.Path == path {
return resp, resp.Status.Err() return resp, resp.Status.Err()
} }
} }
} }
return nil, fmt.Errorf("webdav: missing response for href %q", href) return nil, fmt.Errorf("webdav: missing response for path %q", path)
} }
// https://tools.ietf.org/html/rfc4918#section-14.24 // https://tools.ietf.org/html/rfc4918#section-14.24
type Response struct { type Response struct {
XMLName xml.Name `xml:"DAV: response"` XMLName xml.Name `xml:"DAV: response"`
Hrefs []string `xml:"href"` Hrefs []Href `xml:"href"`
Propstats []Propstat `xml:"propstat,omitempty"` Propstats []Propstat `xml:"propstat,omitempty"`
ResponseDescription string `xml:"responsedescription,omitempty"` ResponseDescription string `xml:"responsedescription,omitempty"`
Status *Status `xml:"status,omitempty"` Status *Status `xml:"status,omitempty"`
@ -101,21 +122,22 @@ type Response struct {
Location *Location `xml:"location,omitempty"` Location *Location `xml:"location,omitempty"`
} }
func NewOKResponse(href string) *Response { func NewOKResponse(path string) *Response {
href := Href{Path: path}
return &Response{ return &Response{
Hrefs: []string{href}, Hrefs: []Href{href},
Status: &Status{Code: http.StatusOK}, Status: &Status{Code: http.StatusOK},
} }
} }
func (resp *Response) Href() (string, error) { func (resp *Response) Path() (string, error) {
if err := resp.Status.Err(); err != nil { if err := resp.Status.Err(); err != nil {
return "", err return "", err
} }
if len(resp.Hrefs) != 1 { if len(resp.Hrefs) != 1 {
return "", fmt.Errorf("webdav: malformed response: expected exactly one href element, got %v", len(resp.Hrefs)) return "", fmt.Errorf("webdav: malformed response: expected exactly one href element, got %v", len(resp.Hrefs))
} }
return resp.Hrefs[0], nil return resp.Hrefs[0].Path, nil
} }
type missingPropError struct { type missingPropError struct {
@ -181,7 +203,7 @@ func (resp *Response) EncodeProp(code int, v interface{}) error {
// https://tools.ietf.org/html/rfc4918#section-14.9 // https://tools.ietf.org/html/rfc4918#section-14.9
type Location struct { type Location struct {
XMLName xml.Name `xml:"DAV: location"` XMLName xml.Name `xml:"DAV: location"`
Href string `xml:"href"` Href Href `xml:"href"`
} }
// https://tools.ietf.org/html/rfc4918#section-14.22 // https://tools.ietf.org/html/rfc4918#section-14.22
@ -332,7 +354,7 @@ type DisplayName struct {
// https://tools.ietf.org/html/rfc5397#section-3 // https://tools.ietf.org/html/rfc5397#section-3
type CurrentUserPrincipal struct { type CurrentUserPrincipal struct {
XMLName xml.Name `xml:"DAV: current-user-principal"` XMLName xml.Name `xml:"DAV: current-user-principal"`
Href string `xml:"href,omitempty"` Href Href `xml:"href,omitempty"`
Unauthenticated *struct{} `xml:"unauthenticated,omitempty"` Unauthenticated *struct{} `xml:"unauthenticated,omitempty"`
} }

View File

@ -171,8 +171,8 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) error {
type PropfindFunc func(raw *RawXMLValue) (interface{}, error) type PropfindFunc func(raw *RawXMLValue) (interface{}, error)
func NewPropfindResponse(href string, propfind *Propfind, props map[xml.Name]PropfindFunc) (*Response, error) { func NewPropfindResponse(path string, propfind *Propfind, props map[xml.Name]PropfindFunc) (*Response, error) {
resp := NewOKResponse(href) resp := NewOKResponse(path)
if _, ok := props[ResourceTypeName]; !ok { if _, ok := props[ResourceTypeName]; !ok {
props[ResourceTypeName] = func(*RawXMLValue) (interface{}, error) { props[ResourceTypeName] = func(*RawXMLValue) (interface{}, error) {

View File

@ -173,7 +173,7 @@ func (b *backend) propfindFile(propfind *internal.Propfind, fi *FileInfo) (*inte
// TODO: getetag // TODO: getetag
} }
return internal.NewPropfindResponse(fi.Href, propfind, props) return internal.NewPropfindResponse(fi.Path, propfind, props)
} }
func (b *backend) Proppatch(r *http.Request, update *internal.Propertyupdate) (*internal.Response, error) { func (b *backend) Proppatch(r *http.Request, update *internal.Propertyupdate) (*internal.Response, error) {

View File

@ -10,7 +10,7 @@ import (
// TODO: add ETag to FileInfo // TODO: add ETag to FileInfo
type FileInfo struct { type FileInfo struct {
Href string Path string
Size int64 Size int64
ModTime time.Time ModTime time.Time
IsDir bool IsDir bool