/****************************************************************************

  mod_dav_pgsql (DASL) for apache 2.X
  CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
Author : sean kim (sean@solutionbox.co.kr)

$Id: lock.c,v 1.3 2006/11/27 02:25:23 sean Exp $

Redistribution and use in source and binary forms, with or with out
modification, are not permitted in outside of SolutionBox Inc.

 ****************************************************************************/

/*
 ** DAV filesystem lock implementation
 */

#include <apr.h>
#include <apr_strings.h>
#include <apr_file_io.h>
#include <apr_uuid.h>

#define APR_WANT_MEMFUNC
#include <apr_want.h>

#include <httpd.h>
#include <http_log.h>

#include "dav_repos.h"
#include "lock.h"
#include "dbms.h"
#include "util.h"


/* Will be replaced to MySQL things */
/* DBM functions used by the repository and locking providers */
extern const dav_hooks_db dav_hooks_db_dbm;

/* ---------------------------------------------------------------
 **
 ** Lock database primitives
 **
 */

/*
 ** LOCK DATABASES
 ** 
 ** Lockdiscovery information is stored in the single lock database specified
 ** by the DAVLockDB directive.  Information about this db is stored in the
 ** global server configuration.
 **
 ** KEY
 **
 ** The database is keyed by a key_type unsigned char (DAV_TYPE_INODE or
 ** DAV_TYPE_FNAME) followed by inode and device number if possible,
 ** otherwise full path (in the case of Win32 or lock-null resources).
 **
 ** VALUE
 **
 ** The value consists of a list of elements.
 **    DIRECT LOCK:     [char      (DAV_LOCK_DIRECT),
 **			char      (dav_lock_scope),
 **			char      (dav_lock_type),
 **			int        depth,
 **			time_t     expires,
 **			apr_uuid_t locktoken,
 **			char[]     owner,
 **                      char[]     auth_user]
 **
 **    INDIRECT LOCK:   [char      (DAV_LOCK_INDIRECT),
 **			apr_uuid_t locktoken,
 **			time_t     expires,
 **			int        key_size,
 **			char[]     key]
 **       The key is to the collection lock that resulted in this indirect lock
 */


/*
 ** Stored direct lock info - full lock_discovery length:  
 ** prefix + Fixed length + lock token + 2 strings + 2 nulls (one for each string)
 */
#define dav_size_direct(a)	(1 + sizeof(dav_lock_discovery_fixed) \
		+ sizeof(apr_uuid_t) \
		+ ((a)->owner ? strlen((a)->owner) : 0) \
		+ ((a)->auth_user ? strlen((a)->auth_user) : 0) \
		+ 2)

/* Stored indirect lock info - lock token and apr_datum_t */
#define dav_size_indirect(a)	(1 + sizeof(apr_uuid_t) \
		+ sizeof(time_t) \
		+ sizeof(int) + (a)->key.dsize)

/*
 ** The lockdb structure.
 **
 ** The <db> field may be NULL, meaning one of two things:
 ** 1) That we have not actually opened the underlying database (yet). The
 **    <opened> field should be false.
 ** 2) We opened it readonly and it wasn't present.
 **
 ** The delayed opening (determined by <opened>) makes creating a lockdb
 ** quick, while deferring the underlying I/O until it is actually required.
 **
 ** We export the notion of a lockdb, but hide the details of it. Most
 ** implementations will use a database of some kind, but it is certainly
 ** possible that alternatives could be used.
 */
struct dav_lockdb_private
{
	request_rec *r;		/* for accessing the uuid state */
	apr_pool_t *pool;		/* a pool to use */
};

typedef struct
{
	dav_lockdb pub;
	dav_lockdb_private priv;
}
dav_lockdb_combined;

/*
 ** The private part of the lock structure.
 */
struct dav_lock_private
{
	const char *key;		/* key into the lock database */
};
typedef struct
{
	dav_lock pub;
	dav_lock_private priv;
	dav_locktoken token;
}
dav_lock_combined;

/*
 ** This must be forward-declared so the open_lockdb function can use it.
 */
extern const dav_hooks_locks dav_repos_hooks_locks;


/* internal function for creating locks */
static dav_lock *dav_repos_alloc_lock(dav_lockdb * lockdb, const char *key,
		const dav_locktoken * locktoken)
{
	dav_lock_combined *comb;
	apr_uuid_t uuid;
	char char_uuid[APR_UUID_FORMATTED_LENGTH + 1];
	TRACE();

	comb = apr_pcalloc(lockdb->info->pool, sizeof(*comb));
	comb->pub.rectype = DAV_LOCKREC_DIRECT;
	comb->pub.info = &comb->priv;
	comb->priv.key = key;

	if (locktoken == NULL) {
		comb->pub.locktoken = &comb->token;
		apr_uuid_get(&uuid);
		apr_uuid_format(char_uuid, &uuid);
		comb->token.char_uuid = apr_pstrdup(lockdb->info->pool, char_uuid);
	}
	else {
		comb->pub.locktoken = locktoken;
	}

	return &comb->pub;
}

/*
 ** dav_repos_parse_locktoken
 **
 ** Parse an opaquelocktoken URI into a locktoken.
 */
static dav_error *dav_repos_parse_locktoken(apr_pool_t * p,
		const char *char_token,
		dav_locktoken ** locktoken_p)
{
	dav_locktoken *locktoken;
	apr_uuid_t uuid;

	TRACE();

	if (ap_strstr_c(char_token, "opaquelocktoken:") != char_token) {
		return solbox_dav_new_error(p,
				HTTP_BAD_REQUEST, DAV_ERR_LOCK_UNK_STATE_TOKEN,
				"The lock token uses an unknown State-token "
				"format and could not be parsed.");
	}
	char_token += 16;
	locktoken = apr_pcalloc(p, sizeof(*locktoken));

	if (apr_uuid_parse(&uuid, char_token)) {
		return solbox_dav_new_error(p, HTTP_BAD_REQUEST, DAV_ERR_LOCK_PARSE_TOKEN,
				"The opaquelocktoken has an incorrect format "
				"and could not be parsed.");
	}

	locktoken->char_uuid = apr_pstrdup(p, char_token);

	*locktoken_p = locktoken;
	return NULL;
}


/*
 ** dav_repos_format_locktoken
 **
 ** Generate the URI for a locktoken
 */
static const char *dav_repos_format_locktoken(apr_pool_t * p,
		const dav_locktoken * locktoken)
{


	TRACE();

	return apr_pstrcat(p, "opaquelocktoken:", locktoken->char_uuid, NULL);
}

/*
 ** dav_repos_compare_locktoken
 **
 ** Determine whether two locktokens are the same
 */
static int dav_repos_compare_locktoken(const dav_locktoken * lt1,
		const dav_locktoken * lt2)
{
	TRACE();

	DBG0(lt1->char_uuid);
	DBG0(lt2->char_uuid);

	return strcmp(lt1->char_uuid, lt2->char_uuid);
}

/*
 ** dav_repos_open_lockdb:
 **
 ** "open" the lock database, as specified in the global server configuration.
 ** If force is TRUE, then the database is opened now, rather than lazily.
 **
 ** Note that only one can be open read/write.
 */
static dav_error *dav_repos_open_lockdb(request_rec * r, int ro, int force,
		dav_lockdb ** lockdb)
{
	TRACE();

#ifdef __NOT_USE_LOCKDB__
	*lockdb = NULL;
#else
	dav_lockdb_combined *comb;

	comb = apr_pcalloc(r->pool, sizeof(*comb));

	comb->pub.hooks = &dav_repos_hooks_locks;
	comb->pub.ro = ro;
	comb->pub.info = &comb->priv;
	comb->priv.r = r;
	comb->priv.pool = r->pool;

	DBG0("===== dav_repos_open_lockdb =====");
	DBG1("%d", ro);
	/*    DBG1("%s", &comb->priv); */
	/*    DBG1("%s", r); */
	/*    DBG1("%s", r->pool); */
	DBG0("=================================");

	/* Get DBMS handler */
	//comb->priv.db = dav_repos_get_db(r);

	/* done initializing. return it. */
	*lockdb = &comb->pub;

	/* What force mean? */
	if (force) {

	}
#endif

	return NULL;
}

/*
 ** dav_repos_close_lockdb:
 **
 ** Close it. Duh.
 */
static void dav_repos_close_lockdb(dav_lockdb * lockdb)
{
	TRACE();
}

/*
 ** dav_repos_lock_expired:  return 1 (true) if the given timeout is in the past
 **    or present (the lock has expired), or 0 (false) if in the future
 **    (the lock has not yet expired).
 */
int dav_repos_lock_expired(time_t expires)
{
	TRACE();
	return expires != DAV_TIMEOUT_INFINITE && time(NULL) >= expires;
}

/*
 ** dav_repos_save_lock_record:  Saves the lock information specified in the
 **    direct and indirect lock lists about path into the lock database.
 **    If direct and indirect == NULL, the key is removed.
 */
static dav_error *dav_repos_save_lock_record(dav_lockdb * lockdb,
		const char *key,
		dav_lock_discovery * direct,
		dav_lock_indirect * indirect)
{
	apr_pool_t *pool;
	dav_error *err;

	TRACE();

	if (!lockdb) return NULL;

	pool = lockdb->info->pool;

#if DAV_DEBUG
	if (lockdb->ro) {
		return solbox_dav_new_error(lockdb->info->pool,
				HTTP_INTERNAL_SERVER_ERROR, 0,
				"INTERNAL DESIGN ERROR: the lockdb was opened "
				"readonly, but an attempt to save locks was "
				"performed.");
	}
#endif

	/* If nothing to save, delete key */
	if (direct == NULL && indirect == NULL) {
		/* don't fail if the key is not present */
		/* ### but what about other errors? */
		return dbms_remove_lock_record(lockdb->info->r, key, pool);
	}

	err = dbms_save_lock_record(lockdb->info->r, key, direct, indirect, pool);
	if (err != NULL)
		/* ### more details? add an error_id? */
		return dav_push_error(lockdb->info->pool,
				HTTP_INTERNAL_SERVER_ERROR,
				DAV_ERR_LOCK_SAVE_LOCK,
				"Could not save lock information.", err);


	return NULL;
}

/*
 ** dav_load_lock_record:  Reads lock information about key from lock db;
 **    creates linked lists of the direct and indirect locks.
 **
 **    If add_method = DAV_APPEND_LIST, the result will be appended to the
 **    head of the direct and indirect lists supplied.
 **
 **    Passive lock removal:  If lock has timed out, it will not be returned.
 **    ### How much "logging" does RFC 2518 require?
 */
static dav_error *dav_repos_load_lock_record(dav_lockdb * lockdb,
		const char *key, int add_method,
		dav_lock_discovery ** direct,
		dav_lock_indirect ** indirect)
{
	apr_pool_t *pool;
	dav_error *err;
	int need_save = DAV_FALSE;

	TRACE();

	if (!lockdb) return NULL;

	pool = lockdb->info->pool;

	if (add_method != DAV_APPEND_LIST) {
		*direct = NULL;
		*indirect = NULL;
	}

	/*
	 ** If we opened readonly and the db wasn't there, then there are no
	 ** locks for this resource. Just exit.
	 ** We need another condition for this
	 */
	if (lockdb->info->r == NULL)
		return NULL;

	/* It will get lock records and remove if it is expired and set need_save */
	if ((err = dbms_load_lock_record(lockdb->info->r, key, direct, indirect, &need_save, pool)) != NULL)
		return err;

	/* Save data, if we need */
	if (need_save == DAV_TRUE) {
		return dav_repos_save_lock_record(lockdb, key, *direct, *indirect);
	}

	return NULL;
}

/* resolve <indirect>, returning <*direct> */
static dav_error *dav_repos_resolve(dav_lockdb * lockdb,
		dav_lock_indirect * indirect,
		dav_lock_discovery ** direct,
		dav_lock_discovery ** ref_dp,
		dav_lock_indirect ** ref_ip)
{
	dav_error *err;
	dav_lock_discovery *dir;
	dav_lock_indirect *ind;

	TRACE();

	if (!lockdb) return NULL;

	if ((err = dav_repos_load_lock_record(lockdb, indirect->key,
					DAV_CREATE_LIST,
					&dir, &ind)) != NULL) {
		/* ### insert a higher-level description? */
		return err;
	}
	if (ref_dp != NULL) {
		*ref_dp = dir;
		*ref_ip = ind;
	}

	for (; dir != NULL; dir = dir->next) {
		if (!dav_repos_compare_locktoken(indirect->locktoken, dir->locktoken)) {
			*direct = dir;
			return NULL;
		}
	}

	/* No match found (but we should have found one!) */

	/* ### use a different description and/or error ID? */
	return solbox_dav_new_error(lockdb->info->pool,
			HTTP_INTERNAL_SERVER_ERROR,
			DAV_ERR_LOCK_CORRUPT_DB,
			"The lock database was found to be corrupt. "
			"An indirect lock's direct lock could not "
			"be found.");
}

/* ---------------------------------------------------------------
 **
 ** Property-related lock functions
 **
 */

/*
 ** dav_repos_get_supportedlock:  Returns a static string for all supportedlock
 **    properties. I think we save more returning a static string than
 **    constructing it every time, though it might look cleaner.
 */
static const char *dav_repos_get_supportedlock(const dav_resource * resource)
{
	static const char supported[] = DEBUG_CR
		"<D:lockentry>" DEBUG_CR
		"<D:lockscope><D:exclusive/></D:lockscope>" DEBUG_CR
		"<D:locktype><D:write/></D:locktype>" DEBUG_CR
		"</D:lockentry>" DEBUG_CR
		"<D:lockentry>" DEBUG_CR
		"<D:lockscope><D:shared/></D:lockscope>" DEBUG_CR
		"<D:locktype><D:write/></D:locktype>" DEBUG_CR
		"</D:lockentry>" DEBUG_CR;

	TRACE();

	return supported;
}

/* ---------------------------------------------------------------
 **
 ** General lock functions
 **
 */

/* ---------------------------------------------------------------
 **
 ** Functions dealing with lock-null resources
 **
 */

/* ### fold into append_lock? */
/* ### take an optional buf parameter? */
static dav_error *dav_repos_add_locknull_state(dav_lockdb * lockdb,
		const dav_resource * resource)
{
	apr_pool_t *p;
	dav_error *err;

	TRACE();

	if (!lockdb) return NULL;

	p = lockdb->info->pool;

	if ((err = dbms_save_locknull_member(lockdb->info->r, resource->uri, p)) != NULL)
		return dav_push_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
				"Could not save locknull DB.", err);

	return NULL;
}

/*
 ** dav_repos_remove_locknull_state:  Given a request, check to see if r->filename
 **    is/was a lock-null resource.  If so, return it to an existant state.
 **
 **    ### this function is broken... it doesn't check!
 **
 **    In this implementation, this involves two things:
 **    (a) remove it from the list in the appropriate .DAV/locknull file
 **    (b) on *nix, convert the key from a filename to an inode.
 */
static dav_error *dav_repos_remove_locknull_state(dav_lockdb * lockdb,
		const dav_resource *
		resource)
{
	dav_error *err;
	apr_pool_t *p;
	const char *pathname = resource->info->pathname;

	TRACE();

	if (!lockdb) return NULL;

	p = lockdb->info->pool;

	if ((err = dbms_remove_locknull_member(lockdb->info->r, pathname, p)) != NULL) {
		/* ### add a higher-level description? */
		return err;
	}


	/* We don't need this, since our key is same for locknull and lock */
#if 0 
	{
		dav_lock_discovery *ld;
		dav_lock_indirect *id;

		/*
		 ** Fetch the lock(s) that made the resource lock-null. Remove
		 ** them under the filename key. Obtain the new inode key, and
		 ** save the same lock information under it.
		 */
		if ((err = dav_repos_load_lock_record(lockdb, pathname, DAV_CREATE_LIST,
						&ld, &id)) != NULL) {
			/* ### insert a higher-level error description */
			return err;
		}

		if ((err = dav_repos_save_lock_record(lockdb, pathname, NULL,
						NULL)) != NULL) {
			/* ### insert a higher-level error description */
			return err;
		}

		if ((err = dav_repos_save_lock_record(lockdb, resource->uri, ld,
						id)) != NULL) {
			/* ### insert a higher-level error description */
			return err;
		}
	}

#endif
	return NULL;
}

static dav_error *dav_repos_create_lock(dav_lockdb * lockdb,
		const dav_resource * resource,
		dav_lock ** lock)
{
	TRACE();

	if (!lockdb) return NULL;

	*lock = dav_repos_alloc_lock(lockdb, resource->uri, NULL);

	(*lock)->is_locknull = !resource->exists;

	return NULL;
}

static dav_error *dav_repos_get_locks(dav_lockdb * lockdb,
		const dav_resource * resource,
		int calltype, dav_lock ** locks)
{
	const char *key;
	dav_error *err;
	dav_lock *lock = NULL;
	dav_lock *newlock;
	dav_lock_discovery *dp = NULL;
	dav_lock_indirect *ip = NULL;

	TRACE();

	if (!lockdb) return NULL;

#if DAV_DEBUG
	if (calltype == DAV_GETLOCKS_COMPLETE) {
		return solbox_dav_new_error(lockdb->info->pool,
				HTTP_INTERNAL_SERVER_ERROR, 0,
				"INTERNAL DESIGN ERROR: DAV_GETLOCKS_COMPLETE "
				"is not yet supported");
	}
#endif

	key = resource->uri;
	if ((err = dav_repos_load_lock_record(lockdb, key, DAV_CREATE_LIST,
					&dp, &ip)) != NULL) {
		/* ### push a higher-level desc? */
		return err;
	}

	/* copy all direct locks to the result list */
	for (; dp != NULL; dp = dp->next) {
		newlock = dav_repos_alloc_lock(lockdb, key, dp->locktoken);
		newlock->is_locknull = !resource->exists;
		newlock->scope = dp->f.scope;
		newlock->type = dp->f.type;
		newlock->depth = dp->f.depth;
		newlock->timeout = dp->f.timeout;
		newlock->owner = dp->owner;
		newlock->auth_user = dp->auth_user;

		/* hook into the result list */
		newlock->next = lock;
		lock = newlock;
	}

	/* copy all the indirect locks to the result list. resolve as needed. */
	for (; ip != NULL; ip = ip->next) {
		newlock = dav_repos_alloc_lock(lockdb, ip->key, ip->locktoken);
		newlock->is_locknull = !resource->exists;

		if (calltype == DAV_GETLOCKS_RESOLVED) {
			if ((err = dav_repos_resolve(lockdb, ip, &dp, NULL, NULL)) != NULL){
				/* ### push a higher-level desc? */
				return err;
			}

			newlock->scope = dp->f.scope;
			newlock->type = dp->f.type;
			newlock->depth = dp->f.depth;
			newlock->timeout = dp->f.timeout;
			newlock->owner = dp->owner;
			newlock->auth_user = dp->auth_user;
		}
		else {
			/* DAV_GETLOCKS_PARTIAL */
			newlock->rectype = DAV_LOCKREC_INDIRECT_PARTIAL;
		}

		/* hook into the result list */
		newlock->next = lock;
		lock = newlock;
	}

	*locks = lock;
	return NULL;
}

static dav_error *dav_repos_find_lock(dav_lockdb * lockdb,
		const dav_resource * resource,
		const dav_locktoken * locktoken,
		int partial_ok, dav_lock ** lock)
{
	dav_error *err;
	const char *key;
	dav_lock_discovery *dp;
	dav_lock_indirect *ip;

	TRACE();

	*lock = NULL;

	if (!lockdb) return NULL;

	key = resource->uri;
	if ((err = dav_repos_load_lock_record(lockdb, key, DAV_CREATE_LIST,
					&dp, &ip)) != NULL) {
		/* ### push a higher-level desc? */
		return err;
	}

	for (; dp != NULL; dp = dp->next) {
		if (!dav_repos_compare_locktoken(locktoken, dp->locktoken)) {
			*lock = dav_repos_alloc_lock(lockdb, key, locktoken);
			(*lock)->is_locknull = !resource->exists;
			(*lock)->scope = dp->f.scope;
			(*lock)->type = dp->f.type;
			(*lock)->depth = dp->f.depth;
			(*lock)->timeout = dp->f.timeout;
			(*lock)->owner = dp->owner;
			(*lock)->auth_user = dp->auth_user;
			return NULL;
		}
	}

	for (; ip != NULL; ip = ip->next) {
		if (!dav_repos_compare_locktoken(locktoken, ip->locktoken)) {
			*lock = dav_repos_alloc_lock(lockdb, ip->key, locktoken);
			(*lock)->is_locknull = !resource->exists;

			/* ### nobody uses the resolving right now! */
			if (partial_ok) {
				(*lock)->rectype = DAV_LOCKREC_INDIRECT_PARTIAL;
			}
			else {
				(*lock)->rectype = DAV_LOCKREC_INDIRECT;
				if ((err = dav_repos_resolve(lockdb, ip, &dp,
								NULL, NULL)) != NULL) {
					/* ### push a higher-level desc? */
					return err;
				}
				(*lock)->scope = dp->f.scope;
				(*lock)->type = dp->f.type;
				(*lock)->depth = dp->f.depth;
				(*lock)->timeout = dp->f.timeout;
				(*lock)->owner = dp->owner;
				(*lock)->auth_user = dp->auth_user;
			}
			return NULL;
		}
	}

	return NULL;
}

static dav_error *dav_repos_has_locks(dav_lockdb * lockdb,
		const dav_resource * resource,
		int *locks_present)
{
	const char *key;
	apr_pool_t *pool;

	TRACE();

	*locks_present = 0;

	if (!lockdb) return NULL;

	pool = lockdb->info->pool;

	/*
	 ** If we opened readonly and the db wasn't there, then there are no
	 ** locks for this resource. Just exit.
	 */
	if (lockdb->info->r == NULL)
		return NULL;

	key = resource->uri;

	*locks_present = dbms_lock_exists(lockdb->info->r, key, pool);

	return NULL;
}

static dav_error *dav_repos_append_locks(dav_lockdb * lockdb,
		const dav_resource * resource,
		int make_indirect,
		const dav_lock * lock)
{


	dav_error *err;
	dav_lock_indirect *ip;
	dav_lock_discovery *dp;
	const char *key;
	apr_pool_t *p;

	TRACE();

	if (!lockdb) return NULL;

	p = lockdb->info->pool;

	key = resource->uri;
	if ((err = dav_repos_load_lock_record(lockdb, key, 0, &dp, &ip)) != NULL) {
		/* ### maybe add in a higher-level description */
		return err;
	}

	/*
	 ** ### when we store the lock more directly, we need to update
	 ** ### lock->rectype and lock->is_locknull
	 */

	if (make_indirect) {
		for (; lock != NULL; lock = lock->next) {

			/* ### this works for any <lock> rectype */
			dav_lock_indirect *newi = apr_pcalloc(p, sizeof(*newi));

			/* ### shut off the const warning for now */
			newi->locktoken = (dav_locktoken *) lock->locktoken;
			newi->timeout = lock->timeout;
			newi->key = lock->info->key;
			newi->next = ip;
			ip = newi;
		}
	}
	else {
		for (; lock != NULL; lock = lock->next) {
			/* create and link in the right kind of lock */

			if (lock->rectype == DAV_LOCKREC_DIRECT) {
				dav_lock_discovery *newd = apr_pcalloc(p, sizeof(*newd));

				newd->f.scope = lock->scope;
				newd->f.type = lock->type;
				newd->f.depth = lock->depth;
				newd->f.timeout = lock->timeout;
				/* ### shut off the const warning for now */
				newd->locktoken = (dav_locktoken *) lock->locktoken;
				newd->owner = lock->owner;
				newd->auth_user = lock->auth_user;
				newd->next = dp;
				dp = newd;
			}
			else {
				/* DAV_LOCKREC_INDIRECT(_PARTIAL) */

				dav_lock_indirect *newi = apr_pcalloc(p, sizeof(*newi));

				/* ### shut off the const warning for now */
				newi->locktoken = (dav_locktoken *) lock->locktoken;
				newi->key = lock->info->key;
				newi->next = ip;
				ip = newi;
			}
		}
	}

	if ((err = dav_repos_save_lock_record(lockdb, key, dp, ip)) != NULL) {
		/* ### maybe add a higher-level description */
		return err;
	}

	/* we have a special list for recording locknull resources */
	/* ### ack! this can add two copies to the locknull list */
	if (!resource->exists
			&& (err = dav_repos_add_locknull_state(lockdb, resource)) != NULL) {
		/* ### maybe add a higher-level description */
		return err;
	}

	return NULL;
}

static dav_error *dav_repos_remove_lock(dav_lockdb * lockdb,
		const dav_resource * resource,
		const dav_locktoken * locktoken)
{
	dav_error *err;
	dav_lock_discovery *dh = NULL;
	dav_lock_indirect *ih = NULL;
	const char *key;

	TRACE();

	if (!lockdb) return NULL;

	key = resource->uri;

	if (locktoken != NULL) {
		dav_lock_discovery *dp;
		dav_lock_discovery *dprev = NULL;
		dav_lock_indirect *ip;
		dav_lock_indirect *iprev = NULL;

		if ((err = dav_repos_load_lock_record(lockdb, key, DAV_CREATE_LIST,
						&dh, &ih)) != NULL) {
			/* ### maybe add a higher-level description */
			return err;
		}

		for (dp = dh; dp != NULL; dp = dp->next) {
			if (dav_repos_compare_locktoken(locktoken, dp->locktoken) == 0) {
				if (dprev)
					dprev->next = dp->next;
				else
					dh = dh->next;
			}
			dprev = dp;
		}

		for (ip = ih; ip != NULL; ip = ip->next) {
			if (dav_repos_compare_locktoken(locktoken, ip->locktoken) == 0) {
				if (iprev)
					iprev->next = ip->next;
				else
					ih = ih->next;
			}
			iprev = ip;
		}

	}

	/* save the modified locks, or remove all locks (dh=ih=NULL). */
	if ((err = dav_repos_save_lock_record(lockdb, key, dh, ih)) != NULL) {
		/* ### maybe add a higher-level description */
		return err;
	}

	/*
	 ** If this resource is a locknull resource AND no more locks exist,
	 ** then remove the locknull member.
	 **
	 */
	/* In locknull, put, unlock case, the resource is exist
	 * Should I set the flag 
	 *
	 * if (!resource->exists && dh == NULL && ih == NULL
	 */
	DBG2("%d: %s", resource->exists, resource->uri);
	if (dh == NULL && ih == NULL
			&& (err = dbms_remove_locknull_member(lockdb->info->r,
					resource->uri,
					lockdb->info->pool)) != NULL) {
		/* ### maybe add a higher-level description */
		return err;
	}

	return NULL;
}

static int dav_repos_do_refresh(dav_lock_discovery * dp,
		const dav_locktoken_list * ltl,
		time_t new_time)
{
	int dirty = 0;

	TRACE();

	for (; ltl != NULL; ltl = ltl->next) {
		if (dav_repos_compare_locktoken(dp->locktoken, ltl->locktoken) == 0) {
			dp->f.timeout = new_time;
			dirty = 1;
		}
	}

	return dirty;
}

static dav_error *dav_repos_refresh_locks(dav_lockdb * lockdb,
		const dav_resource * resource,
		const dav_locktoken_list * ltl,
		time_t new_time, dav_lock ** locks)
{
	dav_error *err;
	const char *key;
	dav_lock_discovery *dp;
	dav_lock_discovery *dp_scan;
	dav_lock_indirect *ip;
	int dirty = 0;
	dav_lock *newlock;

	TRACE();

	*locks = NULL;

	if (!lockdb) return NULL;

	key = resource->uri;
	if ((err = dav_repos_load_lock_record(lockdb, key, DAV_CREATE_LIST,
					&dp, &ip)) != NULL) {
		/* ### maybe add in a higher-level description */
		return err;
	}

	/* ### we should be refreshing direct AND (resolved) indirect locks! */

	/* refresh all of the direct locks on this resource */
	for (dp_scan = dp; dp_scan != NULL; dp_scan = dp_scan->next) {
		if (dav_repos_do_refresh(dp_scan, ltl, new_time)) {
			/* the lock was refreshed. return the lock. */
			newlock = dav_repos_alloc_lock(lockdb, key, dp_scan->locktoken);
			newlock->is_locknull = !resource->exists;
			newlock->scope = dp_scan->f.scope;
			newlock->type = dp_scan->f.type;
			newlock->depth = dp_scan->f.depth;
			newlock->timeout = dp_scan->f.timeout;
			newlock->owner = dp_scan->owner;
			newlock->auth_user = dp_scan->auth_user;

			newlock->next = *locks;
			*locks = newlock;

			dirty = 1;
		}
	}

	/* if we refreshed any locks, then save them back. */
	if (dirty
			&& (err = dav_repos_save_lock_record(lockdb, key, dp, ip)) != NULL) {
		/* ### maybe add in a higher-level description */
		return err;
	}

	/* for each indirect lock, find its direct lock and refresh it. */
	for (; ip != NULL; ip = ip->next) {
		dav_lock_discovery *ref_dp;
		dav_lock_indirect *ref_ip;

		if ((err = dav_repos_resolve(lockdb, ip, &dp_scan,
						&ref_dp, &ref_ip)) != NULL) {
			/* ### push a higher-level desc? */
			return err;
		}
		if (dav_repos_do_refresh(dp_scan, ltl, new_time)) {
			/* the lock was refreshed. return the lock. */
			newlock = dav_repos_alloc_lock(lockdb, ip->key, dp->locktoken);
			newlock->is_locknull = !resource->exists;
			newlock->scope = dp->f.scope;
			newlock->type = dp->f.type;
			newlock->depth = dp->f.depth;
			newlock->timeout = dp->f.timeout;
			newlock->owner = dp->owner;
			newlock->auth_user = dp_scan->auth_user;

			newlock->next = *locks;
			*locks = newlock;

			/* save the (resolved) direct lock back */
			if ((err = dav_repos_save_lock_record(lockdb, ip->key, ref_dp,
							ref_ip)) != NULL) {
				/* ### push a higher-level desc? */
				return err;
			}
		}
	}

	return NULL;
}


const dav_hooks_locks dav_repos_hooks_locks = {
	dav_repos_get_supportedlock,
	dav_repos_parse_locktoken,
	dav_repos_format_locktoken,
	dav_repos_compare_locktoken,
	dav_repos_open_lockdb,
	dav_repos_close_lockdb,
	dav_repos_remove_locknull_state,
	dav_repos_create_lock,
	dav_repos_get_locks,
	dav_repos_find_lock,
	dav_repos_has_locks,
	dav_repos_append_locks,
	dav_repos_remove_lock,
	dav_repos_refresh_locks,
	NULL,			/* lookup_resource */

	NULL			/* ctx */
};
