util.c 77 KB
Newer Older
powelld's avatar
powelld committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
    ** (in fact, it certainly will not: a dummy_header only occurs for the
    **  UNLOCK method, the parent is checked only for locknull resources,
    **  and the parent certainly does not have the (locknull's) locktoken)
    */
    if (lock_list == NULL && if_header->dummy_header) {
        if (flags & DAV_VALIDATE_IS_PARENT)
            return NULL;
        return dav_new_error(p, HTTP_BAD_REQUEST, 0, 0,
                             "The locktoken specified in the \"Lock-Token:\" "
                             "header is invalid because this resource has no "
                             "outstanding locks.");
    }

    /*
    ** Prepare the input URI. We want the URI to never have a trailing slash.
    **
    ** When URIs are placed into the dav_if_header structure, they are
    ** guaranteed to never have a trailing slash. If the URIs are equivalent,
    ** then it doesn't matter if they both lack a trailing slash -- they're
    ** still equivalent.
    **
    ** Note: we could also ensure that a trailing slash is present on both
    ** URIs, but the majority of URIs provided to us via a resource walk
    ** will not contain that trailing slash.
    */
    uri = resource->uri;
    uri_len = strlen(uri);
    if (uri[uri_len - 1] == '/') {
        dav_set_bufsize(p, pbuf, uri_len);
        memcpy(pbuf->buf, uri, uri_len);
        pbuf->buf[--uri_len] = '\0';
        uri = pbuf->buf;
    }

    /* get the resource's etag; we may need it during the checks */
    etag = (*resource->hooks->getetag)(resource);

    /* how many state_lists apply to this URI? */
    num_that_apply = 0;

    /* If there are if-headers, fail if this resource
     * does not match at least one state_list.
     */
    for (ifhdr_scan = if_header;
         ifhdr_scan != NULL;
         ifhdr_scan = ifhdr_scan->next) {

        /* DBG2("uri=<%s>  if_uri=<%s>", uri, ifhdr_scan->uri ? ifhdr_scan->uri : "(no uri)"); */

        if (ifhdr_scan->uri != NULL
            && (uri_len != ifhdr_scan->uri_len
                || memcmp(uri, ifhdr_scan->uri, uri_len) != 0)) {
            /*
            ** A tagged-list's URI doesn't match this resource's URI.
            ** Skip to the next state_list to see if it will match.
            */
            continue;
        }

        /* this state_list applies to this resource */

        /*
        ** ### only one state_list should ever apply! a no-tag, or a tagged
        ** ### where S9.4.2 states only one can match.
        **
        ** ### revamp this code to loop thru ifhdr_scan until we find the
        ** ### matching state_list. process it. stop.
        */
        ++num_that_apply;

        /* To succeed, resource must match *all* of the states
         * specified in the state_list.
         */
        for (state_list = ifhdr_scan->state;
             state_list != NULL;
             state_list = state_list->next) {

            switch(state_list->type) {
            case dav_if_etag:
            {
                const char *given_etag, *current_etag;
                int mismatch;

                /* Do a weak entity comparison function as defined in
                 * RFC 2616 13.3.3.
                 */
                if (state_list->etag[0] == 'W' &&
                    state_list->etag[1] == '/') {
                    given_etag = state_list->etag + 2;
                }
                else {
                    given_etag = state_list->etag;
                }
                if (etag[0] == 'W' &&
                    etag[1] == '/') {
                    current_etag = etag + 2;
                }
                else {
                    current_etag = etag;
                }

                mismatch = strcmp(given_etag, current_etag);

                if (state_list->condition == DAV_IF_COND_NORMAL && mismatch) {
                    /*
                    ** The specified entity-tag does not match the
                    ** entity-tag on the resource. This state_list is
                    ** not going to match. Bust outta here.
                    */
                    reason =
                        "an entity-tag was specified, but the resource's "
                        "actual ETag does not match.";
                    goto state_list_failed;
                }
                else if (state_list->condition == DAV_IF_COND_NOT
                         && !mismatch) {
                    /*
                    ** The specified entity-tag DOES match the
                    ** entity-tag on the resource. This state_list is
                    ** not going to match. Bust outta here.
                    */
                    reason =
                        "an entity-tag was specified using the \"Not\" form, "
                        "but the resource's actual ETag matches the provided "
                        "entity-tag.";
                    goto state_list_failed;
                }
                break;
            }

            case dav_if_opaquelock:
                if (lockdb == NULL) {
                    if (state_list->condition == DAV_IF_COND_NOT) {
                        /* the locktoken is definitely not there! (success) */
                        continue;
                    }

                    /* condition == DAV_IF_COND_NORMAL */

                    /*
                    ** If no lockdb is provided, then validation fails for
                    ** this state_list (NORMAL means we were supposed to
                    ** find the token, which we obviously cannot do without
                    ** a lock database).
                    **
                    ** Go and try the next state list.
                    */
                    reason =
                        "a State-token was supplied, but a lock database "
                        "is not available for to provide the required lock.";
                    goto state_list_failed;
                }

                /* Resource validation 'fails' if:
                 *    ANY  of the lock->locktokens match
                 *         a NOT state_list->locktoken,
                 * OR
                 *    NONE of the lock->locktokens match
                 *         a NORMAL state_list->locktoken.
                 */
                num_matched = 0;
                for (lock = lock_list; lock != NULL; lock = lock->next) {

                    /*
                    DBG2("compare: rsrc=%s  ifhdr=%s",
                         (*locks_hooks->format_locktoken)(p, lock->locktoken),
                         (*locks_hooks->format_locktoken)(p, state_list->locktoken));
                    */

                    /* nothing to do if the locktokens do not match. */
                    if ((*locks_hooks->compare_locktoken)(state_list->locktoken, lock->locktoken)) {
                        continue;
                    }

                    /*
                    ** We have now matched up one of the resource's locktokens
                    ** to a locktoken in a State-token in the If: header.
                    ** Note this fact, so that we can pass the overall
                    ** requirement of seeing at least one of the resource's
                    ** locktokens.
                    */
                    seen_locktoken = 1;

                    if (state_list->condition == DAV_IF_COND_NOT) {
                        /*
                        ** This state requires that the specified locktoken
                        ** is NOT present on the resource. But we just found
                        ** it. There is no way this state-list can now
                        ** succeed, so go try another one.
                        */
                        reason =
                            "a State-token was supplied, which used a "
                            "\"Not\" condition. The State-token was found "
                            "in the locks on this resource";
                        goto state_list_failed;
                    }

                    /* condition == DAV_IF_COND_NORMAL */

                    /* Validate auth_user:  If an authenticated user created
                    ** the lock, only the same user may submit that locktoken
                    ** to manipulate a resource.
                    */
                    if (lock->auth_user &&
                        (!r->user ||
                         strcmp(lock->auth_user, r->user))) {
                        const char *errmsg;

                        errmsg = apr_pstrcat(p, "User \"",
                                            r->user,
                                            "\" submitted a locktoken created "
                                            "by user \"",
                                            lock->auth_user, "\".", NULL);
                        return dav_new_error(p, HTTP_FORBIDDEN, 0, 0, errmsg);
                    }

                    /*
                    ** We just matched a specified State-Token to one of the
                    ** resource's locktokens.
                    **
                    ** Break out of the lock scan -- we only needed to find
                    ** one match (actually, there shouldn't be any other
                    ** matches in the lock list).
                    */
                    num_matched = 1;
                    break;
                }

                if (num_matched == 0
                    && state_list->condition == DAV_IF_COND_NORMAL) {
                    /*
                    ** We had a NORMAL state, meaning that we should have
                    ** found the State-Token within the locks on this
                    ** resource. We didn't, so this state_list must fail.
                    */
                    reason =
                        "a State-token was supplied, but it was not found "
                        "in the locks on this resource.";
                    goto state_list_failed;
                }

                break;

            case dav_if_unknown:
                /* Request is predicated on some unknown state token,
                 * which must be presumed to *not* match, so fail
                 * unless this is a Not condition. */

                if (state_list->condition == DAV_IF_COND_NORMAL) {
                    reason =
                        "an unknown state token was supplied";
                    goto state_list_failed;
                }
                break;

            } /* switch */
        } /* foreach ( state_list ) */

        /*
        ** We've checked every state in this state_list and none of them
        ** have failed. Since all of them succeeded, then we have a matching
        ** state list and we may be done.
        **
        ** The next requirement is that we have seen one of the resource's
        ** locktokens (if any). If we have, then we can just exit. If we
        ** haven't, then we need to keep looking.
        */
        if (seen_locktoken) {
            /* woo hoo! */
            return NULL;
        }

        /*
        ** Haven't seen one. Let's break out of the search and just look
        ** for a matching locktoken.
        */
        break;

        /*
        ** This label is used when we detect that a state_list is not
        ** going to match this resource. We bust out and try the next
        ** state_list.
        */
      state_list_failed:
        ;

    } /* foreach ( ifhdr_scan ) */

    /*
    ** The above loop exits for one of two reasons:
    **   1) a state_list matched and seen_locktoken is false.
    **   2) all if_header structures were scanned, without (1) occurring
    */

    if (ifhdr_scan == NULL) {
        /*
        ** We finished the loop without finding any matching state lists.
        */

        /*
        ** If none of the state_lists apply to this resource, then we
        ** may have succeeded. Note that this scenario implies a
        ** tagged-list with no matching state_lists. If the If: header
        ** was a no-tag-list, then it would have applied to this resource.
        **
        ** S9.4.2 states that when no state_lists apply, then the header
        ** should be ignored.
        **
        ** If we saw one of the resource's locktokens, then we're done.
        ** If we did not see a locktoken, then we fail.
        */
        if (num_that_apply == 0) {
            if (seen_locktoken)
                return NULL;

            /*
            ** We may have aborted the scan before seeing the locktoken.
            ** Rescan the If: header to see if we can find the locktoken
            ** somewhere.
            **
            ** Note that seen_locktoken == 0 implies lock_list != NULL
            ** which implies locks_hooks != NULL.
            */
            if (dav_find_submitted_locktoken(if_header, lock_list,
                                             locks_hooks)) {
                /*
                ** We found a match! We're set... none of the If: header
                ** assertions apply (implicit success), and the If: header
                ** specified the locktoken somewhere. We're done.
                */
                return NULL;
            }

            return dav_new_error(p, HTTP_LOCKED, 0 /* error_id */, 0,
                                 "This resource is locked and the \"If:\" "
                                 "header did not specify one of the "
                                 "locktokens for this resource's lock(s).");
        }
        /* else: one or more state_lists were applicable, but failed. */

        /*
        ** If the dummy_header did not match, then they specified an
        ** incorrect token in the Lock-Token header. Forget whether the
        ** If: statement matched or not... we'll tell them about the
        ** bad Lock-Token first. That is considered a 400 (Bad Request).
        */
        if (if_header->dummy_header) {
            return dav_new_error(p, HTTP_BAD_REQUEST, 0, 0,
                                 "The locktoken specified in the "
                                 "\"Lock-Token:\" header did not specify one "
                                 "of this resource's locktoken(s).");
        }

        if (reason == NULL) {
            return dav_new_error(p, HTTP_PRECONDITION_FAILED, 0, 0,
                                 "The preconditions specified by the \"If:\" "
                                 "header did not match this resource.");
        }

        return dav_new_error(p, HTTP_PRECONDITION_FAILED, 0, 0,
                             apr_psprintf(p,
                                         "The precondition(s) specified by "
                                         "the \"If:\" header did not match "
                                         "this resource. At least one "
                                         "failure is because: %s", reason));
    }

    /* assert seen_locktoken == 0 */

    /*
    ** ifhdr_scan != NULL implies we found a matching state_list.
    **
    ** Since we're still here, it also means that we have not yet found
    ** one the resource's locktokens in the If: header.
    **
    ** Scan all the if_headers and states looking for one of this
    ** resource's locktokens. Note that we need to go back and scan them
    ** all -- we may have aborted a scan with a failure before we saw a
    ** matching token.
    **
    ** Note that seen_locktoken == 0 implies lock_list != NULL which implies
    ** locks_hooks != NULL.
    */
    if (dav_find_submitted_locktoken(if_header, lock_list, locks_hooks)) {
        /*
        ** We found a match! We're set... we have a matching state list,
        ** and the If: header specified the locktoken somewhere. We're done.
        */
        return NULL;
    }

    /*
    ** We had a matching state list, but the user agent did not specify one
    ** of this resource's locktokens. Tell them so.
    **
    ** Note that we need to special-case the message on whether a "dummy"
    ** header exists. If it exists, yet we didn't see a needed locktoken,
    ** then that implies the dummy header (Lock-Token header) did NOT
    ** specify one of this resource's locktokens. (this implies something
    ** in the real If: header matched)
    **
    ** We want to note the 400 (Bad Request) in favor of a 423 (Locked).
    */
    if (if_header->dummy_header) {
        return dav_new_error(p, HTTP_BAD_REQUEST, 0, 0,
                             "The locktoken specified in the "
                             "\"Lock-Token:\" header did not specify one "
                             "of this resource's locktoken(s).");
    }

    return dav_new_error(p, HTTP_LOCKED, 1 /* error_id */, 0,
                         "This resource is locked and the \"If:\" header "
                         "did not specify one of the "
                         "locktokens for this resource's lock(s).");
}

/* dav_validate_walker:  Walker callback function to validate resource state */
static dav_error * dav_validate_walker(dav_walk_resource *wres, int calltype)
{
    dav_walker_ctx *ctx = wres->walk_ctx;
    dav_error *err;

    if ((err = dav_validate_resource_state(ctx->w.pool, wres->resource,
                                           ctx->w.lockdb,
                                           ctx->if_header, ctx->flags,
                                           &ctx->work_buf, ctx->r)) == NULL) {
        /* There was no error, so just bug out. */
        return NULL;
    }

    /*
    ** If we have a serious server error, or if the request itself failed,
    ** then just return error (not a multistatus).
    */
    if (ap_is_HTTP_SERVER_ERROR(err->status)
        || (*wres->resource->hooks->is_same_resource)(wres->resource,
                                                      ctx->w.root)) {
        /* ### maybe push a higher-level description? */
        return err;
    }

    /* associate the error with the current URI */
    dav_add_response(wres, err->status, NULL);

    return NULL;
}

/* If-* header checking */
static int dav_meets_conditions(request_rec *r, int resource_state)
{
    const char *if_match, *if_none_match;
    int retVal;

    /* If-Match '*' fix. Resource existence not checked by ap_meets_conditions.
     * If-Match '*' request should succeed only if the resource exists. */
    if ((if_match = apr_table_get(r->headers_in, "If-Match")) != NULL) {
        if (if_match[0] == '*' && resource_state != DAV_RESOURCE_EXISTS)
            return HTTP_PRECONDITION_FAILED;
    }

    retVal = ap_meets_conditions(r);

    /* If-None-Match '*' fix. If-None-Match '*' request should succeed
     * if the resource does not exist. */
    if (retVal == HTTP_PRECONDITION_FAILED) {
        /* Note. If if_none_match != NULL, if_none_match is the culprit.
         * Since, in presence of If-None-Match,
         * other If-* headers are undefined. */
        if ((if_none_match =
            apr_table_get(r->headers_in, "If-None-Match")) != NULL) {
            if (if_none_match[0] == '*'
                && resource_state != DAV_RESOURCE_EXISTS) {
                return OK;
            }
        }
    }

    return retVal;
}

/*
** dav_validate_request:  Validate if-headers (and check for locks) on:
**    (1) r->filename @ depth;
**    (2) Parent of r->filename if check_parent == 1
**
** The check of parent should be done when it is necessary to verify that
** the parent collection will accept a new member (ie current resource
** state is null).
**
** Return OK on successful validation.
** On error, return appropriate HTTP_* code, and log error. If a multi-stat
** error is necessary, response will point to it, else NULL.
*/
DAV_DECLARE(dav_error *) dav_validate_request(request_rec *r,
                                              dav_resource *resource,
                                              int depth,
                                              dav_locktoken *locktoken,
                                              dav_response **response,
                                              int flags,
                                              dav_lockdb *lockdb)
{
    dav_error *err;
    int result;
    dav_if_header *if_header;
    int lock_db_opened_locally = 0;
    const dav_hooks_locks *locks_hooks = DAV_GET_HOOKS_LOCKS(r);
    const dav_hooks_repository *repos_hooks = resource->hooks;
    dav_buffer work_buf = { 0 };
    dav_response *new_response;
    int resource_state;
    const char *etag;
    int set_etag = 0;

#if DAV_DEBUG
    if (depth && response == NULL) {
        /*
        ** ### bleck. we can't return errors for other URIs unless we have
        ** ### a "response" ptr.
        */
        return dav_new_error(r->pool, HTTP_INTERNAL_SERVER_ERROR, 0, 0,
                             "DESIGN ERROR: dav_validate_request called "
                             "with depth>0, but no response ptr.");
    }
#endif

    if (response != NULL)
        *response = NULL;

    /* Set the ETag header required by dav_meets_conditions() */
    etag = apr_table_get(r->headers_out, "ETag");
    if (!etag) {
        etag = (*resource->hooks->getetag)(resource);
        if (etag && *etag) {
            apr_table_set(r->headers_out, "ETag", etag);
            set_etag = 1;
        }
    }
    /* Do the standard checks for conditional requests using
     * If-..-Since, If-Match etc */
    resource_state = dav_get_resource_state(r, resource);
    result = dav_meets_conditions(r, resource_state);
    if (set_etag) {
        /*
         * If we have set an ETag to headers out above for
         * dav_meets_conditions() revert this here as we do not want to set
         * the ETag in responses to requests with methods where this might not
         * be desired.
         */
        apr_table_unset(r->headers_out, "ETag");
    }
    if (result != OK) {
        return dav_new_error(r->pool, result, 0, 0, NULL);
    }

    /* always parse (and later process) the If: header */
    if ((err = dav_process_if_header(r, &if_header)) != NULL) {
        /* ### maybe add higher-level description */
        return err;
    }

    /* If a locktoken was specified, create a dummy if_header with which
     * to validate resources.  In the interim, figure out why DAV uses
     * locktokens in an if-header without a Lock-Token header to refresh
     * locks, but a Lock-Token header without an if-header to remove them.
     */
    if (locktoken != NULL) {
        dav_if_header *ifhdr_new;

        ifhdr_new = apr_pcalloc(r->pool, sizeof(*ifhdr_new));
        ifhdr_new->uri = resource->uri;
        ifhdr_new->uri_len = strlen(resource->uri);
        ifhdr_new->dummy_header = 1;

        ifhdr_new->state = apr_pcalloc(r->pool, sizeof(*ifhdr_new->state));
        ifhdr_new->state->type = dav_if_opaquelock;
        ifhdr_new->state->condition = DAV_IF_COND_NORMAL;
        ifhdr_new->state->locktoken = locktoken;

        ifhdr_new->next = if_header;
        if_header = ifhdr_new;
    }

    /*
    ** If necessary, open the lock database (read-only, lazily);
    ** the validation process may need to retrieve or update lock info.
    ** Otherwise, assume provided lockdb is valid and opened rw.
    */
    if (lockdb == NULL) {
        if (locks_hooks != NULL) {
            if ((err = (*locks_hooks->open_lockdb)(r, 0, 0, &lockdb)) != NULL) {
                /* ### maybe insert higher-level comment */
                return err;
            }
            lock_db_opened_locally = 1;
        }
    }

    /* (1) Validate the specified resource, at the specified depth.
     * Avoid the walk there is no if_header and we aren't planning
     * to modify this resource. */
    if (resource->exists && depth > 0 && !(!if_header && flags & DAV_VALIDATE_NO_MODIFY)) {
        dav_walker_ctx ctx = { { 0 } };
        dav_response *multi_status;

        ctx.w.walk_type = DAV_WALKTYPE_NORMAL;
        ctx.w.func = dav_validate_walker;
        ctx.w.walk_ctx = &ctx;
        ctx.w.pool = r->pool;
        ctx.w.root = resource;

        ctx.if_header = if_header;
        ctx.r = r;
        ctx.flags = flags;

        if (lockdb != NULL) {
            ctx.w.lockdb = lockdb;
            ctx.w.walk_type |= DAV_WALKTYPE_LOCKNULL;
        }

        err = (*repos_hooks->walk)(&ctx.w, DAV_INFINITY, &multi_status);
        if (err == NULL) {
            *response = multi_status;
        }
        /* else: implies a 5xx status code occurred. */
    }
    else {
        err = dav_validate_resource_state(r->pool, resource, lockdb,
                                          if_header, flags, &work_buf, r);
    }

    /* (2) Validate the parent resource if requested */
    if (err == NULL && (flags & DAV_VALIDATE_PARENT)) {
        dav_resource *parent_resource;

        err = (*repos_hooks->get_parent_resource)(resource, &parent_resource);

        if (err == NULL && parent_resource == NULL) {
            err = dav_new_error(r->pool, HTTP_FORBIDDEN, 0, 0,
                                "Cannot access parent of repository root.");
        }
        else if (err == NULL) {
            err = dav_validate_resource_state(r->pool, parent_resource, lockdb,
                                              if_header,
                                              flags | DAV_VALIDATE_IS_PARENT,
                                              &work_buf, r);

            /*
            ** This error occurred on the parent resource. This implies that
            ** we have to create a multistatus response (to report the error
            ** against a URI other than the Request-URI). "Convert" this error
            ** into a multistatus response.
            */
            if (err != NULL) {
                new_response = apr_pcalloc(r->pool, sizeof(*new_response));

                new_response->href = parent_resource->uri;
                new_response->status = err->status;
                new_response->desc =
                    "A validation error has occurred on the parent resource, "
                    "preventing the operation on the resource specified by "
                    "the Request-URI.";
                if (err->desc != NULL) {
                    new_response->desc = apr_pstrcat(r->pool,
                                                    new_response->desc,
                                                    " The error was: ",
                                                    err->desc, NULL);
                }

                /* assert: DAV_VALIDATE_PARENT implies response != NULL */
                new_response->next = *response;
                *response = new_response;

                err = NULL;
            }
        }
    }

    if (lock_db_opened_locally)
        (*locks_hooks->close_lockdb)(lockdb);

    /*
    ** If we don't have a (serious) error, and we have multistatus responses,
    ** then we need to construct an "error". This error will be the overall
    ** status returned, and the multistatus responses will go into its body.
    **
    ** For certain methods, the overall error will be a 424. The default is
    ** to construct a standard 207 response.
    */
    if (err == NULL && response != NULL && *response != NULL) {
        apr_text *propstat = NULL;

        if ((flags & DAV_VALIDATE_USE_424) != 0) {
            /* manufacture a 424 error to hold the multistatus response(s) */
            return dav_new_error(r->pool, HTTP_FAILED_DEPENDENCY, 0, 0,
                                 "An error occurred on another resource, "
                                 "preventing the requested operation on "
                                 "this resource.");
        }

        /*
        ** Whatever caused the error, the Request-URI should have a 424
        ** associated with it since we cannot complete the method.
        **
        ** For a LOCK operation, insert an empty DAV:lockdiscovery property.
        ** For other methods, return a simple 424.
        */
        if ((flags & DAV_VALIDATE_ADD_LD) != 0) {
            propstat = apr_pcalloc(r->pool, sizeof(*propstat));
            propstat->text =
                "<D:propstat>" DEBUG_CR
                "<D:prop><D:lockdiscovery/></D:prop>" DEBUG_CR
                "<D:status>HTTP/1.1 424 Failed Dependency</D:status>" DEBUG_CR
                "</D:propstat>" DEBUG_CR;
        }

        /* create the 424 response */
        new_response = apr_pcalloc(r->pool, sizeof(*new_response));
        new_response->href = resource->uri;
        new_response->status = HTTP_FAILED_DEPENDENCY;
        new_response->propresult.propstats = propstat;
        new_response->desc =
            "An error occurred on another resource, preventing the "
            "requested operation on this resource.";

        new_response->next = *response;
        *response = new_response;

        /* manufacture a 207 error for the multistatus response(s) */
        return dav_new_error(r->pool, HTTP_MULTI_STATUS, 0, 0,
                             "Error(s) occurred on resources during the "
                             "validation process.");
    }

    return err;
}

/* dav_get_locktoken_list:
 *
 * Sets ltl to a locktoken_list of all positive locktokens in header,
 * else NULL if no If-header, or no positive locktokens.
 */
DAV_DECLARE(dav_error *) dav_get_locktoken_list(request_rec *r,
                                                dav_locktoken_list **ltl)
{
    dav_error *err;
    dav_if_header *if_header;
    dav_if_state_list *if_state;
    dav_locktoken_list *lock_token = NULL;

    *ltl = NULL;

    if ((err = dav_process_if_header(r, &if_header)) != NULL) {
        /* ### add a higher-level description? */
        return err;
    }

    while (if_header != NULL) {
        if_state = if_header->state;        /* Beginning of the if_state linked list */
        while (if_state != NULL)        {
            if (if_state->condition == DAV_IF_COND_NORMAL
                && if_state->type == dav_if_opaquelock) {
                lock_token = apr_pcalloc(r->pool, sizeof(dav_locktoken_list));
                lock_token->locktoken = if_state->locktoken;
                lock_token->next = *ltl;
                *ltl = lock_token;
            }
            if_state = if_state->next;
        }
        if_header = if_header->next;
    }
    if (*ltl == NULL) {
        /* No nodes added */
        return dav_new_error(r->pool, HTTP_BAD_REQUEST, DAV_ERR_IF_ABSENT, 0,
                             "No locktokens were specified in the \"If:\" "
                             "header, so the refresh could not be performed.");
    }

    return NULL;
}

#if 0 /* not needed right now... */

static const char *strip_white(const char *s, apr_pool_t *pool)
{
    apr_size_t idx;

    /* trim leading whitespace */
    while (apr_isspace(*s))     /* assume: return false for '\0' */
        ++s;

    /* trim trailing whitespace */
    idx = strlen(s) - 1;
    if (apr_isspace(s[idx])) {
        char *s2 = apr_pstrdup(pool, s);

        while (apr_isspace(s2[idx]) && idx > 0)
            --idx;
        s2[idx + 1] = '\0';
        return s2;
    }

    return s;
}
#endif

#define DAV_LABEL_HDR "Label"

/* dav_add_vary_header
 *
 * If there were any headers in the request which require a Vary header
 * in the response, add it.
 */
DAV_DECLARE(void) dav_add_vary_header(request_rec *in_req,
                                      request_rec *out_req,
                                      const dav_resource *resource)
{
    const dav_hooks_vsn *vsn_hooks = DAV_GET_HOOKS_VSN(in_req);

    /* ### this is probably all wrong... I think there is a function in
       ### the Apache API to add things to the Vary header. need to check */

    /* Only versioning headers require a Vary response header,
     * so only do this check if there is a versioning provider */
    if (vsn_hooks != NULL) {
        const char *target = apr_table_get(in_req->headers_in, DAV_LABEL_HDR);

        /* If Target-Selector specified, add it to the Vary header */
        if (target != NULL) {
            const char *vary = apr_table_get(out_req->headers_out, "Vary");

            if (vary == NULL)
                vary = DAV_LABEL_HDR;
            else
                vary = apr_pstrcat(out_req->pool, vary, "," DAV_LABEL_HDR,
                                   NULL);

            apr_table_setn(out_req->headers_out, "Vary", vary);
        }
    }
}

/* dav_can_auto_checkout
 *
 * Determine whether auto-checkout is enabled for a resource.
 * r - the request_rec
 * resource - the resource
 * auto_version - the value of the auto_versionable hook for the resource
 * lockdb - pointer to lock database (opened if necessary)
 * auto_checkout - set to 1 if auto-checkout enabled
 */
static dav_error * dav_can_auto_checkout(
    request_rec *r,
    dav_resource *resource,
    dav_auto_version auto_version,
    dav_lockdb **lockdb,
    int *auto_checkout)
{
    dav_error *err;
    dav_lock *lock_list;

    *auto_checkout = 0;

    if (auto_version == DAV_AUTO_VERSION_ALWAYS) {
        *auto_checkout = 1;
    }
    else if (auto_version == DAV_AUTO_VERSION_LOCKED) {
        if (*lockdb == NULL) {
            const dav_hooks_locks *locks_hooks = DAV_GET_HOOKS_LOCKS(r);

            if (locks_hooks == NULL) {
                return dav_new_error(r->pool, HTTP_INTERNAL_SERVER_ERROR, 0, 0,
                                     "Auto-checkout is only enabled for locked resources, "
                                     "but there is no lock provider.");
            }

            if ((err = (*locks_hooks->open_lockdb)(r, 0, 0, lockdb)) != NULL) {
                return dav_push_error(r->pool, HTTP_INTERNAL_SERVER_ERROR, 0,
                                      "Cannot open lock database to determine "
                                      "auto-versioning behavior.",
                                      err);
            }
        }

        if ((err = dav_lock_query(*lockdb, resource, &lock_list)) != NULL) {
            return dav_push_error(r->pool,
                                  HTTP_INTERNAL_SERVER_ERROR, 0,
                                  "The locks could not be queried for "
                                  "determining auto-versioning behavior.",
                                  err);
        }

        if (lock_list != NULL)
            *auto_checkout = 1;
    }

    return NULL;
}

/* see mod_dav.h for docco */
DAV_DECLARE(dav_error *) dav_auto_checkout(
    request_rec *r,
    dav_resource *resource,
    int parent_only,
    dav_auto_version_info *av_info)
{
    const dav_hooks_vsn *vsn_hooks = DAV_GET_HOOKS_VSN(r);
    dav_lockdb *lockdb = NULL;
    dav_error *err = NULL;

    /* Initialize results */
    memset(av_info, 0, sizeof(*av_info));

    /* if no versioning provider, just return */
    if (vsn_hooks == NULL)
        return NULL;

    /* check parent resource if requested or if resource must be created */
    if (!resource->exists || parent_only) {
        dav_resource *parent;

        if ((err = (*resource->hooks->get_parent_resource)(resource,
                                                           &parent)) != NULL)
            goto done;

        if (parent == NULL || !parent->exists) {
            err = dav_new_error(r->pool, HTTP_CONFLICT, 0, 0,
                                apr_psprintf(r->pool,
                                            "Missing one or more intermediate "
                                            "collections. Cannot create resource %s.",
                                            ap_escape_html(r->pool, resource->uri)));
            goto done;
        }

        av_info->parent_resource = parent;

        /* if parent versioned and not checked out, see if it can be */
        if (parent->versioned && !parent->working) {
            int checkout_parent;

            if ((err = dav_can_auto_checkout(r, parent,
                                             (*vsn_hooks->auto_versionable)(parent),
                                             &lockdb, &checkout_parent))
                != NULL) {
                goto done;
            }

            if (!checkout_parent) {
                err = dav_new_error(r->pool, HTTP_CONFLICT, 0, 0,
                                    "<DAV:cannot-modify-checked-in-parent>");
                goto done;
            }

            /* Try to checkout the parent collection.
             * Note that auto-versioning can only be applied to a version selector,
             * so no separate working resource will be created.
             */
            if ((err = (*vsn_hooks->checkout)(parent, 1 /*auto_checkout*/,
                                              0, 0, 0, NULL, NULL))
                != NULL)
            {
                err = dav_push_error(r->pool, HTTP_CONFLICT, 0,
                                     apr_psprintf(r->pool,
                                                 "Unable to auto-checkout parent collection. "
                                                 "Cannot create resource %s.",
                                                 ap_escape_html(r->pool, resource->uri)),
                                     err);
                goto done;
            }

            /* remember that parent was checked out */
            av_info->parent_checkedout = 1;
        }
    }

    /* if only checking parent, we're done */
    if (parent_only)
        goto done;

    /* if creating a new resource, see if it should be version-controlled */
    if (!resource->exists
        && (*vsn_hooks->auto_versionable)(resource) == DAV_AUTO_VERSION_ALWAYS) {

        if ((err = (*vsn_hooks->vsn_control)(resource, NULL)) != NULL) {
            err = dav_push_error(r->pool, HTTP_CONFLICT, 0,
                                 apr_psprintf(r->pool,
                                             "Unable to create versioned resource %s.",
                                             ap_escape_html(r->pool, resource->uri)),
                                 err);
            goto done;
        }

        /* remember that resource was created */
        av_info->resource_versioned = 1;
    }

    /* if resource is versioned, make sure it is checked out */
    if (resource->versioned && !resource->working) {
        int checkout_resource;

        if ((err = dav_can_auto_checkout(r, resource,