Compare commits

..

10 Commits

Author SHA1 Message Date
Alex Dunmow
f9b91e9a35 fork: module path git.dev.alexdunmow.com/blissful/go-webdav
Fork of emersion/go-webdav v0.8.0 for BlissCRM's calendar server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:47:46 +08:00
Jay Hemnani
1e38b14489 webdav: reject COPY and MOVE onto the same path
RFC 4918 sections 9.8.5 and 9.9.4 say the server should return 403 when
the source and destination are the same. Overwriting the destination
deletes the source, so LocalFileSystem lost the file.

Check this in the shared handler so every backend gets it.
2026-11-21 11:19:42 +01:00
Jay Hemnani
2b106fb99b webdav: fix LocalFileSystem.Copy for directories
The walk ignored the path of each entry: it created dstPath for every directory
and copied srcPath to dstPath for every file, so copying a non-empty directory
failed with "open: is a directory". With Overwrite the destination had already
been removed, so its files were lost. Copy each entry to its own path under the
destination.
2026-11-18 21:18:25 +01:00
Simon Ser
bf63772263 carddav: make malformed address object data non-fatal in client
Same as 8ddea980d48a ("caldav: make malformed calendar data
non-fatal in client"), but for the CardDAV side.
2026-11-13 14:58:01 +01:00
Robin van der Vleuten
2c2af7cdf2 caldav: add Calendar.Color
Read the calendar-color property in the http://apple.com/ns/ical/
namespace in FindCalendar and FindCalendars, and report it in PROPFIND
responses when it is set, the same way as calendar-description.
2026-11-13 14:29:23 +01:00
Robin van der Vleuten
ad1766c2ef
caldav, carddav: fill ReadOnly from current-user-privilege-set in client 2026-11-13 13:54:26 +01:00
Robin van der Vleuten
8ddea980d4 caldav: make malformed calendar data non-fatal in client
QueryCalendar and MultiGetCalendar returned no objects at all when the
calendar-data of one of them failed to parse. Skip that object instead
and report its error, with its href, in the returned error, like
multistatus errors since 71ae569.
2026-11-12 22:07:44 +01:00
Henry Stern
4ce863ae71 caldav, carddav: support If-Match/If-None-Match on client PUT
PutCalendarObject and PutAddressObject sent no conditional request
headers, so a client could not perform an optimistic-concurrency write
(overwrite only if the resource still carries an expected ETag). Add an
options parameter to both, reusing the existing server-side
PutCalendarObjectOptions / PutAddressObjectOptions types so the client
and Backend interface mirror each other. A nil opts preserves the prior
unconditional behaviour; a non-nil opts sets If-Match / If-None-Match.

Signed-off-by: Henry Stern <henry@stern.ca>
Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
Closes: https://github.com/emersion/go-webdav/issues/130
2026-11-12 17:55:00 +01:00
Robin van der Vleuten
bcd0dee048 webdav: add support for If-Match/If-None-Match in Client.RemoveAll
Client.RemoveAll had no way to send conditional headers, so a client
could not delete a resource only if it still has a known ETag. Take a
*RemoveAllOptions, the same type FileSystem.RemoveAll uses on the server
side. A nil value keeps the previous unconditional behavior.
2026-11-12 14:04:11 +01:00
Henry Stern
c16f8a9a13 caldav: decode inline calendar-data in SyncCollection responses
SyncCollection already requests calendar-data via the query's CompRequest, but
only the ETag and last-modified props were decoded, so a caller had to follow
every sync with a multiget even when the server (e.g. Radicale, SOGo) returned
the calendar object inline in the sync-collection response.

Decode the calendar-data prop into CalendarObject.Data when it is present; when
the server omits it, Data is left nil and the caller fetches it with a multiget
as before. Backward compatible.

Signed-off-by: Henry Stern <henry@stern.ca>
Assisted-by: Claude (Anthropic) <noreply@anthropic.com>
2026-06-28 12:28:23 +02:00
28 changed files with 765 additions and 37 deletions

View File

@ -1,3 +1,10 @@
# go-webdav (BlissCRM fork)
This is a fork of [emersion/go-webdav](https://github.com/emersion/go-webdav) at v0.8.0, kept for BlissCRM's calendar
server. Its module path is `git.dev.alexdunmow.com/blissful/go-webdav`. BlissCRM adds the CalDAV parts its phones need
(getctag, sync-collection, the user's calendar address, scheduling and free/busy). The licence is unchanged (MIT, see
LICENSE). Upstream changes are merged by hand.
# go-webdav
[![Go Reference](https://pkg.go.dev/badge/github.com/emersion/go-webdav.svg)](https://pkg.go.dev/github.com/emersion/go-webdav)

View File

@ -8,8 +8,8 @@ import (
"time"
"github.com/emersion/go-ical"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
var CapabilityCalendar = webdav.Capability("calendar-access")
@ -69,8 +69,15 @@ type Calendar struct {
Description string
MaxResourceSize int64
SupportedComponentSet []string
// Color is the value of the calendar-color property in the
// http://apple.com/ns/ical/ namespace. That property is not defined by
// CalDAV. The value is a hexadecimal string following the #rrggbb syntax,
// or #rrggbbaa with an alpha channel, as Apple Calendar writes it.
Color string
// ReadOnly reports that the current user may only read this calendar. It
// controls the DAV:current-user-privilege-set reported by the server.
// controls the DAV:current-user-privilege-set reported by the server. The
// client sets it when the server reports a DAV:current-user-privilege-set
// that doesn't grant DAV:write.
ReadOnly bool
}

View File

@ -14,8 +14,8 @@ import (
"time"
"github.com/emersion/go-ical"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
var calendarProps = []xml.Name{
@ -24,6 +24,8 @@ var calendarProps = []xml.Name{
calendarDescriptionName,
maxResourceSizeName,
supportedCalendarComponentSetName,
internal.CurrentUserPrivilegeSetName,
calendarColorName,
}
// DiscoverContextURL performs a DNS-based CardDAV service discovery as
@ -128,6 +130,11 @@ func decodeCalendar(path string, resp *internal.Response) (*Calendar, error) {
return nil, err
}
var color calendarColor
if err := resp.DecodeProp(&color); err != nil && !internal.IsNotFound(err) {
return nil, err
}
var maxResSize maxResourceSize
if err := resp.DecodeProp(&maxResSize); err != nil && !internal.IsNotFound(err) {
return nil, err
@ -141,6 +148,14 @@ func decodeCalendar(path string, resp *internal.Response) (*Calendar, error) {
return nil, err
}
var privSet internal.CurrentUserPrivilegeSet
readOnly := false
if err := resp.DecodeProp(&privSet); err == nil {
readOnly = privSet.ReadOnly()
} else if !internal.IsNotFound(err) {
return nil, err
}
compNames := make([]string, 0, len(supportedCompSet.Comp))
for _, comp := range supportedCompSet.Comp {
compNames = append(compNames, comp.Name)
@ -152,6 +167,8 @@ func decodeCalendar(path string, resp *internal.Response) (*Calendar, error) {
Description: desc.Description,
MaxResourceSize: maxResSize.Size,
SupportedComponentSet: compNames,
Color: color.Color,
ReadOnly: readOnly,
}, nil
}
@ -294,7 +311,8 @@ func decodeCalendarObjectList(ms *internal.MultiStatus) ([]CalendarObject, error
r := bytes.NewReader(calData.Data)
data, err := ical.NewDecoder(r).Decode()
if err != nil {
return nil, err
errs = append(errs, &internal.HrefError{Href: url.URL(resp.Hrefs[0]), Err: err})
continue
}
addrs = append(addrs, CalendarObject{
@ -432,8 +450,11 @@ func (c *Client) GetCalendarObject(ctx context.Context, path string) (*CalendarO
return co, nil
}
func (c *Client) PutCalendarObject(ctx context.Context, path string, cal *ical.Calendar) (*CalendarObject, error) {
// TODO: add support for If-None-Match and If-Match
// PutCalendarObject stores cal as the calendar object resource at path.
func (c *Client) PutCalendarObject(ctx context.Context, path string, cal *ical.Calendar, opts *PutCalendarObjectOptions) (*CalendarObject, error) {
if opts == nil {
opts = new(PutCalendarObjectOptions)
}
// TODO: some servers want a Content-Length header, so we can't stream the
// request body here. See the Radicale issue:
@ -449,6 +470,12 @@ func (c *Client) PutCalendarObject(ctx context.Context, path string, cal *ical.C
return nil, err
}
req.Header.Set("Content-Type", ical.MIMEType)
if opts.IfMatch.IsSet() {
req.Header.Set("If-Match", string(opts.IfMatch))
}
if opts.IfNoneMatch.IsSet() {
req.Header.Set("If-None-Match", string(opts.IfNoneMatch))
}
resp, err := c.ic.Do(req.WithContext(ctx))
if err != nil {
@ -515,6 +542,22 @@ func (c *Client) SyncCollection(ctx context.Context, path string, query *SyncQue
ModTime: time.Time(getLastMod.LastModified),
ETag: string(getETag.ETag),
}
// Many servers return the calendar-data inline in the sync-collection
// response (the query already requests it via CompRequest); decode it so
// the caller need not follow up with a multiget. When the server omits the
// data, Data is left nil and the caller fetches it as before.
var calData calendarDataResp
if err := resp.DecodeProp(&calData); err == nil {
cal, err := ical.NewDecoder(bytes.NewReader(calData.Data)).Decode()
if err != nil {
return nil, err
}
o.Data = cal
} else if !internal.IsNotFound(err) {
return nil, err
}
ret.Updated = append(ret.Updated, o)
}

View File

@ -0,0 +1,88 @@
package caldav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/emersion/go-ical"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// minimalCalendar builds a single-VEVENT VCALENDAR valid enough to encode.
func minimalCalendar() *ical.Calendar {
cal := ical.NewCalendar()
cal.Props.SetText(ical.PropVersion, "2.0")
cal.Props.SetText(ical.PropProductID, "-//go-webdav//test//EN")
ev := ical.NewEvent()
ev.Props.SetText(ical.PropUID, "test-uid")
ev.Props.SetDateTime(ical.PropDateTimeStamp, time.Date(2026, 6, 24, 0, 0, 0, 0, time.UTC))
cal.Children = append(cal.Children, ev.Component)
return cal
}
// TestPutCalendarObjectSendsIfMatch verifies the client forwards the
// PutCalendarObjectOptions.IfMatch ETag as an If-Match request header and
// returns the server's new ETag.
func TestPutCalendarObjectSendsIfMatch(t *testing.T) {
var gotIfMatch string
var gotMethod string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotIfMatch = r.Header.Get("If-Match")
w.Header().Set("ETag", `"new-etag"`)
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutCalendarObjectOptions{IfMatch: webdav.ConditionalMatch(`"old-etag"`)}
co, err := c.PutCalendarObject(context.Background(), "/cal/test-uid.ics", minimalCalendar(), opts)
if err != nil {
t.Fatalf("PutCalendarObject: %v", err)
}
if gotMethod != http.MethodPut {
t.Errorf("method = %q, want PUT", gotMethod)
}
if gotIfMatch != `"old-etag"` {
t.Errorf("If-Match header = %q, want %q", gotIfMatch, `"old-etag"`)
}
if co.ETag != "new-etag" {
t.Errorf("returned ETag = %q, want %q", co.ETag, "new-etag")
}
}
// TestPutCalendarObjectPreconditionFailed verifies a 412 response surfaces as
// an error whose status code consumers can read via webdav.HTTPErrorCode.
func TestPutCalendarObjectPreconditionFailed(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPreconditionFailed)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutCalendarObjectOptions{IfMatch: webdav.ConditionalMatch(`"stale"`)}
_, err = c.PutCalendarObject(context.Background(), "/cal/test-uid.ics", minimalCalendar(), opts)
if err == nil {
t.Fatal("PutCalendarObject: want error on 412, got nil")
}
var httpErr *internal.HTTPError
if !errors.As(err, &httpErr) {
t.Fatalf("not an HTTP error: %v", err)
}
if httpErr.Code != http.StatusPreconditionFailed {
t.Errorf("status code = %d, want %d", httpErr.Code, http.StatusPreconditionFailed)
}
}

View File

@ -0,0 +1,78 @@
package caldav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
const queryCalendarMalformedResponse = `<?xml version="1.0" encoding="utf-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:response>
<d:href>/cal/good.ics</d:href>
<d:propstat>
<d:prop>
<d:getetag>"good"</d:getetag>
<c:calendar-data>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//go-webdav//test//EN
BEGIN:VEVENT
UID:good
DTSTAMP:20260624T000000Z
END:VEVENT
END:VCALENDAR
</c:calendar-data>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/bad.ics</d:href>
<d:propstat>
<d:prop>
<d:getetag>"bad"</d:getetag>
<c:calendar-data>BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:bad
</c:calendar-data>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func TestQueryCalendarMalformedObject(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
w.Write([]byte(queryCalendarMalformedResponse))
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
objs, err := c.QueryCalendar(context.Background(), "/cal/", &CalendarQuery{
CompFilter: CompFilter{Name: "VCALENDAR"},
})
var hrefErr *internal.HrefError
if !errors.As(err, &hrefErr) {
t.Fatalf("QueryCalendar: want an *internal.HrefError, got %v", err)
}
if hrefErr.Href.Path != "/cal/bad.ics" {
t.Errorf("HrefError.Href = %q, want %q", hrefErr.Href.Path, "/cal/bad.ics")
}
if len(objs) != 1 {
t.Fatalf("got %d objects, want 1", len(objs))
}
if objs[0].Path != "/cal/good.ics" || objs[0].ETag != "good" || objs[0].Data == nil {
t.Errorf("got object %+v, want /cal/good.ics with ETag good and data", objs[0])
}
}

99
caldav/client_test.go Normal file
View File

@ -0,0 +1,99 @@
package caldav
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
const findCalendarsReadOnlyResponse = `<?xml version="1.0" encoding="utf-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:response>
<d:href>/cal/read-only/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/write-content/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write-content/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/write/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write/></d:privilege>
<d:privilege><d:write-content/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/unknown/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
<d:propstat>
<d:prop>
<d:current-user-privilege-set/>
</d:prop>
<d:status>HTTP/1.1 404 Not Found</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func TestFindCalendarsReadOnly(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
w.Write([]byte(findCalendarsReadOnlyResponse))
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
cals, err := c.FindCalendars(context.Background(), "/cal/")
if err != nil {
t.Fatalf("FindCalendars: %v", err)
}
want := map[string]bool{
"/cal/read-only/": true,
"/cal/write-content/": true,
"/cal/write/": false,
"/cal/unknown/": false,
}
if len(cals) != len(want) {
t.Fatalf("got %d calendars, want %d", len(cals), len(want))
}
for _, cal := range cals {
if cal.ReadOnly != want[cal.Path] {
t.Errorf("%s: ReadOnly = %v, want %v", cal.Path, cal.ReadOnly, want[cal.Path])
}
}
}

View File

@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
const namespace = "urn:ietf:params:xml:ns:caldav"
@ -23,6 +23,8 @@ var (
calendarName = xml.Name{namespace, "calendar"}
calendarDataName = xml.Name{namespace, "calendar-data"}
calendarColorName = xml.Name{"http://apple.com/ns/ical/", "calendar-color"}
)
// https://tools.ietf.org/html/rfc4791#section-6.2.1
@ -41,6 +43,13 @@ type calendarDescription struct {
Description string `xml:",chardata"`
}
// calendar-color is not defined by any RFC. It comes from Apple's
// http://apple.com/ns/ical/ namespace.
type calendarColor struct {
XMLName xml.Name `xml:"http://apple.com/ns/ical/ calendar-color"`
Color string `xml:",chardata"`
}
// https://tools.ietf.org/html/rfc4791#section-5.2.4
type supportedCalendarData struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:caldav supported-calendar-data"`

View File

@ -13,8 +13,8 @@ import (
"time"
"github.com/emersion/go-ical"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// TODO if nothing more Caldav-specific needs to be added this should be merged with carddav.PutAddressObjectOptions
@ -559,6 +559,11 @@ func (b *backend) propFindCalendar(ctx context.Context, propfind *internal.PropF
Description: cal.Description,
})
}
if cal.Color != "" {
props[calendarColorName] = internal.PropFindValue(&calendarColor{
Color: cal.Color,
})
}
if cal.MaxResourceSize > 0 {
props[maxResourceSizeName] = internal.PropFindValue(&maxResourceSize{
Size: cal.MaxResourceSize,

View File

@ -233,3 +233,34 @@ func (t testBackend) ListCalendarObjects(ctx context.Context, path string, req *
func (t testBackend) QueryCalendarObjects(ctx context.Context, path string, query *CalendarQuery) ([]CalendarObject, error) {
return nil, nil
}
func TestFindCalendarsColor(t *testing.T) {
h := Handler{Backend: testBackend{calendars: []Calendar{
{Path: "/user/calendars/a/", Color: "#FF2968FF"},
{Path: "/user/calendars/b/"},
}}}
srv := httptest.NewServer(&h)
defer srv.Close()
c, err := NewClient(nil, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
cals, err := c.FindCalendars(context.Background(), "/user/calendars/")
if err != nil {
t.Fatalf("FindCalendars: %v", err)
}
want := map[string]string{
"/user/calendars/a/": "#FF2968FF",
"/user/calendars/b/": "",
}
if len(cals) != len(want) {
t.Fatalf("got %d calendars, want %d", len(cals), len(want))
}
for _, cal := range cals {
if cal.Color != want[cal.Path] {
t.Errorf("%s: Color = %q, want %q", cal.Path, cal.Color, want[cal.Path])
}
}
}

View File

@ -7,8 +7,8 @@ import (
"time"
"github.com/emersion/go-vcard"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
var CapabilityAddressBook = webdav.Capability("addressbook")
@ -30,6 +30,8 @@ type AddressBook struct {
SupportedAddressData []AddressDataType
// ReadOnly reports that the current user may only read this address book.
// It controls the DAV:current-user-privilege-set reported by the server.
// The client sets it when the server reports a
// DAV:current-user-privilege-set that doesn't grant DAV:write.
ReadOnly bool
}

View File

@ -9,7 +9,7 @@ import (
"testing"
"github.com/emersion/go-vcard"
"github.com/emersion/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav"
)
type testBackend struct {

View File

@ -13,8 +13,8 @@ import (
"time"
"github.com/emersion/go-vcard"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// DiscoverContextURL performs a DNS-based CardDAV service discovery as
@ -84,6 +84,7 @@ func (c *Client) FindAddressBooks(ctx context.Context, addressBookHomeSet string
addressBookDescriptionName,
maxResourceSizeName,
supportedAddressDataName,
internal.CurrentUserPrivilegeSetName,
)
ms, err := c.ic.PropFind(ctx, addressBookHomeSet, internal.DepthOne, propfind)
if err != nil {
@ -130,12 +131,21 @@ func (c *Client) FindAddressBooks(ctx context.Context, addressBookHomeSet string
return nil, err
}
var privSet internal.CurrentUserPrivilegeSet
readOnly := false
if err := resp.DecodeProp(&privSet); err == nil {
readOnly = privSet.ReadOnly()
} else if !internal.IsNotFound(err) {
return nil, err
}
l = append(l, AddressBook{
Path: path,
Name: dispName.Name,
Description: desc.Description,
MaxResourceSize: maxResSize.Size,
SupportedAddressData: decodeSupportedAddressData(&supported),
ReadOnly: readOnly,
})
}
@ -233,7 +243,8 @@ func decodeAddressList(ms *internal.MultiStatus) ([]AddressObject, error) {
r := bytes.NewReader(addrData.Data)
card, err := vcard.NewDecoder(r).Decode()
if err != nil {
return nil, err
errs = append(errs, &internal.HrefError{Href: url.URL(resp.Hrefs[0])})
continue
}
addrs = append(addrs, AddressObject{
@ -384,8 +395,11 @@ func (c *Client) GetAddressObject(ctx context.Context, path string) (*AddressObj
return ao, nil
}
func (c *Client) PutAddressObject(ctx context.Context, path string, card vcard.Card) (*AddressObject, error) {
// TODO: add support for If-None-Match and If-Match
// PutAddressObject stores card as the address object resource at path.
func (c *Client) PutAddressObject(ctx context.Context, path string, card vcard.Card, opts *PutAddressObjectOptions) (*AddressObject, error) {
if opts == nil {
opts = new(PutAddressObjectOptions)
}
// TODO: some servers want a Content-Length header, so we can't stream the
// request body here. See the Radicale issue:
@ -408,6 +422,12 @@ func (c *Client) PutAddressObject(ctx context.Context, path string, card vcard.C
return nil, err
}
req.Header.Set("Content-Type", vcard.MIMEType)
if opts.IfMatch.IsSet() {
req.Header.Set("If-Match", string(opts.IfMatch))
}
if opts.IfNoneMatch.IsSet() {
req.Header.Set("If-None-Match", string(opts.IfNoneMatch))
}
resp, err := c.ic.Do(req.WithContext(ctx))
if err != nil {

View File

@ -0,0 +1,81 @@
package carddav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/emersion/go-vcard"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
func minimalCard() vcard.Card {
card := make(vcard.Card)
card.SetValue(vcard.FieldFormattedName, "Alice Gopher")
card.SetValue(vcard.FieldUID, "test-uid")
vcard.ToV4(card)
return card
}
// TestPutAddressObjectSendsIfMatch verifies the client forwards
// PutAddressObjectOptions.IfMatch as an If-Match request header and returns the
// server's new ETag.
func TestPutAddressObjectSendsIfMatch(t *testing.T) {
var gotIfMatch, gotMethod string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotIfMatch = r.Header.Get("If-Match")
w.Header().Set("ETag", `"new-etag"`)
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutAddressObjectOptions{IfMatch: webdav.ConditionalMatch(`"old-etag"`)}
ao, err := c.PutAddressObject(context.Background(), "/contacts/test-uid.vcf", minimalCard(), opts)
if err != nil {
t.Fatalf("PutAddressObject: %v", err)
}
if gotMethod != http.MethodPut {
t.Errorf("method = %q, want PUT", gotMethod)
}
if gotIfMatch != `"old-etag"` {
t.Errorf("If-Match header = %q, want %q", gotIfMatch, `"old-etag"`)
}
if ao.ETag != "new-etag" {
t.Errorf("returned ETag = %q, want %q", ao.ETag, "new-etag")
}
}
// TestPutAddressObjectPreconditionFailed verifies a 412 response surfaces as an
// error readable via webdav.HTTPErrorCode.
func TestPutAddressObjectPreconditionFailed(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPreconditionFailed)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutAddressObjectOptions{IfMatch: webdav.ConditionalMatch(`"stale"`)}
_, err = c.PutAddressObject(context.Background(), "/contacts/test-uid.vcf", minimalCard(), opts)
if err == nil {
t.Fatal("PutAddressObject: want error on 412, got nil")
}
var httpErr *internal.HTTPError
if !errors.As(err, &httpErr) {
t.Fatalf("not an HTTP error: %v", err)
}
if httpErr.Code != http.StatusPreconditionFailed {
t.Errorf("status code = %d, want %d", httpErr.Code, http.StatusPreconditionFailed)
}
}

69
carddav/client_test.go Normal file
View File

@ -0,0 +1,69 @@
package carddav
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
const findAddressBooksReadOnlyResponse = `<?xml version="1.0" encoding="utf-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
<d:response>
<d:href>/contacts/read-only/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><card:addressbook/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/contacts/all/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><card:addressbook/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:all/></d:privilege>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func TestFindAddressBooksReadOnly(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
w.Write([]byte(findAddressBooksReadOnlyResponse))
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
abs, err := c.FindAddressBooks(context.Background(), "/contacts/")
if err != nil {
t.Fatalf("FindAddressBooks: %v", err)
}
want := map[string]bool{
"/contacts/read-only/": true,
"/contacts/all/": false,
}
if len(abs) != len(want) {
t.Fatalf("got %d address books, want %d", len(abs), len(want))
}
for _, ab := range abs {
if ab.ReadOnly != want[ab.Path] {
t.Errorf("%s: ReadOnly = %v, want %v", ab.Path, ab.ReadOnly, want[ab.Path])
}
}
}

View File

@ -4,7 +4,7 @@ import (
"encoding/xml"
"fmt"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
const namespace = "urn:ietf:params:xml:ns:carddav"

View File

@ -12,8 +12,8 @@ import (
"strings"
"github.com/emersion/go-vcard"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
type PutAddressObjectOptions struct {

View File

@ -8,7 +8,7 @@ import (
"net/http"
"time"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// HTTPClient performs HTTP requests. It's implemented by *http.Client.
@ -221,12 +221,23 @@ func (c *Client) Create(ctx context.Context, name string) (io.WriteCloser, error
// RemoveAll deletes a file. If the file is a directory, all of its descendants
// are recursively deleted as well.
func (c *Client) RemoveAll(ctx context.Context, name string) error {
func (c *Client) RemoveAll(ctx context.Context, name string, opts *RemoveAllOptions) error {
if opts == nil {
opts = new(RemoveAllOptions)
}
req, err := c.ic.NewRequest(http.MethodDelete, name, nil)
if err != nil {
return err
}
if opts.IfMatch.IsSet() {
req.Header.Set("If-Match", string(opts.IfMatch))
}
if opts.IfNoneMatch.IsSet() {
req.Header.Set("If-None-Match", string(opts.IfNoneMatch))
}
resp, err := c.ic.Do(req.WithContext(ctx))
if err != nil {
return err

78
client_test.go Normal file
View File

@ -0,0 +1,78 @@
package webdav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
func TestClientRemoveAll(t *testing.T) {
for _, tc := range []struct {
name string
opts *RemoveAllOptions
wantIfMatch string
wantIfNoneMatch string
}{
{name: "nil options"},
{
name: "If-Match",
opts: &RemoveAllOptions{IfMatch: `"abc"`},
wantIfMatch: `"abc"`,
},
{
name: "If-None-Match",
opts: &RemoveAllOptions{IfNoneMatch: "*"},
wantIfNoneMatch: "*",
},
} {
t.Run(tc.name, func(t *testing.T) {
var gotMethod, gotIfMatch, gotIfNoneMatch string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotIfMatch = r.Header.Get("If-Match")
gotIfNoneMatch = r.Header.Get("If-None-Match")
w.WriteHeader(http.StatusNoContent)
}))
defer ts.Close()
c, err := NewClient(nil, ts.URL)
if err != nil {
t.Fatalf("NewClient() = %v", err)
}
if err := c.RemoveAll(context.Background(), "/file", tc.opts); err != nil {
t.Fatalf("RemoveAll() = %v", err)
}
if gotMethod != http.MethodDelete {
t.Errorf("method = %q, want %q", gotMethod, http.MethodDelete)
}
if gotIfMatch != tc.wantIfMatch {
t.Errorf("If-Match = %q, want %q", gotIfMatch, tc.wantIfMatch)
}
if gotIfNoneMatch != tc.wantIfNoneMatch {
t.Errorf("If-None-Match = %q, want %q", gotIfNoneMatch, tc.wantIfNoneMatch)
}
})
}
}
func TestClientRemoveAllPreconditionFailed(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPreconditionFailed)
}))
defer ts.Close()
c, err := NewClient(nil, ts.URL)
if err != nil {
t.Fatalf("NewClient() = %v", err)
}
err = c.RemoveAll(context.Background(), "/file", &RemoveAllOptions{IfMatch: `"abc"`})
var httpErr *internal.HTTPError
if !errors.As(err, &httpErr) || httpErr.Code != http.StatusPreconditionFailed {
t.Fatalf("RemoveAll() = %v, want HTTP error with status %v", err, http.StatusPreconditionFailed)
}
}

View File

@ -7,7 +7,7 @@ import (
"net/http"
"os"
"github.com/emersion/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav"
)
func main() {

View File

@ -3,7 +3,7 @@ package webdav
import (
"encoding/xml"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
var (

View File

@ -13,7 +13,7 @@ import (
"path/filepath"
"strings"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// LocalFileSystem implements FileSystem for a local directory.
@ -252,11 +252,9 @@ func (fs LocalFileSystem) Copy(ctx context.Context, src, dst string, options *Co
// TODO: "Note that an infinite-depth COPY of /A/ into /A/B/ could lead to
// infinite recursion if not handled correctly"
srcInfo, err := os.Stat(srcPath)
if err != nil {
if _, err := os.Stat(srcPath); err != nil {
return false, errFromOS(err)
}
srcPerm := srcInfo.Mode() & os.ModePerm
if _, err := os.Stat(dstPath); err != nil {
if !os.IsNotExist(err) {
@ -277,12 +275,19 @@ func (fs LocalFileSystem) Copy(ctx context.Context, src, dst string, options *Co
return err
}
rel, err := filepath.Rel(srcPath, p)
if err != nil {
return err
}
target := filepath.Join(dstPath, rel)
perm := fi.Mode() & os.ModePerm
if fi.IsDir() {
if err := os.Mkdir(dstPath, srcPerm); err != nil {
if err := os.Mkdir(target, perm); err != nil {
return errFromOS(err)
}
} else {
if err := copyRegularFile(srcPath, dstPath, srcPerm); err != nil {
if err := copyRegularFile(p, target, perm); err != nil {
return err
}
}

36
fs_local_test.go Normal file
View File

@ -0,0 +1,36 @@
package webdav
import (
"context"
"os"
"path/filepath"
"testing"
)
func TestLocalFileSystemCopyDirectory(t *testing.T) {
dir := t.TempDir()
for name, data := range map[string]string{"src/a.txt": "a", "src/sub/b.txt": "b", "dst/old.txt": "old"} {
p := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(data), 0o644); err != nil {
t.Fatal(err)
}
}
fs := LocalFileSystem(dir)
if _, err := fs.Copy(context.Background(), "/src", "/dst", &CopyOptions{}); err != nil {
t.Fatalf("Copy() = %v", err)
}
for name, want := range map[string]string{"dst/a.txt": "a", "dst/sub/b.txt": "b"} {
got, err := os.ReadFile(filepath.Join(dir, name))
if err != nil || string(got) != want {
t.Errorf("%s = %q, %v; want %q", name, got, err, want)
}
}
if _, err := os.Stat(filepath.Join(dir, "dst/old.txt")); !os.IsNotExist(err) {
t.Errorf("dst/old.txt still exists after overwrite: %v", err)
}
}

2
go.mod
View File

@ -1,4 +1,4 @@
module github.com/emersion/go-webdav
module git.dev.alexdunmow.com/blissful/go-webdav
go 1.13

View File

@ -462,7 +462,7 @@ type Limit struct {
// https://tools.ietf.org/html/rfc3744#section-5.4
type CurrentUserPrivilegeSet struct {
XMLName xml.Name `xml:"DAV: current-user-privilege-set"`
Privilege []Privilege
Privilege []Privilege `xml:"DAV: privilege"`
}
// https://tools.ietf.org/html/rfc3744#section-5.4
@ -481,3 +481,15 @@ func NewCurrentUserPrivilegeSet(readOnly bool) *CurrentUserPrivilegeSet {
}
return &CurrentUserPrivilegeSet{Privilege: []Privilege{priv}}
}
// ReadOnly reports whether the set doesn't grant DAV:write. The set lists
// aggregate privileges together with the ones they contain (RFC 3744 section
// 5.4), so DAV:write is listed whenever it is granted, also through DAV:all.
func (set *CurrentUserPrivilegeSet) ReadOnly() bool {
for _, priv := range set.Privilege {
if priv.Write != nil {
return false
}
}
return true
}

View File

@ -8,6 +8,7 @@ import (
"mime"
"net/http"
"net/url"
"path"
"strings"
)
@ -284,6 +285,12 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) error {
}
}
// RFC 4918 sections 9.8.5 and 9.9.4: overwriting the destination would
// delete the source.
if path.Clean(r.URL.Path) == path.Clean(dest.Path) {
return HTTPErrorf(http.StatusForbidden, "webdav: source and destination are the same")
}
var created bool
if r.Method == "COPY" {
var recursive bool

View File

@ -9,7 +9,7 @@ import (
"strconv"
"strings"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// FileSystem is a WebDAV server backend.

40
server_test.go Normal file
View File

@ -0,0 +1,40 @@
package webdav
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestHandlerCopyMoveOntoItself(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "a.txt")
if err := os.WriteFile(p, []byte("a"), 0o644); err != nil {
t.Fatal(err)
}
ts := httptest.NewServer(&Handler{FileSystem: LocalFileSystem(dir)})
defer ts.Close()
for _, method := range []string{"COPY", "MOVE"} {
req, err := http.NewRequest(method, ts.URL+"/a.txt", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Destination", ts.URL+"/a.txt")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("%v onto itself: status = %v, want %v", method, resp.StatusCode, http.StatusForbidden)
}
}
if got, err := os.ReadFile(p); err != nil || string(got) != "a" {
t.Errorf("a.txt = %q, %v; want %q", got, err, "a")
}
}

View File

@ -6,7 +6,7 @@ package webdav
import (
"time"
"github.com/emersion/go-webdav/internal"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// FileInfo holds information about a WebDAV file.