package server import ( "bytes" "context" "encoding/xml" "fmt" "io" "net/http" "net/url" "strings" "time" "pageswiki/internal/calendar" ) const davNS = "DAV:" const calNS = "urn:ietf:params:xml:ns:caldav" type davNode struct { XMLName xml.Name Attrs []xml.Attr `xml:",any,attr"` Text string `xml:",chardata"` Children []davNode `xml:",any"` } func (n davNode) child(ns, name string) *davNode { for i := range n.Children { if n.Children[i].XMLName.Space == ns && n.Children[i].XMLName.Local == name { return &n.Children[i] } } return nil } func (n davNode) attr(name string) string { for _, a := range n.Attrs { if a.Name.Space == "" && a.Name.Local == name { return a.Value } } return "" } func readDAV(w http.ResponseWriter, r *http.Request) (davNode, error) { b, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10)) if e != nil { return davNode{}, e } if len(bytes.TrimSpace(b)) == 0 { return davNode{}, nil } // Reject DTDs and cap nesting before recursive decoding. d := xml.NewDecoder(bytes.NewReader(b)) depth, count := 0, 0 for { t, e := d.Token() if e == io.EOF { break } if e != nil { return davNode{}, e } switch t.(type) { case xml.Directive: return davNode{}, fmt.Errorf("DTD not allowed") case xml.StartElement: depth++ count++ if depth > 12 || count > 1000 { return davNode{}, fmt.Errorf("XML complexity limit") } case xml.EndElement: depth-- } } var n davNode e = xml.Unmarshal(b, &n) return n, e } func xmlText(s string) string { var b bytes.Buffer; xml.EscapeText(&b, []byte(s)); return b.String() } type davResponse struct { href string props map[xml.Name]string status int errorXML string } func davProperty(ns, key, value string) (xml.Name, string) { return xml.Name{Space: ns, Local: key}, value } func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode, syncToken ...string) { var b strings.Builder b.WriteString(``) for _, row := range rows { b.WriteString("" + xmlText(row.href) + "") if row.status != 0 { fmt.Fprintf(&b, "HTTP/1.1 %d %s", row.status, http.StatusText(row.status)) if row.errorXML != "" { b.WriteString("" + row.errorXML + "") } } else { present, missing := strings.Builder{}, strings.Builder{} props := requested if len(props) == 0 { for n := range row.props { props = append(props, davNode{XMLName: n}) } } for _, prop := range props { name := prop.XMLName value, ok := row.props[name] tag := "p:" + name.Local piece := "<" + tag + " xmlns:p=\"" + xmlText(name.Space) + "\">" + value + "" if ok { present.WriteString(piece) } else { missing.WriteString(piece) } } if present.Len() > 0 { b.WriteString("" + present.String() + "HTTP/1.1 200 OK") } if missing.Len() > 0 { b.WriteString("" + missing.String() + "HTTP/1.1 404 Not Found") } } b.WriteString("") } if len(syncToken) == 1 { b.WriteString("" + xmlText(syncToken[0]) + "") } b.WriteString("") w.Header().Set("Content-Type", "application/xml; charset=utf-8") w.WriteHeader(207) io.WriteString(w, b.String()) } func eventDAVRow(c calendar.Calendar, e calendar.Event) davResponse { return davResponse{href: calendarDAV + c.ID + "/" + calendar.DAVFilename(c, e.UID), props: map[xml.Name]string{{Space: davNS, Local: "getetag"}: xmlText(e.ETag), {Space: davNS, Local: "getcontenttype"}: "text/calendar; charset=utf-8", {Space: davNS, Local: "resourcetype"}: "", {Space: calNS, Local: "calendar-data"}: xmlText(e.Data)}} } func calendarDAVRow(c calendar.Calendar) davResponse { return davResponse{href: calendarDAV + c.ID + "/", props: map[xml.Name]string{ {Space: davNS, Local: "displayname"}: xmlText(c.PrettyName), {Space: davNS, Local: "resourcetype"}: "", {Space: calNS, Local: "supported-calendar-component-set"}: ``, {Space: calNS, Local: "supported-calendar-data"}: ``, {Space: davNS, Local: "supported-report-set"}: ``, }} } func (s *Server) handleCalendarDAV(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") if strings.TrimSuffix(r.URL.Path, "/") == strings.TrimSuffix(calendarDAV, "/") { s.handleDAVHome(w, r) return } if r.Method == "MKCALENDAR" { s.handleTaskMKCalendar(w, r) return } segment := strings.Split(strings.TrimPrefix(r.URL.Path, calendarDAV), "/")[0] if found, err := s.store.IsTaskDAVCollection(r.Context(), s.domainUUIDForRequest(r), segment); err != nil { taskError(w, err) return } else if found { s.handleTaskDAVAt(w, r, segment) return } repo, ok := s.calendarReady(w, r) if !ok { return } domain := s.domainUUIDForRequest(r) actor, active, _, credential, authenticated := s.davActor(w, r, "calendar", true) if !authenticated { return } parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, calendarDAV), "/"), "/") root := len(parts) == 1 && parts[0] == "" s.setDAVCapabilities(w, r, actor, credential) w.Header().Set("Allow", "OPTIONS, PROPFIND, REPORT, GET, HEAD, PUT, DELETE") if r.Method == "OPTIONS" { w.WriteHeader(204) return } var c calendar.Calendar if !root { var e error c, e = repo.Get(domain, parts[0], actor) if e != nil { calendarError(w, e) return } } if len(parts) > 2 { http.NotFound(w, r) return } if r.Method == "PROPFIND" { depth := r.Header.Get("Depth") if depth != "0" && depth != "1" { http.Error(w, "Depth 0 or 1 required", 403) return } n, e := readDAV(w, r) if e != nil { http.Error(w, "invalid XML", 400) return } if n.XMLName.Local != "" && (n.XMLName.Local != "propfind" || n.XMLName.Space != davNS) { http.Error(w, "invalid PROPFIND", 400) return } var req []davNode if p := n.child(davNS, "prop"); p != nil { req = p.Children } rows := []davResponse{} if root { rows = append(rows, davResponse{href: calendarDAV, props: map[xml.Name]string{{Space: davNS, Local: "resourcetype"}: "", {Space: davNS, Local: "displayname"}: "PagesWiki calendars", {Space: calNS, Local: "calendar-home-set"}: "" + calendarDAV + ""}}) if depth == "1" { cs, e := repo.List(domain, actor) if e != nil { calendarError(w, e) return } for _, v := range cs { rows = append(rows, calendarDAVRow(v)) } } } else if len(parts) == 1 { row := calendarDAVRow(c) row.props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] = davPrivileges(active && c.CanWrite(actor)) rows = append(rows, row) if depth == "1" { var items []calendar.Event withData := false for _, p := range req { if !taskDAVFullProperty(p) { http.Error(w, "unsupported property projection", 403) return } if p.XMLName == (xml.Name{Space: calNS, Local: "calendar-data"}) { withData = true } } c, items, e = repo.DAVSnapshot(r.Context(), domain, c.ID, actor, withData) if e != nil { calendarError(w, e) return } for _, item := range items { rows = append(rows, eventDAVRow(c, item)) } } } else { uid, e := calendar.DAVUID(c, parts[1]) if e != nil { calendarError(w, e) return } v, e := repo.Event(r.Context(), domain, c.ID, actor, uid) if e != nil { calendarError(w, e) return } row := eventDAVRow(c, v) row.href = r.URL.Path rows = append(rows, row) } writeDAV(w, rows, req) return } if root { w.WriteHeader(405) return } if r.Method == "REPORT" && len(parts) == 1 { n, e := readDAV(w, r) if e != nil { http.Error(w, "invalid XML", 400) return } if n.XMLName.Space != calNS { http.Error(w, "unsupported report", 405) return } seen := map[string]int{} for _, child := range n.Children { key := child.XMLName.Space + "|" + child.XMLName.Local seen[key]++ allowed := child.XMLName.Space == davNS && child.XMLName.Local == "prop" || n.XMLName.Local == "calendar-query" && child.XMLName.Space == calNS && child.XMLName.Local == "filter" || n.XMLName.Local == "calendar-multiget" && child.XMLName.Space == davNS && child.XMLName.Local == "href" if !allowed || child.XMLName.Local != "href" && seen[key] > 1 { http.Error(w, "unsupported report element", 403) return } } p := n.child(davNS, "prop") if p == nil || len(p.Children) == 0 { http.Error(w, "explicit properties required", 400) return } for _, prop := range p.Children { if !taskDAVFullProperty(prop) { http.Error(w, "calendar-data projection/expansion unsupported", 403) return } } rows := []davResponse{} switch n.XMLName.Local { case "calendar-query": filter := n.child(calNS, "filter") if filter == nil || len(filter.Children) != 1 { http.Error(w, "time-range filter required", 403) return } outer := filter.Children[0] if outer.XMLName.Space != calNS || outer.XMLName.Local != "comp-filter" || outer.attr("name") != "VCALENDAR" || len(outer.Children) > 1 || taskDAVAttrCount(outer) != 1 || taskDAVAttrCount(*filter) != 0 { http.Error(w, "unsupported filter", 403) return } inner := davNode{XMLName: xml.Name{Space: calNS, Local: "comp-filter"}} if len(outer.Children) == 1 { inner = outer.Children[0] } if len(outer.Children) == 1 && (inner.XMLName.Space != calNS || inner.XMLName.Local != "comp-filter" || inner.attr("name") != "VEVENT" || len(inner.Children) > 1 || taskDAVAttrCount(inner) != 1) { http.Error(w, "unsupported filter", 403) return } if len(inner.Children) == 0 { withData := false for _, prop := range p.Children { if prop.XMLName == (xml.Name{Space: calNS, Local: "calendar-data"}) { withData = true } } var items []calendar.Event c, items, e = repo.DAVSnapshot(r.Context(), domain, c.ID, actor, withData) if e != nil { calendarError(w, e) return } for _, item := range items { rows = append(rows, eventDAVRow(c, item)) } break } tr := inner.Children[0] if tr.XMLName.Space != calNS || tr.XMLName.Local != "time-range" || len(tr.Children) != 0 || taskDAVAttrCount(tr) != 2 { http.Error(w, "unsupported filter", 403) return } start, e1 := time.Parse("20060102T150405Z", tr.attr("start")) end, e2 := time.Parse("20060102T150405Z", tr.attr("end")) if e1 != nil || e2 != nil { http.Error(w, "UTC start and end required", 400) return } query := repo.QueryETags for _, prop := range p.Children { if prop.XMLName.Space == calNS && prop.XMLName.Local == "calendar-data" { query = repo.Query } } events, e := query(r.Context(), domain, c.ID, actor, start, end) if e != nil { calendarError(w, e) return } for _, event := range events { rows = append(rows, eventDAVRow(c, event)) } case "calendar-multiget": count := 0 for _, node := range n.Children { if node.XMLName.Space != davNS || node.XMLName.Local != "href" { continue } count++ if count > 200 { http.Error(w, "too many hrefs", 413) return } u, e := url.Parse(strings.TrimSpace(node.Text)) prefix := calendarDAV + c.ID + "/" if e != nil || u.IsAbs() || u.RawQuery != "" || u.Fragment != "" || !strings.HasPrefix(u.Path, prefix) { http.Error(w, "foreign href", 400) return } uid, e := calendar.DAVUID(c, strings.TrimPrefix(u.Path, prefix)) if e != nil { http.Error(w, "invalid href", 400) return } v, e := repo.Event(r.Context(), domain, c.ID, actor, uid) if e == calendar.ErrMissing { rows = append(rows, davResponse{href: u.Path, status: 404}) continue } if e != nil { calendarError(w, e) return } row := eventDAVRow(c, v) row.href = u.Path rows = append(rows, row) } default: http.Error(w, "unsupported report", 403) return } writeDAV(w, rows, p.Children) return } if len(parts) != 2 { w.WriteHeader(405) return } uid, e := calendar.DAVUID(c, parts[1]) if e != nil && r.Method != "PUT" { calendarError(w, e) return } switch r.Method { case "GET", "HEAD": v, e := repo.Event(r.Context(), domain, c.ID, actor, uid) if e != nil { calendarError(w, e) return } w.Header().Set("ETag", v.ETag) w.Header().Set("Content-Type", "text/calendar; charset=utf-8") if r.Header.Get("If-None-Match") == v.ETag { w.WriteHeader(304) return } if r.Method == "GET" { io.WriteString(w, v.Data) } case "PUT", "DELETE": if !active { calendarError(w, calendar.ErrForbidden) return } match := r.Header.Get("If-Match") if match == "" && r.Header.Get("If-None-Match") == "*" && r.Method == "PUT" { match = "*" } if match == "" && r.Method != "PUT" { http.Error(w, "If-Match or If-None-Match: * required", 428) return } var event *calendar.Event unchangedRepresentation := false if r.Method == "PUT" { if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "text/calendar") { http.Error(w, "text/calendar required", 415) return } data, e := io.ReadAll(http.MaxBytesReader(w, r.Body, calendar.MaxResource)) if e != nil { http.Error(w, "resource too large", 413) return } v, e := calendar.Parse(string(data)) if e != nil { calendarError(w, e) return } event = &v unchangedRepresentation = string(data) == v.Data } var authorize func() error if credential != "" { authorize = func() error { return s.store.CheckDAVCredential(r.Context(), domain, actor, credential, true, "calendar") } } v, created, e := repo.ChangeDAV(r.Context(), domain, c.ID, actor, parts[1], match, event, authorize) if e != nil { calendarError(w, e) return } if event != nil && unchangedRepresentation { w.Header().Set("ETag", v.ETag) } if created { w.Header().Set("Location", r.URL.Path) w.WriteHeader(201) } else { w.WriteHeader(204) } default: w.WriteHeader(405) } }