summaryrefslogtreecommitdiffstats
path: root/modules/dav/fs/lock.c
blob: 7d2f83c675f02fa4ad1fe230e998fdcf194a7afa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
** DAV filesystem lock implementation
*/

#include "httpd.h"
#include "http_log.h"
#include "apr_file_io.h"

#include "mod_dav.h"
#include "dav_opaquelock.h"
#include "repos.h"


/* ---------------------------------------------------------------
**
** 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,
**			uuid_t locktoken,
**			char[] owner,
**                      char[] auth_user]
**
**    INDIRECT LOCK:   [char  (DAV_LOCK_INDIRECT),
**			uuid_t locktoken,
**			time_t expires,
**			int    key_size,
**			char[] key]
**       The key is to the collection lock that resulted in this indirect lock
*/

#define DAV_TRUE		1
#define DAV_FALSE		0

#define DAV_CREATE_LIST		23
#define DAV_APPEND_LIST		24

/* Stored lock_discovery prefix */
#define DAV_LOCK_DIRECT		1
#define DAV_LOCK_INDIRECT	2

#define DAV_TYPE_INODE		10
#define DAV_TYPE_FNAME		11


/* ack. forward declare. */
static dav_error * dav_fs_remove_locknull_member(apr_pool_t *p,
						 const char *filename,
						 dav_buffer *pbuf);

/*
** Use the opaquelock scheme for locktokens
*/
struct dav_locktoken {
    uuid_t uuid;
};


/* #################################################################
** ### keep these structures (internal) or move fully to dav_lock?
*/

/*
** We need to reliably size the fixed-length portion of
** dav_lock_discovery; best to separate it into another 
** struct for a convenient sizeof, unless we pack lock_discovery.
*/
typedef struct dav_lock_discovery_fixed
{
    char scope;
    char type;
    int depth;
    time_t timeout;
} dav_lock_discovery_fixed;

typedef struct dav_lock_discovery
{
    struct dav_lock_discovery_fixed f;

    dav_locktoken *locktoken;
    const char *owner;		/* owner field from activelock */
    const char *auth_user;	/* authenticated user who created the lock */
    struct dav_lock_discovery *next;
} dav_lock_discovery;

/* Indirect locks represent locks inherited from containing collections.
 * They reference the lock token for the collection the lock is
 * inherited from. A lock provider may also define a key to the
 * inherited lock, for fast datbase lookup. The key is opaque outside
 * the lock provider.
 */
typedef struct dav_lock_indirect
{
    dav_locktoken *locktoken;
    dav_datum key;
    struct dav_lock_indirect *next;
    time_t timeout;
} dav_lock_indirect;

/* ################################################################# */


/*
** 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(uuid_t) \
				 + ((a)->owner ? strlen((a)->owner) : 0) \
				 + ((a)->auth_user ? strlen((a)->auth_user) : 0) \
				 + 2)

/* Stored indirect lock info - lock token and dav_datum */
#define dav_size_indirect(a)	(1 + sizeof(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 */
    const char *lockdb_path;		/* where is the lock database? */

    int opened;				/* we opened the database */
    dav_db *db;				/* if non-NULL, the lock database */
};
typedef struct
{
    dav_lockdb pub;
    dav_lockdb_private priv;
} dav_lockdb_combined;

/*
** The private part of the lock structure.
*/
struct dav_lock_private
{
    dav_datum 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_hooks_locks_fs;


/* internal function for creating locks */
static dav_lock *dav_fs_alloc_lock(dav_lockdb *lockdb, dav_datum key,
				   const dav_locktoken *locktoken)
{
    dav_lock_combined *comb;

    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;
	dav_create_opaquelocktoken(dav_get_uuid_state(lockdb->info->r),
                                   &comb->token.uuid);
    }
    else {
	comb->pub.locktoken = locktoken;
    }

    return &comb->pub;
}

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

    if (ap_strstr_c(char_token, "opaquelocktoken:") != char_token) {
	return 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 (dav_parse_opaquelocktoken(char_token, &locktoken->uuid)) {
	return dav_new_error(p, HTTP_BAD_REQUEST, DAV_ERR_LOCK_PARSE_TOKEN,
			     "The opaquelocktoken has an incorrect format "
			     "and could not be parsed.");
    }
    
    *locktoken_p = locktoken;
    return NULL;
}

/*
** dav_fs_format_locktoken
**
** Generate the URI for a locktoken
*/
static const char *dav_fs_format_locktoken(
    apr_pool_t *p,
    const dav_locktoken *locktoken)
{
    const char *uuid_token = dav_format_opaquelocktoken(p, &locktoken->uuid);
    return apr_pstrcat(p, "opaquelocktoken:", uuid_token, NULL);
}

/*
** dav_fs_compare_locktoken
**
** Determine whether two locktokens are the same
*/
static int dav_fs_compare_locktoken(
    const dav_locktoken *lt1,
    const dav_locktoken *lt2)
{
    return dav_compare_opaquelocktoken(lt1->uuid, lt2->uuid);
}

/*
** dav_fs_really_open_lockdb:
**
** If the database hasn't been opened yet, then open the thing.
*/
static dav_error * dav_fs_really_open_lockdb(dav_lockdb *lockdb)
{
    dav_error *err;

    if (lockdb->info->opened)
	return NULL;

    err = dav_dbm_open_direct(lockdb->info->pool,
			      lockdb->info->lockdb_path,
			      lockdb->ro,
			      &lockdb->info->db);
    if (err != NULL) {
	return dav_push_error(lockdb->info->pool,
			      HTTP_INTERNAL_SERVER_ERROR,
			      DAV_ERR_LOCK_OPENDB,
			      "Could not open the lock database.",
			      err);
    }

    /* all right. it is opened now. */
    lockdb->info->opened = 1;

    return NULL;
}

/*
** dav_fs_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_fs_open_lockdb(request_rec *r, int ro, int force,
				      dav_lockdb **lockdb)
{
    dav_lockdb_combined *comb;

    comb = apr_pcalloc(r->pool, sizeof(*comb));
    comb->pub.hooks = &dav_hooks_locks_fs;
    comb->pub.ro = ro;
    comb->pub.info = &comb->priv;
    comb->priv.r = r;
    comb->priv.pool = r->pool;

    comb->priv.lockdb_path = dav_get_lockdb_path(r);
    if (comb->priv.lockdb_path == NULL) {
	return dav_new_error(r->pool, HTTP_INTERNAL_SERVER_ERROR,
			     DAV_ERR_LOCK_NO_DB,
			     "A lock database was not specified with the "
			     "DAVLockDB directive. One must be specified "
			     "to use the locking functionality.");
    }

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

    if (force) {
	/* ### add a higher-level comment? */
	return dav_fs_really_open_lockdb(*lockdb);
    }

    return NULL;
}

/*
** dav_fs_close_lockdb:
**
** Close it. Duh.
*/
static void dav_fs_close_lockdb(dav_lockdb *lockdb)
{
    if (lockdb->info->db != NULL)
	(*dav_hooks_db_dbm.close)(lockdb->info->db);
}

/*
** dav_fs_build_fname_key
**
** Given a pathname, build a DAV_TYPE_FNAME lock database key.
*/
static dav_datum dav_fs_build_fname_key(apr_pool_t *p, const char *pathname)
{
    dav_datum key;

    /* ### does this allocation have a proper lifetime? need to check */
    /* ### can we use a buffer for this? */

    /* size is TYPE + pathname + null */
    key.dsize = strlen(pathname) + 2;
    key.dptr = apr_palloc(p, key.dsize);
    *key.dptr = DAV_TYPE_FNAME;
    memcpy(key.dptr + 1, pathname, key.dsize - 1);
    if (key.dptr[key.dsize - 2] == '/')
	key.dptr[--key.dsize - 1] = '\0';
    return key;
}

/*
** dav_fs_build_key:  Given a resource, return a dav_datum key
**    to look up lock information for this file.
**
**    (Win32 or file is lock-null):
**       dav_datum->dvalue = full path
**
**    (non-Win32 and file exists ):
**       dav_datum->dvalue = inode, dev_major, dev_minor
*/
static dav_datum dav_fs_build_key(apr_pool_t *p, const dav_resource *resource)
{
    const char *file = dav_fs_pathname(resource);
#ifndef WIN32
    dav_datum key;
    apr_finfo_t finfo;

    /* ### use lstat() ?? */
    if (apr_stat(&finfo, file, p) == 0) {

	/* ### can we use a buffer for this? */
	key.dsize = 1 + sizeof(finfo.inode) + sizeof(finfo.device);
	key.dptr = apr_palloc(p, key.dsize);
	*key.dptr = DAV_TYPE_INODE;
	memcpy(key.dptr + 1, &finfo.inode, sizeof(finfo.inode));
	memcpy(key.dptr + 1 + sizeof(finfo.inode), &finfo.device,
	       sizeof(finfo.device));

	return key;
    }
#endif

    return dav_fs_build_fname_key(p, file);
}

/*
** dav_fs_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).
*/
static int dav_fs_lock_expired(time_t expires)
{
    return expires != DAV_TIMEOUT_INFINITE && time(NULL) >= expires;
}

/*
** dav_fs_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_fs_save_lock_record(dav_lockdb *lockdb, dav_datum key,
					   dav_lock_discovery *direct,
					   dav_lock_indirect *indirect)
{
    dav_error *err;
    dav_datum val = { 0 };
    char *ptr;
    dav_lock_discovery *dp = direct;
    dav_lock_indirect *ip = indirect;

#if DAV_DEBUG
    if (lockdb->ro) {
	return 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 ((err = dav_fs_really_open_lockdb(lockdb)) != NULL) {
	/* ### add a higher-level error? */
	return err;
    }

    /* If nothing to save, delete key */
    if (dp == NULL && ip == NULL) {
        /* don't fail if the key is not present */
        /* ### but what about other errors? */
	(void) (*dav_hooks_db_dbm.remove)(lockdb->info->db, key);
        return NULL;
    }
		
    while(dp) {
	val.dsize += dav_size_direct(dp);
	dp = dp->next;
    }
    while(ip) {
	val.dsize += dav_size_indirect(ip);
	ip = ip->next;
    }

    /* ### can this be apr_palloc() ? */
    /* ### hmmm.... investigate the use of a buffer here */
    ptr = val.dptr = apr_pcalloc(lockdb->info->pool, val.dsize);
    dp  = direct;
    ip  = indirect;

    while(dp) {
	*ptr++ = DAV_LOCK_DIRECT;	/* Direct lock - lock_discovery struct follows */
	memcpy(ptr, dp, sizeof(dp->f));	/* Fixed portion of struct */
	ptr += sizeof(dp->f);
        memcpy(ptr, dp->locktoken, sizeof(*dp->locktoken));
        ptr += sizeof(*dp->locktoken);
	if (dp->owner == NULL) {
	    *ptr++ = '\0';
	}
	else {
	    memcpy(ptr, dp->owner, strlen(dp->owner) + 1);	
	    ptr += strlen(dp->owner) + 1;
	}
	if (dp->auth_user == NULL) {
            *ptr++ = '\0';
	}
	else {
	    memcpy(ptr, dp->auth_user, strlen(dp->auth_user) + 1);
	    ptr += strlen(dp->auth_user) + 1;
	}

	dp = dp->next;
    }

    while(ip) {
	*ptr++ = DAV_LOCK_INDIRECT;	/* Indirect lock prefix */
	memcpy(ptr, ip->locktoken, sizeof(*ip->locktoken));	/* Locktoken */
	ptr += sizeof(*ip->locktoken);
	memcpy(ptr, &ip->timeout, sizeof(ip->timeout));		/* Expire time */
	ptr += sizeof(ip->timeout);
	memcpy(ptr, &ip->key.dsize, sizeof(ip->key.dsize));	/* Size of key */
	ptr += sizeof(ip->key.dsize);
	memcpy(ptr, ip->key.dptr, ip->key.dsize);	/* Key data */
	ptr += ip->key.dsize;
	ip = ip->next;
    }

    if ((err = (*dav_hooks_db_dbm.store)(lockdb->info->db,
						key, val)) != 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_fs_load_lock_record(dav_lockdb *lockdb, dav_datum key,
					   int add_method,
					   dav_lock_discovery **direct,
					   dav_lock_indirect **indirect)
{
    apr_pool_t *p = lockdb->info->pool;
    dav_error *err;
    size_t offset = 0;
    int need_save = DAV_FALSE;
    dav_datum val = { 0 };
    dav_lock_discovery *dp;
    dav_lock_indirect *ip;
    dav_buffer buf = { 0 };

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

    if ((err = dav_fs_really_open_lockdb(lockdb)) != NULL) {
	/* ### add a higher-level error? */
	return err;
    }

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

    if ((err = (*dav_hooks_db_dbm.fetch)(lockdb->info->db, key, &val)) != NULL)
        return err;
	
    if (!val.dsize)
	return NULL;

    while (offset < val.dsize) {
	switch (*(val.dptr + offset++)) {
	case DAV_LOCK_DIRECT:
	    /* Create and fill a dav_lock_discovery structure */

	    dp = apr_pcalloc(p, sizeof(*dp));
	    memcpy(dp, val.dptr + offset, sizeof(dp->f));
	    offset += sizeof(dp->f);
            dp->locktoken = apr_palloc(p, sizeof(*dp->locktoken));
            memcpy(dp->locktoken, val.dptr + offset, sizeof(*dp->locktoken));
            offset += sizeof(*dp->locktoken);
	    if (*(val.dptr + offset) == '\0') {
		++offset;
	    }
	    else {
		dp->owner = apr_pstrdup(p, val.dptr + offset);
		offset += strlen(dp->owner) + 1;
	    }

            if (*(val.dptr + offset) == '\0') {
                ++offset;
            } 
            else {
                dp->auth_user = apr_pstrdup(p, val.dptr + offset);
                offset += strlen(dp->auth_user) + 1;
            }

	    if (!dav_fs_lock_expired(dp->f.timeout)) {
		dp->next = *direct;
		*direct = dp;
	    }
	    else {
		need_save = DAV_TRUE;

		/* Remove timed-out locknull fm .locknull list */
		if (*key.dptr == DAV_TYPE_FNAME) {
		    const char *fname = key.dptr + 1;
		    apr_finfo_t finfo;

		    /* if we don't see the file, then it's a locknull */
		    if (apr_lstat(&finfo, fname, p) != 0) {
			if ((err = dav_fs_remove_locknull_member(p, fname, &buf)) != NULL) {
                            /* ### push a higher-level description? */
                            return err;
                        }
		    }
		}
	    }
	    break;

	case DAV_LOCK_INDIRECT:
	    /* Create and fill a dav_lock_indirect structure */

	    ip = apr_pcalloc(p, sizeof(*ip));
            ip->locktoken = apr_palloc(p, sizeof(*ip->locktoken));
	    memcpy(ip->locktoken, val.dptr + offset, sizeof(*ip->locktoken));
	    offset += sizeof(*ip->locktoken);
	    memcpy(&ip->timeout, val.dptr + offset, sizeof(ip->timeout));
	    offset += sizeof(ip->timeout);
	    ip->key.dsize = *((int *) (val.dptr + offset));	/* length of datum */
	    offset += sizeof(ip->key.dsize);
	    ip->key.dptr = apr_palloc(p, ip->key.dsize); 
	    memcpy(ip->key.dptr, val.dptr + offset, ip->key.dsize);
	    offset += ip->key.dsize;

	    if (!dav_fs_lock_expired(ip->timeout)) {
		ip->next = *indirect;
		*indirect = ip;
	    }
	    else {
		need_save = DAV_TRUE;
		/* A locknull resource will never be locked indirectly */
	    }

	    break;

	default:
	    (*dav_hooks_db_dbm.freedatum)(lockdb->info->db, val);

	    /* ### should use a computed_desc and insert corrupt token data */
	    --offset;
	    return dav_new_error(p,
				 HTTP_INTERNAL_SERVER_ERROR,
				 DAV_ERR_LOCK_CORRUPT_DB,
				 apr_psprintf(p,
					     "The lock database was found to "
					     "be corrupt. offset %i, c=%02x",
					     offset, val.dptr[offset]));
	}
    }

    (*dav_hooks_db_dbm.freedatum)(lockdb->info->db, val);

    /* Clean up this record if we found expired locks */
    /*
    ** ### shouldn't do this if we've been opened READONLY. elide the
    ** ### timed-out locks from the response, but don't save that info back
    */
    if (need_save == DAV_TRUE) {
	return dav_fs_save_lock_record(lockdb, key, *direct, *indirect);
    }

    return NULL;
}

/* resolve <indirect>, returning <*direct> */
static dav_error * dav_fs_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;
	
    if ((err = dav_fs_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_compare_opaquelocktoken(indirect->locktoken->uuid, 
					 dir->locktoken->uuid)) {
	    *direct = dir;
	    return NULL;
	}
    }

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

    /* ### use a different description and/or error ID? */
    return 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_fs_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_fs_get_supportedlock(void)
{
    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;

    return supported;
}

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

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

/*
** dav_fs_load_locknull_list:  Returns a dav_buffer dump of the locknull file
**    for the given directory.
*/
static dav_error * dav_fs_load_locknull_list(apr_pool_t *p, const char *dirpath,
					     dav_buffer *pbuf) 
{
    apr_finfo_t finfo;
    apr_file_t *file = NULL;
    dav_error *err = NULL;
    apr_ssize_t amt;

    dav_buffer_init(p, pbuf, dirpath);

    if (pbuf->buf[pbuf->cur_len - 1] == '/')
	pbuf->buf[--pbuf->cur_len] = '\0';

    dav_buffer_place(p, pbuf, "/" DAV_FS_STATE_DIR "/" DAV_FS_LOCK_NULL_FILE);

    /* reset this in case we leave w/o reading into the buffer */
    pbuf->cur_len = 0;

    if (apr_open(&file, pbuf->buf, APR_READ | APR_BINARY, APR_OS_DEFAULT,
                p) != APR_SUCCESS) {
	return NULL;
    }

    if (apr_getfileinfo(&finfo, file) != APR_SUCCESS) {
	err = dav_new_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
			    apr_psprintf(p,
					"Opened but could not stat file %s",
					pbuf->buf));
	goto loaderror;
    }

    dav_set_bufsize(p, pbuf, finfo.size);
    amt = finfo.size;
    if (apr_read(file, pbuf->buf, &amt) != APR_SUCCESS
        || amt != finfo.size) {
	err = dav_new_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
			    apr_psprintf(p,
					"Failure reading locknull file "
					"for %s", dirpath));

	/* just in case the caller disregards the returned error */
	pbuf->cur_len = 0;
	goto loaderror;
    }

  loaderror:
    apr_close(file);
    return err;
}

/*
** dav_fs_save_locknull_list:  Saves contents of pbuf into the
**    locknull file for dirpath.
*/
static dav_error * dav_fs_save_locknull_list(apr_pool_t *p, const char *dirpath,
					     dav_buffer *pbuf)
{
    const char *pathname;
    apr_file_t *file = NULL;
    dav_error *err = NULL;
    apr_ssize_t amt;

    if (pbuf->buf == NULL)
	return NULL;

    dav_fs_ensure_state_dir(p, dirpath);
    pathname = apr_pstrcat(p,
			  dirpath,
			  dirpath[strlen(dirpath) - 1] == '/' ? "" : "/",
			  DAV_FS_STATE_DIR "/" DAV_FS_LOCK_NULL_FILE,
			  NULL);

    if (pbuf->cur_len == 0) {
	/* delete the file if cur_len == 0 */
	if (remove(pathname) != 0) {
	    return dav_new_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
				 apr_psprintf(p,
					     "Error removing %s", pathname));
	}
	return NULL;
    }

    if (apr_open(&file, pathname,
                APR_WRITE | APR_CREATE | APR_TRUNCATE | APR_BINARY,
                APR_OS_DEFAULT, p) != APR_SUCCESS) {
	return dav_new_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
			     apr_psprintf(p,
					 "Error opening %s for writing",
					 pathname));
    }

    amt = pbuf->cur_len;
    if (apr_write(file, pbuf->buf, &amt) != APR_SUCCESS
        || amt != pbuf->cur_len) {
	err = dav_new_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
			    apr_psprintf(p,
					"Error writing %i bytes to %s",
					pbuf->cur_len, pathname));
    }

    apr_close(file);
    return err;
}

/*
** dav_fs_remove_locknull_member:  Removes filename from the locknull list
**    for directory path.
*/
static dav_error * dav_fs_remove_locknull_member(apr_pool_t *p,
                                                 const char *filename,
						 dav_buffer *pbuf)
{
    dav_error *err;
    size_t len;
    size_t scanlen;
    char *scan;
    const char *scanend;
    char *dirpath = apr_pstrdup(p, filename);
    char *fname = strrchr(dirpath, '/');
    int dirty = 0;

    if (fname != NULL)
	*fname++ = '\0';
    else
	fname = dirpath;
    len = strlen(fname) + 1;

    if ((err = dav_fs_load_locknull_list(p, dirpath, pbuf)) != NULL) {
	/* ### add a higher level description? */
	return err;
    }

    for (scan = pbuf->buf, scanend = scan + pbuf->cur_len;
	 scan < scanend;
	 scan += scanlen) {
	scanlen = strlen(scan) + 1;
	if (len == scanlen && memcmp(fname, scan, scanlen) == 0) {
	    pbuf->cur_len -= scanlen;
	    memmove(scan, scan + scanlen, scanend - (scan + scanlen));
	    dirty = 1;
	    break;
	}
    }

    if (dirty) {
	if ((err = dav_fs_save_locknull_list(p, dirpath, pbuf)) != NULL) {
	    /* ### add a higher level description? */
	    return err;
	}
    }

    return NULL;
}

/* Note: used by dav_fs_repos.c */
dav_error * dav_fs_get_locknull_members(
    const dav_resource *resource,
    dav_buffer *pbuf)
{
    const char *dirpath;

    dav_fs_dir_file_name(resource, &dirpath, NULL);
    return dav_fs_load_locknull_list(dav_fs_pool(resource), dirpath, pbuf);
}

/* ### fold into append_lock? */
/* ### take an optional buf parameter? */
static dav_error * dav_fs_add_locknull_state(
    dav_lockdb *lockdb,
    const dav_resource *resource)
{
    dav_buffer buf = { 0 };
    apr_pool_t *p = lockdb->info->pool;
    const char *dirpath;
    const char *fname;
    dav_error *err;

    dav_fs_dir_file_name(resource, &dirpath, &fname);

    if ((err = dav_fs_load_locknull_list(p, dirpath, &buf)) != NULL) {
        return dav_push_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
			      "Could not load .locknull file.", err);
    }

    dav_buffer_append(p, &buf, fname);
    buf.cur_len++;	/* we want the null-term here */

    if ((err = dav_fs_save_locknull_list(p, dirpath, &buf)) != NULL) {
        return dav_push_error(p, HTTP_INTERNAL_SERVER_ERROR, 0,
			      "Could not save .locknull file.", err);
    }

    return NULL;
}

/*
** dav_fs_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_fs_remove_locknull_state(
    dav_lockdb *lockdb,
    const dav_resource *resource)
{
    dav_buffer buf = { 0 };
    dav_error *err;
    apr_pool_t *p = lockdb->info->pool;
    const char *pathname = dav_fs_pathname(resource);

    if ((err = dav_fs_remove_locknull_member(p, pathname, &buf)) != NULL) {
	/* ### add a higher-level description? */
	return err;
    }

#ifndef WIN32
    {
	dav_lock_discovery *ld;
	dav_lock_indirect  *id;
	dav_datum key;

	/*
	** 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.
	*/
	key = dav_fs_build_fname_key(p, pathname);
	if ((err = dav_fs_load_lock_record(lockdb, key, DAV_CREATE_LIST,
					   &ld, &id)) != NULL) {
	    /* ### insert a higher-level error description */
	    return err;
	}

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

	key = dav_fs_build_key(p, resource);
	if ((err = dav_fs_save_lock_record(lockdb, key, ld, id)) != NULL) {
	    /* ### insert a higher-level error description */
	    return err;
        }
    }
#endif

    return NULL;
}

static dav_error * dav_fs_create_lock(dav_lockdb *lockdb,
				      const dav_resource *resource,
				      dav_lock **lock)
{
    dav_datum key;

    key = dav_fs_build_key(lockdb->info->pool, resource);

    *lock = dav_fs_alloc_lock(lockdb,
			      key,
			      NULL);

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

    return NULL;
}

static dav_error * dav_fs_get_locks(dav_lockdb *lockdb,
				    const dav_resource *resource,
				    int calltype,
				    dav_lock **locks)
{
    apr_pool_t *p = lockdb->info->pool;
    dav_datum key;
    dav_error *err;
    dav_lock *lock = NULL;
    dav_lock *newlock;
    dav_lock_discovery *dp;
    dav_lock_indirect *ip;

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

    key = dav_fs_build_key(p, resource);
    if ((err = dav_fs_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_fs_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_fs_alloc_lock(lockdb, ip->key, ip->locktoken);
	newlock->is_locknull = !resource->exists;

	if (calltype == DAV_GETLOCKS_RESOLVED) {
	    if ((err = dav_fs_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_fs_find_lock(dav_lockdb *lockdb,
				    const dav_resource *resource,
				    const dav_locktoken *locktoken,
				    int partial_ok,
				    dav_lock **lock)
{
    dav_error *err;
    dav_datum key;
    dav_lock_discovery *dp;
    dav_lock_indirect *ip;

    *lock = NULL;

    key = dav_fs_build_key(lockdb->info->pool, resource);
    if ((err = dav_fs_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_compare_opaquelocktoken(locktoken->uuid,
					 dp->locktoken->uuid)) {
	    *lock = dav_fs_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_compare_opaquelocktoken(locktoken->uuid,
					 ip->locktoken->uuid)) {
	    *lock = dav_fs_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_fs_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_fs_has_locks(dav_lockdb *lockdb,
				    const dav_resource *resource,
				    int *locks_present)
{
    dav_error *err;
    dav_datum key;

    *locks_present = 0;

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

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

    key = dav_fs_build_key(lockdb->info->pool, resource);

    *locks_present = (*dav_hooks_db_dbm.exists)(lockdb->info->db, key);

    return NULL;
}

static dav_error * dav_fs_append_locks(dav_lockdb *lockdb,
				       const dav_resource *resource,
				       int make_indirect,
				       const dav_lock *lock)
{
    apr_pool_t *p = lockdb->info->pool;
    dav_error *err;
    dav_lock_indirect *ip;
    dav_lock_discovery *dp;
    dav_datum key;

    key = dav_fs_build_key(lockdb->info->pool, resource);
    if ((err = dav_fs_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_fs_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_fs_add_locknull_state(lockdb, resource)) != NULL) {
	/* ### maybe add a higher-level description */
	return err;
    }

    return NULL;
}

static dav_error * dav_fs_remove_lock(dav_lockdb *lockdb,
				      const dav_resource *resource,
				      const dav_locktoken *locktoken)
{
    dav_error *err;
    dav_buffer buf = { 0 };
    dav_lock_discovery *dh = NULL;
    dav_lock_indirect *ih = NULL;
    dav_datum key;

    key = dav_fs_build_key(lockdb->info->pool, resource);

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

	if ((err = dav_fs_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_compare_opaquelocktoken(locktoken->uuid,
					    dp->locktoken->uuid) == 0) {
		if (dprev)
		    dprev->next = dp->next;
		else
		    dh = dh->next;
	    }
	    dprev = dp;
	}

	for (ip = ih; ip != NULL; ip = ip->next) {
	    if (dav_compare_opaquelocktoken(locktoken->uuid,
					    ip->locktoken->uuid) == 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_fs_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.
    **
    ** Note: remove_locknull_state() attempts to convert a locknull member
    **       to a real member. In this case, all locks are gone, so the
    **       locknull resource returns to the null state (ie. doesn't exist),
    **       so there is no need to update the lockdb (and it won't find
    **       any because a precondition is that none exist).
    */
    if (!resource->exists && dh == NULL && ih == NULL
	&& (err = dav_fs_remove_locknull_member(lockdb->info->pool,
						dav_fs_pathname(resource),
						&buf)) != NULL) {
	/* ### maybe add a higher-level description */
	return err;
    }

    return NULL;
}

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

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

    return dirty;
}

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

    *locks = NULL;

    key = dav_fs_build_key(lockdb->info->pool, resource);
    if ((err = dav_fs_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_fs_do_refresh(dp_scan, ltl, new_time)) {
	    /* the lock was refreshed. return the lock. */
	    newlock = dav_fs_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_fs_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_fs_resolve(lockdb, ip, &dp_scan,
				  &ref_dp, &ref_ip)) != NULL) {
	    /* ### push a higher-level desc? */
	    return err;
	}
	if (dav_fs_do_refresh(dp_scan, ltl, new_time)) {
	    /* the lock was refreshed. return the lock. */
	    newlock = dav_fs_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_fs_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_hooks_locks_fs =
{
    dav_fs_get_supportedlock,
    dav_fs_parse_locktoken,
    dav_fs_format_locktoken,
    dav_fs_compare_locktoken,
    dav_fs_open_lockdb,
    dav_fs_close_lockdb,
    dav_fs_remove_locknull_state,
    dav_fs_create_lock,
    dav_fs_get_locks,
    dav_fs_find_lock,
    dav_fs_has_locks,
    dav_fs_append_locks,
    dav_fs_remove_lock,
    dav_fs_refresh_locks,
    NULL, /* get_resource */
};