Files
Anya Tokugawa 19e12f96a8
Build and publish container images / images (push) Successful in 13m39s
Release container images / release (push) Successful in 18s
Add private CardDAV synchronization and contact revision recovery
2026-11-02 08:41:15 +09:00

587 lines
18 KiB
Go

package server
import (
"context"
"database/sql"
"encoding/xml"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
"golang.org/x/text/unicode/norm"
"pageswiki/internal/store"
)
const contactDAV = "/_/api/v1/carddav/"
const cardNS = "urn:ietf:params:xml:ns:carddav"
func contactDAVRoute(p string) bool {
return p == strings.TrimSuffix(contactDAV, "/") || strings.HasPrefix(p, contactDAV) || p == "/.well-known/carddav"
}
func contactDAVError(w http.ResponseWriter, status int, ns, condition string) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(status)
io.WriteString(w, `<?xml version="1.0"?><d:error xmlns:d="DAV:"><p:`+condition+` xmlns:p="`+xmlText(ns)+`"/></d:error>`)
}
func contactDAVStoreError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, sql.ErrNoRows):
w.WriteHeader(404)
case errors.Is(err, store.ErrTaskConflict):
w.WriteHeader(412)
case errors.Is(err, store.ErrContactUIDConflict):
contactDAVError(w, 403, cardNS, "no-uid-conflict")
case errors.Is(err, store.ErrContactSyncToken):
contactDAVError(w, 403, davNS, "valid-sync-token")
case errors.Is(err, store.ErrAccessDenied):
w.WriteHeader(403)
case errors.Is(err, store.ErrTaskInvalid):
contactDAVError(w, 403, cardNS, "valid-address-data")
default:
http.Error(w, "address book operation failed", 500)
}
}
func contactDAVRow(base string, item store.ContactDAVItem) davResponse {
row := davResponse{href: base + item.Name}
if item.Deleted {
row.status = 404
return row
}
size := len(item.VCard)
if item.Size > 0 {
size = item.Size
}
row.props = map[xml.Name]string{
{Space: davNS, Local: "getetag"}: xmlText(store.ContactETag(item.Contact)),
{Space: davNS, Local: "resourcetype"}: "",
{Space: davNS, Local: "getcontenttype"}: "text/vcard; charset=utf-8",
{Space: davNS, Local: "getcontentlength"}: strconv.Itoa(size),
{Space: cardNS, Local: "address-data"}: xmlText(item.VCard),
}
return row
}
func contactBookRow(base, token string, writable bool) davResponse {
return davResponse{href: base, props: map[xml.Name]string{
{Space: davNS, Local: "displayname"}: "PagesWiki Contacts",
{Space: davNS, Local: "resourcetype"}: "<d:collection/><a:addressbook/>",
{Space: davNS, Local: "current-user-privilege-set"}: davPrivileges(writable),
{Space: davNS, Local: "sync-token"}: xmlText(token),
{Space: "http://calendarserver.org/ns/", Local: "getctag"}: xmlText(token),
{Space: cardNS, Local: "addressbook-description"}: "Private contacts",
{Space: cardNS, Local: "max-resource-size"}: "65536",
{Space: cardNS, Local: "supported-address-data"}: `<a:address-data-type content-type="text/vcard" version="3.0"/><a:address-data-type content-type="text/vcard" version="4.0"/>`,
{Space: cardNS, Local: "supported-collation-set"}: `<a:supported-collation>i;unicode-casemap</a:supported-collation><a:supported-collation>i;octet</a:supported-collation>`,
{Space: davNS, Local: "supported-report-set"}: `<d:supported-report><d:report><a:addressbook-query/></d:report></d:supported-report><d:supported-report><d:report><a:addressbook-multiget/></d:report></d:supported-report><d:supported-report><d:report><d:sync-collection/></d:report></d:supported-report>`,
}}
}
func (s *Server) handleContactDAV(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
r = r.WithContext(ctx)
w.Header().Set("Cache-Control", "private, no-store")
domain := s.domainUUIDForRequest(r)
if !s.systemExtensionEnabled(domain, "organizer.contacts") {
http.NotFound(w, r)
return
}
if r.URL.Path == "/.well-known/carddav" {
w.Header().Set("Location", contactDAV)
w.WriteHeader(307)
return
}
actor, writable, _, credential, ok := s.davActor(w, r, "contacts", false)
if !ok {
return
}
// davActor authenticates the principal; storage rechecks active membership,
// ownership and the extension switch even on reads.
snapshot, err := s.store.ContactDAVSnapshot(ctx, domain, actor, "", 0)
if err != nil {
contactDAVStoreError(w, err)
return
}
principal := contactDAV + actor + "/"
book := principal + "contacts/"
p := r.URL.Path
root := p == contactDAV || p == strings.TrimSuffix(contactDAV, "/")
home := p == principal || p == strings.TrimSuffix(principal, "/")
collection := p == book || p == strings.TrimSuffix(book, "/")
name := ""
if !root && !home && !collection {
if !strings.HasPrefix(p, book) {
http.NotFound(w, r)
return
}
name = strings.TrimPrefix(p, book)
if !store.ValidContactDAVName(name) {
http.NotFound(w, r)
return
}
}
w.Header().Set("DAV", "1, addressbook-access")
w.Header().Set("X-PagesWiki-CardDAV-Profile", "private-addressbook")
allow := "OPTIONS, PROPFIND"
if collection {
allow += ", REPORT"
}
if name != "" {
allow += ", GET, HEAD"
if writable {
allow += ", PUT, DELETE"
}
}
w.Header().Set("Allow", allow)
if r.Method == "OPTIONS" {
w.WriteHeader(204)
return
}
if r.Method == "PROPFIND" {
depth := r.Header.Get("Depth")
if depth != "0" && depth != "1" {
contactDAVError(w, 403, davNS, "propfind-finite-depth")
return
}
n, e := readDAV(w, r)
if e != nil || n.XMLName.Local != "" && n.XMLName != (xml.Name{Space: davNS, Local: "propfind"}) {
w.WriteHeader(400)
return
}
var requested []davNode
if prop := n.child(davNS, "prop"); prop != nil {
requested = prop.Children
}
if name != "" {
c, e := s.store.ContactDAVResource(ctx, domain, actor, name)
if e != nil {
contactDAVStoreError(w, e)
return
}
if c.Deleted {
w.WriteHeader(404)
return
}
row := contactDAVRow(book, store.ContactDAVItem{Contact: c, Name: name})
delete(row.props, xml.Name{Space: cardNS, Local: "address-data"})
writeDAV(w, []davResponse{row}, requested)
return
}
var rows []davResponse
if collection {
rows = append(rows, contactBookRow(book, snapshot.Token, writable))
if depth == "1" {
data, e := s.store.ContactDAVInventory(ctx, domain, actor)
if e != nil {
contactDAVStoreError(w, e)
return
}
if data.More {
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
return
}
for _, c := range data.Items {
row := contactDAVRow(book, c)
delete(row.props, xml.Name{Space: cardNS, Local: "address-data"})
rows = append(rows, row)
}
rows[0] = contactBookRow(book, data.Token, writable)
}
} else {
href := principal
if root {
href = contactDAV
}
rows = append(rows, davResponse{href: href, props: map[xml.Name]string{
{Space: davNS, Local: "resourcetype"}: "<d:collection/><d:principal/>",
{Space: davNS, Local: "displayname"}: "PagesWiki Contacts",
{Space: davNS, Local: "current-user-principal"}: "<d:href>" + principal + "</d:href>",
{Space: davNS, Local: "principal-URL"}: "<d:href>" + principal + "</d:href>",
{Space: cardNS, Local: "addressbook-home-set"}: "<d:href>" + principal + "</d:href>",
{Space: davNS, Local: "current-user-privilege-set"}: davPrivileges(false),
}})
if depth == "1" {
rows = append(rows, contactBookRow(book, snapshot.Token, writable))
}
}
writeDAV(w, rows, requested)
return
}
if r.Method == "REPORT" && collection {
s.contactDAVReport(w, r, domain, actor, book)
return
}
if name == "" {
w.WriteHeader(405)
return
}
c, err := s.store.ContactDAVResource(ctx, domain, actor, name)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
contactDAVStoreError(w, err)
return
}
exists := err == nil && !c.Deleted
if r.Method == "GET" || r.Method == "HEAD" {
if !exists {
w.WriteHeader(404)
return
}
tag := store.ContactETag(c)
w.Header().Set("ETag", tag)
if contactETagMatch(r.Header.Get("If-None-Match"), tag, true) {
w.WriteHeader(304)
return
}
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
w.Header().Set("Content-Length", strconv.Itoa(len(c.VCard)))
if r.Method == "GET" {
io.WriteString(w, c.VCard)
}
return
}
if r.Method != "PUT" && r.Method != "DELETE" {
w.WriteHeader(405)
return
}
if !writable {
w.WriteHeader(403)
return
}
if r.Method == "DELETE" && !exists {
w.WriteHeader(404)
return
}
match, none := r.Header.Get("If-Match"), r.Header.Get("If-None-Match")
if match != "" && none != "" {
w.WriteHeader(400)
return
}
if match != "" && (!exists || !contactETagMatch(match, store.ContactETag(c), false)) || none != "" && exists && contactETagMatch(none, store.ContactETag(c), true) {
w.WriteHeader(412)
return
}
if exists && match == "" {
w.WriteHeader(428)
return
}
if !exists && match == "" && none != "*" {
w.WriteHeader(428)
return
}
raw := ""
if r.Method == "PUT" {
media, params, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
if e != nil || media != "text/vcard" && media != "text/x-vcard" || params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8") {
contactDAVError(w, 415, cardNS, "supported-address-data")
return
}
data, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
if e != nil {
w.WriteHeader(413)
return
}
raw = string(data)
if values := store.ContactPropertyValues(store.Contact{VCard: raw}, "UID"); len(values) != 1 || values[0] == "" {
contactDAVError(w, 403, cardNS, "valid-address-data")
return
}
if v := params["version"]; v != "" {
values := store.ContactPropertyValues(store.Contact{VCard: raw}, "VERSION")
if len(values) != 1 || values[0] != v {
contactDAVError(w, 415, cardNS, "supported-address-data")
return
}
}
}
saved, e := s.store.SaveContactDAV(ctx, domain, actor, credential, name, raw, c.Version, r.Method == "DELETE")
if e != nil {
contactDAVStoreError(w, e)
return
}
if r.Method == "DELETE" {
w.WriteHeader(204)
return
}
// RFC 6352: a transformed PUT representation must be fetched again by client.
if saved.VCard == raw {
w.Header().Set("ETag", store.ContactETag(saved))
}
if exists {
w.WriteHeader(204)
} else {
w.Header().Set("Location", book+name)
w.WriteHeader(201)
}
}
func contactETagMatch(value, tag string, weak bool) bool {
for _, v := range strings.Split(value, ",") {
v = strings.TrimSpace(v)
if weak {
v = strings.TrimPrefix(v, "W/")
}
if v == "*" || v == tag {
return true
}
}
return false
}
func (s *Server) contactDAVReport(w http.ResponseWriter, r *http.Request, domain, actor, book string) {
if depth := r.Header.Get("Depth"); depth != "" && depth != "0" && depth != "1" {
w.WriteHeader(400)
return
}
n, err := readDAV(w, r)
if err != nil {
w.WriteHeader(400)
return
}
prop := n.child(davNS, "prop")
if prop == nil || len(prop.Children) == 0 {
w.WriteHeader(400)
return
}
for _, p := range prop.Children {
if p.XMLName == (xml.Name{Space: cardNS, Local: "address-data"}) && (len(p.Children) > 0 || p.attr("content-type") != "" && p.attr("content-type") != "text/vcard" || p.attr("version") != "" && p.attr("version") != "3.0" && p.attr("version") != "4.0") {
contactDAVError(w, 403, cardNS, "supported-address-data")
return
}
}
requested := prop.Children
rows := []davResponse{}
if n.XMLName == (xml.Name{Space: davNS, Local: "sync-collection"}) {
level := n.child(davNS, "sync-level")
token := n.child(davNS, "sync-token")
if level == nil || level.Text != "1" || token == nil {
w.WriteHeader(400)
return
}
limit := 200
if l := n.child(davNS, "limit"); l != nil {
num := l.child(davNS, "nresults")
if num == nil {
w.WriteHeader(400)
return
}
v, e := strconv.Atoi(num.Text)
if e != nil || v < 1 {
w.WriteHeader(400)
return
}
if v < limit {
limit = v
}
}
data, e := s.store.ContactDAVSnapshot(r.Context(), domain, actor, token.Text, limit)
if e != nil {
contactDAVStoreError(w, e)
return
}
for _, c := range data.Items {
rows = append(rows, contactDAVRow(book, c))
}
if data.More {
rows = append(rows, davResponse{href: book, status: 507, errorXML: "<d:number-of-matches-within-limits/>"})
}
writeContactDAV(w, rows, requested, data.Token)
return
}
if n.XMLName == (xml.Name{Space: cardNS, Local: "addressbook-multiget"}) {
count := 0
for _, h := range n.Children {
if h.XMLName != (xml.Name{Space: davNS, Local: "href"}) {
continue
}
count++
if count > 100 {
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
return
}
u, e := url.Parse(h.Text)
if e != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Host != "" && (!strings.EqualFold(u.Host, r.Host) || u.Scheme != "https" && u.Scheme != "http") || !strings.HasPrefix(u.Path, book) || !store.ValidContactDAVName(strings.TrimPrefix(u.Path, book)) {
w.WriteHeader(400)
return
}
name := strings.TrimPrefix(u.Path, book)
c, e := s.store.ContactDAVResource(r.Context(), domain, actor, name)
if errors.Is(e, sql.ErrNoRows) {
rows = append(rows, davResponse{href: book + name, status: 404})
continue
}
if e != nil {
contactDAVStoreError(w, e)
return
}
rows = append(rows, contactDAVRow(book, store.ContactDAVItem{Contact: c, Name: name}))
}
if count == 0 {
w.WriteHeader(400)
return
}
writeContactDAV(w, rows, requested)
return
}
if n.XMLName != (xml.Name{Space: cardNS, Local: "addressbook-query"}) {
contactDAVError(w, 403, davNS, "supported-report")
return
}
filter := n.child(cardNS, "filter")
if filter != nil && !validContactFilter(*filter) {
contactDAVError(w, 403, cardNS, "supported-filter")
return
}
// A bounded full scan is explicit; never return a truncated 207 as a complete
// address book, which would make clients infer deletions. Sync is paginated.
data, e := s.store.ContactDAVSnapshot(r.Context(), domain, actor, "", 200)
if e != nil {
contactDAVStoreError(w, e)
return
}
if data.More {
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
return
}
limit := 200
if l := n.child(cardNS, "limit"); l != nil {
num := l.child(cardNS, "nresults")
if num == nil {
w.WriteHeader(400)
return
}
v, e := strconv.Atoi(num.Text)
if e != nil || v < 1 {
w.WriteHeader(400)
return
}
if v < limit {
limit = v
}
}
for _, c := range data.Items {
if filter == nil || matchContactFilter(c.Contact, *filter) {
rows = append(rows, contactDAVRow(book, c))
}
}
if len(rows) > limit {
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
return
}
writeContactDAV(w, rows, requested)
}
func writeContactDAV(w http.ResponseWriter, rows []davResponse, requested []davNode, token ...string) {
for _, p := range requested {
if p.XMLName == (xml.Name{Space: cardNS, Local: "address-data"}) && p.attr("version") != "" {
for _, row := range rows {
if v, ok := row.props[xml.Name{Space: cardNS, Local: "address-data"}]; ok && !strings.HasPrefix(v, xmlText("BEGIN:VCARD\r\nVERSION:"+p.attr("version")+"\r\n")) {
contactDAVError(w, 403, cardNS, "supported-address-data")
return
}
}
}
}
writeDAV(w, rows, requested, token...)
}
func validContactFilter(n davNode) bool {
if n.attr("test") != "" && n.attr("test") != "anyof" && n.attr("test") != "allof" {
return false
}
for _, p := range n.Children {
if p.XMLName != (xml.Name{Space: cardNS, Local: "prop-filter"}) || p.attr("name") == "" || p.attr("test") != "" && p.attr("test") != "anyof" && p.attr("test") != "allof" {
return false
}
for _, c := range p.attr("name") {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
return false
}
}
for _, m := range p.Children {
switch m.XMLName {
case xml.Name{Space: cardNS, Local: "is-not-defined"}:
if len(p.Children) != 1 {
return false
}
case xml.Name{Space: cardNS, Local: "text-match"}:
if m.attr("collation") != "" && m.attr("collation") != "i;unicode-casemap" && m.attr("collation") != "i;octet" {
return false
}
if m.attr("match-type") != "" && m.attr("match-type") != "contains" && m.attr("match-type") != "equals" && m.attr("match-type") != "starts-with" && m.attr("match-type") != "ends-with" {
return false
}
if m.attr("negate-condition") != "" && m.attr("negate-condition") != "yes" && m.attr("negate-condition") != "no" {
return false
}
default:
return false
}
if len(m.Children) > 0 {
return false
}
}
}
return true
}
func matchContactFilter(c store.Contact, n davNode) bool {
if len(n.Children) == 0 {
return true
}
all := n.attr("test") == "allof"
result := all
for _, p := range n.Children {
values := store.ContactPropertyValues(c, p.attr("name"))
match := len(values) > 0
if len(p.Children) > 0 {
and := p.attr("test") == "allof"
match = and
for _, m := range p.Children {
hit := false
if m.XMLName.Local == "is-not-defined" {
hit = len(values) == 0
} else {
for _, v := range values {
query := m.Text
if m.attr("collation") != "i;octet" {
v = norm.NFKD.String(strings.Map(unicode.ToTitle, v))
query = norm.NFKD.String(strings.Map(unicode.ToTitle, query))
}
switch m.attr("match-type") {
case "equals":
hit = v == query
case "starts-with":
hit = strings.HasPrefix(v, query)
case "ends-with":
hit = strings.HasSuffix(v, query)
default:
hit = strings.Contains(v, query)
}
if hit {
break
}
}
if m.attr("negate-condition") == "yes" {
hit = !hit && len(values) > 0
}
}
if and {
match = match && hit
} else {
match = match || hit
}
}
}
if all {
result = result && match
} else {
result = result || match
}
}
return result
}