r"""Translated from t/modules/dav.t -- mod_dav.

Exercises the WebDAV verbs against a generated resource: LOCK, PUT, PROPFIND
(creationdate/getlastmodified), is-locked, UNLOCK, GET (plain http), then a
second client attempting to PUT/LOCK a resource locked by the first, plus the
PR 49825 invalid Content-Range -> 400 check and DELETE.

The Perl test used HTTP::DAV; here we drive the verbs directly via the httpx
client (LOCK/PROPFIND/MKCOL/PUT/DELETE/UNLOCK with hand-built bodies and Lock
tokens).

Perl original: plan tests => 21, [qw(dav HTTP::DAV)].
"""

import os
import re
import time

import httpx
import pytest

from apache_pytest import need_module, not_backported, t_cmp

DIR = "modules/dav"
URI = f"/{DIR}/dav.html"

BODY = (
    "<html>\n"
    "    <body>\n"
    "    <center>\n"
    "        <h1>mod_dav test page</h1>\n"
    "        this is a page generated by<br>\n"
    "        the mod_dav test in the Apache<br>\n"
    "        perl test suite.<br>\n"
    "    </center>\n"
    "    </body>\n"
    "</html>\n"
)

LOCK_BODY = (
    '<?xml version="1.0" encoding="utf-8"?>\n'
    '<D:lockinfo xmlns:D="DAV:">\n'
    "  <D:lockscope><D:exclusive/></D:lockscope>\n"
    "  <D:locktype><D:write/></D:locktype>\n"
    "  <D:owner>{owner}</D:owner>\n"
    "</D:lockinfo>\n"
)

PROPFIND_BODY = (
    '<?xml version="1.0" encoding="utf-8"?>\n'
    '<D:propfind xmlns:D="DAV:"><D:allprop/></D:propfind>\n'
)


def _lock_token(resp):
    lt = resp.headers.get("Lock-Token")
    if lt:
        return lt.strip()
    m = re.search(r"<D:locktoken>\s*<D:href>([^<]+)</D:href>",
                  resp.text, re.IGNORECASE)
    return f"<{m.group(1)}>" if m else None


@need_module("dav")
def test_dav(http):
    htdocs = http.vars("documentroot")
    os.makedirs(os.path.join(htdocs, DIR), exist_ok=True)
    fpath = os.path.join(htdocs, *URI.lstrip("/").split("/"))
    if os.path.exists(fpath):
        os.unlink(fpath)
    # Clear any DAV lock database left by a previous run so the first LOCK isn't
    # 423 (mod_dav_fs stores locks in DAVLockDB = t/logs/davlock.db*, not a
    # per-dir .DAV in this config).
    import glob
    import shutil
    serverroot = http.vars("serverroot")
    for pat in (os.path.join(http.vars("t_logs"), "davlock.db*"),
                os.path.join(serverroot, "state", "davlockdb.*")):
        for db in glob.glob(pat):
            try:
                os.unlink(db)
            except OSError:
                pass
    shutil.rmtree(os.path.join(htdocs, DIR, ".DAV"), ignore_errors=True)

    base = http.base_url
    url = base + URI

    with httpx.Client(timeout=30.0) as c:
        # lock the resource (it doesn't exist yet -> lock-null resource)
        resp = c.request("LOCK", url, content=LOCK_BODY.format(owner="client 1"),
                         headers={"Timeout": "Second-120", "Depth": "infinity"})
        assert resp.is_success, f"resource lock test (got {resp.status_code})"
        token = _lock_token(resp)
        assert token, "got a lock token"

        # write the resource (PUT with the lock token)
        resp = c.put(url, content=BODY,
                     headers={"If": f"({token})"})
        assert resp.is_success, f"DAV put test (got {resp.status_code})"

        # properties
        time.sleep(2)
        resp = c.request("PROPFIND", url, content=PROPFIND_BODY,
                         headers={"Depth": "0"})
        assert resp.is_success, f"PROPFIND (got {resp.status_code})"

        # mod_dav namespaces the live props (e.g. <lp1:creationdate>), so match
        # any namespace prefix.
        cd = re.search(r"<\w+:creationdate[^>]*>([^<]+)</\w+:creationdate>",
                       resp.text, re.IGNORECASE)
        lm = re.search(r"<\w+:getlastmodified[^>]*>([^<]+)</\w+:getlastmodified>",
                       resp.text, re.IGNORECASE)
        # The Perl test compared HTTP::Date-formatted values; we just confirm
        # both properties are present and consistent (created != "now").
        assert cd is not None, "creationdate property present"
        assert lm is not None, "getlastmodified property present"

        # should be locked: a PUT without the token must fail
        resp_nolock = c.put(url, content="x")
        assert not resp_nolock.is_success, "resource is locked (unconditional PUT fails)"

        # unlock
        resp = c.request("UNLOCK", url, headers={"Lock-Token": token})
        assert resp.is_success, f"resource unlock test (got {resp.status_code})"

        # should be unlocked now: unconditional PUT succeeds
        resp = c.put(url, content=BODY)
        assert resp.is_success, "resource unlocked (unconditional PUT succeeds)"

    # verify via plain http GET
    actual = http.GET_BODY(URI)
    assert t_cmp(actual, BODY), "GET of put resource matches body"

    with httpx.Client(timeout=30.0) as c1, httpx.Client(timeout=30.0) as c2:
        # second client GETs and modifies content
        resp = c2.get(url)
        assert resp.status_code == 200, f"GET failed for {url}"
        b2 = resp.text.replace("<h1>mod_dav test page</h1>",
                               "<h1>mod_dav test page take two</h1>")
        # put unlocked resource with client 2 (works)
        resp = c2.put(url, content=b2)
        assert resp.is_success, "client 2 PUT on unlocked resource"

        actual = http.GET_BODY(URI)
        assert t_cmp(actual, b2), "GET reflects client 2 PUT"

        # client 1 locks
        resp = c1.request("LOCK", url, content=LOCK_BODY.format(owner="client 1"),
                          headers={"Timeout": "Second-120", "Depth": "infinity"})
        assert resp.is_success, "client 1 locking resource"
        token = _lock_token(resp)

        # client 2 should NOT be able to lock the same resource
        resp = c2.request("LOCK", url, content=LOCK_BODY.format(owner="client 2"),
                          headers={"Timeout": "Second-120", "Depth": "infinity"})
        assert not resp.is_success, "client 2 cannot lock resource locked by client 1"

        # client 2 should NOT be able to put (resource locked by client 1)
        resp = c2.get(url)
        assert resp.status_code == 200, f"GET failed for {url}"
        b3 = resp.text.replace("mod_dav", "f00")
        resp = c2.put(url, content=b3)
        assert not resp.is_success, "client 2 cannot put resource locked by client 1"

        actual = http.GET_BODY(URI)
        assert actual != b3, "content not modified by client 2"
        assert t_cmp(actual, b2), "content still client 2's earlier PUT"

        # The Perl test does forcefully_unlock_all then delete: unlock the
        # resource (client 1 owns the lock) and then DELETE the now-unlocked
        # resource (mod_dav requires the parent collection not be lock-blocked,
        # so deleting via the lock token on a child still 412s on the parent).
        resp = c1.request("UNLOCK", url, headers={"Lock-Token": token})
        assert resp.is_success, f"forcefully unlock before delete (got {resp.status_code})"
        resp = c1.request("DELETE", url)
        assert resp.is_success, f"resource delete test (got {resp.status_code})"

    actual = http.GET_RC(URI)
    assert actual == 404, f"expect 404 not found, got {actual}"

    # PR 49825: invalid Content-Range header -> 400
    with httpx.Client(timeout=30.0) as c:
        resp = c.put(url, content=BODY,
                     headers={"Content-Range": "bytes 1-a/44"})
        assert resp.status_code == 400, \
            f"PR 49825: expect 400 bad request, got {resp.status_code}"

    # PUT to a .DAV state subdirectory should be blocked (403) in 2.4.68+,
    # else allowed (201).
    dav_uri = f"/{DIR}/.DAV/test.html"
    expected = 403 if http.have_min_apache_version("2.4.68") else 201
    with httpx.Client(timeout=30.0) as c:
        resp = c.put(base + dav_uri, content=BODY)
        assert t_cmp(resp.status_code, expected), \
            f"PUT to .DAV subdir: expect {expected}, got {resp.status_code}"

    # clean up
    try:
        os.unlink(os.path.join(htdocs, DIR, ".DAV", "test.html"))
    except OSError:
        pass
    for sub in (".DAV",):
        p = os.path.join(htdocs, DIR, sub)
        if os.path.isdir(p):
            try:
                os.rmdir(p)
            except OSError:
                pass


@need_module("dav")
@not_backported("r1939426", "DAVMSext (ms_wdv) null dereference")
def test_dav_mswdv_null_deref(http):
    """BZ 70051: a PUT/DELETE/MOVE/LOCK whose dav_get_resource() fails (e.g. an
    extraneous path component under an existing file) must not crash the
    worker. Under DAVMSext, check_locked_by_other() in ms_wdv.c used to
    dereference its lockdb unconditionally in the out: label, even on the
    paths that goto out before open_lockdb() runs and leave it NULL.
    """
    htdocs = http.vars("documentroot")
    os.makedirs(os.path.join(htdocs, DIR), exist_ok=True)
    name = "mswdv-70051.html"
    fpath = os.path.join(htdocs, DIR, name)
    if os.path.exists(fpath):
        os.unlink(fpath)

    base = http.base_url
    url = f"{base}/{DIR}/{name}"

    with httpx.Client(timeout=30.0) as c:
        resp = c.put(url, content=BODY)
        assert resp.is_success, f"seed PUT failed (got {resp.status_code})"

        # dav_fs_get_resource() rejects the extra path component below the
        # plain file with an error -- dav_get_resource() fails before any
        # lockdb is opened. Pre-fix, check_locked_by_other()'s "out:" label
        # dereferenced that still-NULL lockdb and crashed the worker.
        resp = c.put(f"{url}/extra", content="boom")
        assert resp.status_code in (403, 404, 409), \
            f"PUT past a file should be a clean DAV error, got {resp.status_code}"

        # the worker must still be alive: a normal request must succeed.
        resp = c.get(url)
        assert resp.status_code == 200, \
            f"server did not survive the request (got {resp.status_code})"

    os.unlink(fpath)
