]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/accesslog.c
ITS#8752 additional debug info, thread ID of rmutex lockers
[openldap] / servers / slapd / overlays / accesslog.c
1 /* accesslog.c - log operations for audit/history purposes */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2005-2017 The OpenLDAP Foundation.
6  * Portions copyright 2004-2005 Symas Corporation.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by Howard Chu for inclusion in
19  * OpenLDAP Software.
20  */
21
22 #include "portable.h"
23
24 #ifdef SLAPD_OVER_ACCESSLOG
25
26 #include <stdio.h>
27
28 #include <ac/string.h>
29 #include <ac/ctype.h>
30
31 #include "slap.h"
32 #include "config.h"
33 #include "lutil.h"
34 #include "ldap_rq.h"
35
36 #define LOG_OP_ADD      0x001
37 #define LOG_OP_DELETE   0x002
38 #define LOG_OP_MODIFY   0x004
39 #define LOG_OP_MODRDN   0x008
40 #define LOG_OP_COMPARE  0x010
41 #define LOG_OP_SEARCH   0x020
42 #define LOG_OP_BIND     0x040
43 #define LOG_OP_UNBIND   0x080
44 #define LOG_OP_ABANDON  0x100
45 #define LOG_OP_EXTENDED 0x200
46 #define LOG_OP_UNKNOWN  0x400
47
48 #define LOG_OP_WRITES   (LOG_OP_ADD|LOG_OP_DELETE|LOG_OP_MODIFY|LOG_OP_MODRDN)
49 #define LOG_OP_READS    (LOG_OP_COMPARE|LOG_OP_SEARCH)
50 #define LOG_OP_SESSION  (LOG_OP_BIND|LOG_OP_UNBIND|LOG_OP_ABANDON)
51 #define LOG_OP_ALL              (LOG_OP_READS|LOG_OP_WRITES|LOG_OP_SESSION| \
52         LOG_OP_EXTENDED|LOG_OP_UNKNOWN)
53
54 typedef struct log_attr {
55         struct log_attr *next;
56         AttributeDescription *attr;
57 } log_attr;
58
59 typedef struct log_base {
60         struct log_base *lb_next;
61         slap_mask_t lb_ops;
62         struct berval lb_base;
63         struct berval lb_line;
64 } log_base;
65
66 typedef struct log_info {
67         BackendDB *li_db;
68         struct berval li_db_suffix;
69         slap_mask_t li_ops;
70         int li_age;
71         int li_cycle;
72         struct re_s *li_task;
73         Filter *li_oldf;
74         Entry *li_old;
75         log_attr *li_oldattrs;
76         struct berval li_uuid;
77         int li_success;
78         log_base *li_bases;
79         ldap_pvt_thread_rmutex_t li_op_rmutex;
80         ldap_pvt_thread_mutex_t li_log_mutex;
81 } log_info;
82
83 static ConfigDriver log_cf_gen;
84
85 enum {
86         LOG_DB = 1,
87         LOG_OPS,
88         LOG_PURGE,
89         LOG_SUCCESS,
90         LOG_OLD,
91         LOG_OLDATTR,
92         LOG_BASE
93 };
94
95 static ConfigTable log_cfats[] = {
96         { "logdb", "suffix", 2, 2, 0, ARG_DN|ARG_MAGIC|LOG_DB,
97                 log_cf_gen, "( OLcfgOvAt:4.1 NAME 'olcAccessLogDB' "
98                         "DESC 'Suffix of database for log content' "
99                         "SUP distinguishedName SINGLE-VALUE )", NULL, NULL },
100         { "logops", "op|writes|reads|session|all", 2, 0, 0,
101                 ARG_MAGIC|LOG_OPS,
102                 log_cf_gen, "( OLcfgOvAt:4.2 NAME 'olcAccessLogOps' "
103                         "DESC 'Operation types to log' "
104                         "EQUALITY caseIgnoreMatch "
105                         "SYNTAX OMsDirectoryString )", NULL, NULL },
106         { "logpurge", "age> <interval", 3, 3, 0, ARG_MAGIC|LOG_PURGE,
107                 log_cf_gen, "( OLcfgOvAt:4.3 NAME 'olcAccessLogPurge' "
108                         "DESC 'Log cleanup parameters' "
109                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
110         { "logsuccess", NULL, 2, 2, 0, ARG_MAGIC|ARG_ON_OFF|LOG_SUCCESS,
111                 log_cf_gen, "( OLcfgOvAt:4.4 NAME 'olcAccessLogSuccess' "
112                         "DESC 'Log successful ops only' "
113                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
114         { "logold", "filter", 2, 2, 0, ARG_MAGIC|LOG_OLD,
115                 log_cf_gen, "( OLcfgOvAt:4.5 NAME 'olcAccessLogOld' "
116                         "DESC 'Log old values when modifying entries matching the filter' "
117                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
118         { "logoldattr", "attrs", 2, 0, 0, ARG_MAGIC|LOG_OLDATTR,
119                 log_cf_gen, "( OLcfgOvAt:4.6 NAME 'olcAccessLogOldAttr' "
120                         "DESC 'Log old values of these attributes even if unmodified' "
121                         "EQUALITY caseIgnoreMatch "
122                         "SYNTAX OMsDirectoryString )", NULL, NULL },
123         { "logbase", "op|writes|reads|session|all< <baseDN", 3, 3, 0,
124                 ARG_MAGIC|LOG_BASE,
125                 log_cf_gen, "( OLcfgOvAt:4.7 NAME 'olcAccessLogBase' "
126                         "DESC 'Operation types to log under a specific branch' "
127                         "EQUALITY caseIgnoreMatch "
128                         "SYNTAX OMsDirectoryString )", NULL, NULL },
129         { NULL }
130 };
131
132 static ConfigOCs log_cfocs[] = {
133         { "( OLcfgOvOc:4.1 "
134                 "NAME 'olcAccessLogConfig' "
135                 "DESC 'Access log configuration' "
136                 "SUP olcOverlayConfig "
137                 "MUST olcAccessLogDB "
138                 "MAY ( olcAccessLogOps $ olcAccessLogPurge $ olcAccessLogSuccess $ "
139                         "olcAccessLogOld $ olcAccessLogOldAttr $ olcAccessLogBase ) )",
140                         Cft_Overlay, log_cfats },
141         { NULL }
142 };
143
144 static slap_verbmasks logops[] = {
145         { BER_BVC("all"),               LOG_OP_ALL },
146         { BER_BVC("writes"),    LOG_OP_WRITES },
147         { BER_BVC("session"),   LOG_OP_SESSION },
148         { BER_BVC("reads"),             LOG_OP_READS },
149         { BER_BVC("add"),               LOG_OP_ADD },
150         { BER_BVC("delete"),    LOG_OP_DELETE },
151         { BER_BVC("modify"),    LOG_OP_MODIFY },
152         { BER_BVC("modrdn"),    LOG_OP_MODRDN },
153         { BER_BVC("compare"),   LOG_OP_COMPARE },
154         { BER_BVC("search"),    LOG_OP_SEARCH },
155         { BER_BVC("bind"),              LOG_OP_BIND },
156         { BER_BVC("unbind"),    LOG_OP_UNBIND },
157         { BER_BVC("abandon"),   LOG_OP_ABANDON },
158         { BER_BVC("extended"),  LOG_OP_EXTENDED },
159         { BER_BVC("unknown"),   LOG_OP_UNKNOWN },
160         { BER_BVNULL, 0 }
161 };
162
163 /* Start with "add" in logops */
164 #define EN_OFFSET       4
165
166 enum {
167         LOG_EN_ADD = 0,
168         LOG_EN_DELETE,
169         LOG_EN_MODIFY,
170         LOG_EN_MODRDN,
171         LOG_EN_COMPARE,
172         LOG_EN_SEARCH,
173         LOG_EN_BIND,
174         LOG_EN_UNBIND,
175         LOG_EN_ABANDON,
176         LOG_EN_EXTENDED,
177         LOG_EN_UNKNOWN,
178         LOG_EN__COUNT
179 };
180
181 static ObjectClass *log_ocs[LOG_EN__COUNT], *log_container,
182         *log_oc_read, *log_oc_write;
183
184 #define LOG_SCHEMA_ROOT "1.3.6.1.4.1.4203.666.11.5"
185
186 #define LOG_SCHEMA_AT LOG_SCHEMA_ROOT ".1"
187 #define LOG_SCHEMA_OC LOG_SCHEMA_ROOT ".2"
188 #define LOG_SCHEMA_SYN LOG_SCHEMA_ROOT ".3"
189
190 static AttributeDescription *ad_reqDN, *ad_reqStart, *ad_reqEnd, *ad_reqType,
191         *ad_reqSession, *ad_reqResult, *ad_reqAuthzID, *ad_reqControls,
192         *ad_reqRespControls, *ad_reqMethod, *ad_reqAssertion, *ad_reqNewRDN,
193         *ad_reqNewSuperior, *ad_reqDeleteOldRDN, *ad_reqMod,
194         *ad_reqScope, *ad_reqFilter, *ad_reqAttr, *ad_reqEntries,
195         *ad_reqSizeLimit, *ad_reqTimeLimit, *ad_reqAttrsOnly, *ad_reqData,
196         *ad_reqId, *ad_reqMessage, *ad_reqVersion, *ad_reqDerefAliases,
197         *ad_reqReferral, *ad_reqOld, *ad_auditContext, *ad_reqEntryUUID;
198
199 static int
200 logSchemaControlValidate(
201         Syntax          *syntax,
202         struct berval   *val );
203
204 char    *mrControl[] = {
205         "objectIdentifierFirstComponentMatch",
206         NULL
207 };
208
209 static struct {
210         char                    *oid;
211         slap_syntax_defs_rec    syn;
212         char                    **mrs;
213 } lsyntaxes[] = {
214         { LOG_SCHEMA_SYN ".1" ,
215                 { "( " LOG_SCHEMA_SYN ".1 DESC 'Control' )",
216                         SLAP_SYNTAX_HIDE,
217                         NULL,
218                         logSchemaControlValidate,
219                         NULL },
220                 mrControl },
221         { NULL }
222 };
223
224 static struct {
225         char *at;
226         AttributeDescription **ad;
227 } lattrs[] = {
228         { "( " LOG_SCHEMA_AT ".1 NAME 'reqDN' "
229                 "DESC 'Target DN of request' "
230                 "EQUALITY distinguishedNameMatch "
231                 "SYNTAX OMsDN "
232                 "SINGLE-VALUE )", &ad_reqDN },
233         { "( " LOG_SCHEMA_AT ".2 NAME 'reqStart' "
234                 "DESC 'Start time of request' "
235                 "EQUALITY generalizedTimeMatch "
236                 "ORDERING generalizedTimeOrderingMatch "
237                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
238                 "SINGLE-VALUE )", &ad_reqStart },
239         { "( " LOG_SCHEMA_AT ".3 NAME 'reqEnd' "
240                 "DESC 'End time of request' "
241                 "EQUALITY generalizedTimeMatch "
242                 "ORDERING generalizedTimeOrderingMatch "
243                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
244                 "SINGLE-VALUE )", &ad_reqEnd },
245         { "( " LOG_SCHEMA_AT ".4 NAME 'reqType' "
246                 "DESC 'Type of request' "
247                 "EQUALITY caseIgnoreMatch "
248                 "SYNTAX OMsDirectoryString "
249                 "SINGLE-VALUE )", &ad_reqType },
250         { "( " LOG_SCHEMA_AT ".5 NAME 'reqSession' "
251                 "DESC 'Session ID of request' "
252                 "EQUALITY caseIgnoreMatch "
253                 "SYNTAX OMsDirectoryString "
254                 "SINGLE-VALUE )", &ad_reqSession },
255         { "( " LOG_SCHEMA_AT ".6 NAME 'reqAuthzID' "
256                 "DESC 'Authorization ID of requestor' "
257                 "EQUALITY distinguishedNameMatch "
258                 "SYNTAX OMsDN "
259                 "SINGLE-VALUE )", &ad_reqAuthzID },
260         { "( " LOG_SCHEMA_AT ".7 NAME 'reqResult' "
261                 "DESC 'Result code of request' "
262                 "EQUALITY integerMatch "
263                 "ORDERING integerOrderingMatch "
264                 "SYNTAX OMsInteger "
265                 "SINGLE-VALUE )", &ad_reqResult },
266         { "( " LOG_SCHEMA_AT ".8 NAME 'reqMessage' "
267                 "DESC 'Error text of request' "
268                 "EQUALITY caseIgnoreMatch "
269                 "SUBSTR caseIgnoreSubstringsMatch "
270                 "SYNTAX OMsDirectoryString "
271                 "SINGLE-VALUE )", &ad_reqMessage },
272         { "( " LOG_SCHEMA_AT ".9 NAME 'reqReferral' "
273                 "DESC 'Referrals returned for request' "
274                 "SUP labeledURI )", &ad_reqReferral },
275         { "( " LOG_SCHEMA_AT ".10 NAME 'reqControls' "
276                 "DESC 'Request controls' "
277                 "EQUALITY objectIdentifierFirstComponentMatch "
278                 "SYNTAX " LOG_SCHEMA_SYN ".1 "
279                 "X-ORDERED 'VALUES' )", &ad_reqControls },
280         { "( " LOG_SCHEMA_AT ".11 NAME 'reqRespControls' "
281                 "DESC 'Response controls of request' "
282                 "EQUALITY objectIdentifierFirstComponentMatch "
283                 "SYNTAX " LOG_SCHEMA_SYN ".1 "
284                 "X-ORDERED 'VALUES' )", &ad_reqRespControls },
285         { "( " LOG_SCHEMA_AT ".12 NAME 'reqId' "
286                 "DESC 'ID of Request to Abandon' "
287                 "EQUALITY integerMatch "
288                 "ORDERING integerOrderingMatch "
289                 "SYNTAX OMsInteger "
290                 "SINGLE-VALUE )", &ad_reqId },
291         { "( " LOG_SCHEMA_AT ".13 NAME 'reqVersion' "
292                 "DESC 'Protocol version of Bind request' "
293                 "EQUALITY integerMatch "
294                 "ORDERING integerOrderingMatch "
295                 "SYNTAX OMsInteger "
296                 "SINGLE-VALUE )", &ad_reqVersion },
297         { "( " LOG_SCHEMA_AT ".14 NAME 'reqMethod' "
298                 "DESC 'Bind method of request' "
299                 "EQUALITY caseIgnoreMatch "
300                 "SYNTAX OMsDirectoryString "
301                 "SINGLE-VALUE )", &ad_reqMethod },
302         { "( " LOG_SCHEMA_AT ".15 NAME 'reqAssertion' "
303                 "DESC 'Compare Assertion of request' "
304                 "SYNTAX OMsDirectoryString "
305                 "SINGLE-VALUE )", &ad_reqAssertion },
306         { "( " LOG_SCHEMA_AT ".16 NAME 'reqMod' "
307                 "DESC 'Modifications of request' "
308                 "EQUALITY octetStringMatch "
309                 "SUBSTR octetStringSubstringsMatch "
310                 "SYNTAX OMsOctetString )", &ad_reqMod },
311         { "( " LOG_SCHEMA_AT ".17 NAME 'reqOld' "
312                 "DESC 'Old values of entry before request completed' "
313                 "EQUALITY octetStringMatch "
314                 "SUBSTR octetStringSubstringsMatch "
315                 "SYNTAX OMsOctetString )", &ad_reqOld },
316         { "( " LOG_SCHEMA_AT ".18 NAME 'reqNewRDN' "
317                 "DESC 'New RDN of request' "
318                 "EQUALITY distinguishedNameMatch "
319                 "SYNTAX OMsDN "
320                 "SINGLE-VALUE )", &ad_reqNewRDN },
321         { "( " LOG_SCHEMA_AT ".19 NAME 'reqDeleteOldRDN' "
322                 "DESC 'Delete old RDN' "
323                 "EQUALITY booleanMatch "
324                 "SYNTAX OMsBoolean "
325                 "SINGLE-VALUE )", &ad_reqDeleteOldRDN },
326         { "( " LOG_SCHEMA_AT ".20 NAME 'reqNewSuperior' "
327                 "DESC 'New superior DN of request' "
328                 "EQUALITY distinguishedNameMatch "
329                 "SYNTAX OMsDN "
330                 "SINGLE-VALUE )", &ad_reqNewSuperior },
331         { "( " LOG_SCHEMA_AT ".21 NAME 'reqScope' "
332                 "DESC 'Scope of request' "
333                 "EQUALITY caseIgnoreMatch "
334                 "SYNTAX OMsDirectoryString "
335                 "SINGLE-VALUE )", &ad_reqScope },
336         { "( " LOG_SCHEMA_AT ".22 NAME 'reqDerefAliases' "
337                 "DESC 'Disposition of Aliases in request' "
338                 "EQUALITY caseIgnoreMatch "
339                 "SYNTAX OMsDirectoryString "
340                 "SINGLE-VALUE )", &ad_reqDerefAliases },
341         { "( " LOG_SCHEMA_AT ".23 NAME 'reqAttrsOnly' "
342                 "DESC 'Attributes and values of request' "
343                 "EQUALITY booleanMatch "
344                 "SYNTAX OMsBoolean "
345                 "SINGLE-VALUE )", &ad_reqAttrsOnly },
346         { "( " LOG_SCHEMA_AT ".24 NAME 'reqFilter' "
347                 "DESC 'Filter of request' "
348                 "EQUALITY caseIgnoreMatch "
349                 "SUBSTR caseIgnoreSubstringsMatch "
350                 "SYNTAX OMsDirectoryString "
351                 "SINGLE-VALUE )", &ad_reqFilter },
352         { "( " LOG_SCHEMA_AT ".25 NAME 'reqAttr' "
353                 "DESC 'Attributes of request' "
354                 "EQUALITY caseIgnoreMatch "
355                 "SYNTAX OMsDirectoryString )", &ad_reqAttr },
356         { "( " LOG_SCHEMA_AT ".26 NAME 'reqSizeLimit' "
357                 "DESC 'Size limit of request' "
358                 "EQUALITY integerMatch "
359                 "ORDERING integerOrderingMatch "
360                 "SYNTAX OMsInteger "
361                 "SINGLE-VALUE )", &ad_reqSizeLimit },
362         { "( " LOG_SCHEMA_AT ".27 NAME 'reqTimeLimit' "
363                 "DESC 'Time limit of request' "
364                 "EQUALITY integerMatch "
365                 "ORDERING integerOrderingMatch "
366                 "SYNTAX OMsInteger "
367                 "SINGLE-VALUE )", &ad_reqTimeLimit },
368         { "( " LOG_SCHEMA_AT ".28 NAME 'reqEntries' "
369                 "DESC 'Number of entries returned' "
370                 "EQUALITY integerMatch "
371                 "ORDERING integerOrderingMatch "
372                 "SYNTAX OMsInteger "
373                 "SINGLE-VALUE )", &ad_reqEntries },
374         { "( " LOG_SCHEMA_AT ".29 NAME 'reqData' "
375                 "DESC 'Data of extended request' "
376                 "EQUALITY octetStringMatch "
377                 "SUBSTR octetStringSubstringsMatch "
378                 "SYNTAX OMsOctetString "
379                 "SINGLE-VALUE )", &ad_reqData },
380
381         /*
382          * from <draft-chu-ldap-logschema-01.txt>:
383          *
384
385    ( LOG_SCHEMA_AT .30 NAME 'auditContext'
386    DESC 'DN of auditContainer'
387    EQUALITY distinguishedNameMatch
388    SYNTAX 1.3.6.1.4.1.1466.115.121.1.12
389    SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation )
390
391          * - removed EQUALITY matchingRule
392          * - changed directoryOperation in dSAOperation
393          */
394         { "( " LOG_SCHEMA_AT ".30 NAME 'auditContext' "
395                 "DESC 'DN of auditContainer' "
396                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 "
397                 "SINGLE-VALUE "
398                 "NO-USER-MODIFICATION "
399                 "USAGE dSAOperation )", &ad_auditContext },
400
401         /*
402          * ITS#6656
403          */
404         { "( " LOG_SCHEMA_AT ".31 NAME 'reqEntryUUID' "
405                 "DESC 'UUID of entry' "
406                 "EQUALITY UUIDMatch "
407                 "ORDERING UUIDOrderingMatch "
408                 "SYNTAX 1.3.6.1.1.16.1 "
409                 "SINGLE-VALUE )", &ad_reqEntryUUID },
410         { NULL, NULL }
411 };
412
413 static struct {
414         char *ot;
415         ObjectClass **oc;
416 } locs[] = {
417         { "( " LOG_SCHEMA_OC ".0 NAME 'auditContainer' "
418                 "DESC 'AuditLog container' "
419                 "SUP top STRUCTURAL "
420                 "MAY ( cn $ reqStart $ reqEnd ) )", &log_container },
421         { "( " LOG_SCHEMA_OC ".1 NAME 'auditObject' "
422                 "DESC 'OpenLDAP request auditing' "
423                 "SUP top STRUCTURAL "
424                 "MUST ( reqStart $ reqType $ reqSession ) "
425                 "MAY ( reqDN $ reqAuthzID $ reqControls $ reqRespControls $ reqEnd $ "
426                         "reqResult $ reqMessage $ reqReferral $ reqEntryUUID ) )",
427                                 &log_ocs[LOG_EN_UNBIND] },
428         { "( " LOG_SCHEMA_OC ".2 NAME 'auditReadObject' "
429                 "DESC 'OpenLDAP read request record' "
430                 "SUP auditObject STRUCTURAL )", &log_oc_read },
431         { "( " LOG_SCHEMA_OC ".3 NAME 'auditWriteObject' "
432                 "DESC 'OpenLDAP write request record' "
433                 "SUP auditObject STRUCTURAL )", &log_oc_write },
434         { "( " LOG_SCHEMA_OC ".4 NAME 'auditAbandon' "
435                 "DESC 'Abandon operation' "
436                 "SUP auditObject STRUCTURAL "
437                 "MUST reqId )", &log_ocs[LOG_EN_ABANDON] },
438         { "( " LOG_SCHEMA_OC ".5 NAME 'auditAdd' "
439                 "DESC 'Add operation' "
440                 "SUP auditWriteObject STRUCTURAL "
441                 "MUST reqMod )", &log_ocs[LOG_EN_ADD] },
442         { "( " LOG_SCHEMA_OC ".6 NAME 'auditBind' "
443                 "DESC 'Bind operation' "
444                 "SUP auditObject STRUCTURAL "
445                 "MUST ( reqVersion $ reqMethod ) )", &log_ocs[LOG_EN_BIND] },
446         { "( " LOG_SCHEMA_OC ".7 NAME 'auditCompare' "
447                 "DESC 'Compare operation' "
448                 "SUP auditReadObject STRUCTURAL "
449                 "MUST reqAssertion )", &log_ocs[LOG_EN_COMPARE] },
450         { "( " LOG_SCHEMA_OC ".8 NAME 'auditDelete' "
451                 "DESC 'Delete operation' "
452                 "SUP auditWriteObject STRUCTURAL "
453                 "MAY reqOld )", &log_ocs[LOG_EN_DELETE] },
454         { "( " LOG_SCHEMA_OC ".9 NAME 'auditModify' "
455                 "DESC 'Modify operation' "
456                 "SUP auditWriteObject STRUCTURAL "
457                 "MAY reqOld MUST reqMod )", &log_ocs[LOG_EN_MODIFY] },
458         { "( " LOG_SCHEMA_OC ".10 NAME 'auditModRDN' "
459                 "DESC 'ModRDN operation' "
460                 "SUP auditWriteObject STRUCTURAL "
461                 "MUST ( reqNewRDN $ reqDeleteOldRDN ) "
462                 "MAY ( reqNewSuperior $ reqMod $ reqOld ) )", &log_ocs[LOG_EN_MODRDN] },
463         { "( " LOG_SCHEMA_OC ".11 NAME 'auditSearch' "
464                 "DESC 'Search operation' "
465                 "SUP auditReadObject STRUCTURAL "
466                 "MUST ( reqScope $ reqDerefAliases $ reqAttrsonly ) "
467                 "MAY ( reqFilter $ reqAttr $ reqEntries $ reqSizeLimit $ "
468                         "reqTimeLimit ) )", &log_ocs[LOG_EN_SEARCH] },
469         { "( " LOG_SCHEMA_OC ".12 NAME 'auditExtended' "
470                 "DESC 'Extended operation' "
471                 "SUP auditObject STRUCTURAL "
472                 "MAY reqData )", &log_ocs[LOG_EN_EXTENDED] },
473         { NULL, NULL }
474 };
475
476 #define RDNEQ   "reqStart="
477
478 /* Our time intervals are of the form [ddd+]hh:mm[:ss]
479  * If a field is present, it must be two digits. (Except for
480  * days, which can be arbitrary width.)
481  */
482 static int
483 log_age_parse(char *agestr)
484 {
485         int t1, t2;
486         int gotdays = 0;
487         char *endptr;
488
489         t1 = strtol( agestr, &endptr, 10 );
490         /* Is there a days delimiter? */
491         if ( *endptr == '+' ) {
492                 /* 32 bit time only covers about 68 years */
493                 if ( t1 < 0 || t1 > 25000 )
494                         return -1;
495                 t1 *= 24;
496                 gotdays = 1;
497                 agestr = endptr + 1;
498         } else {
499                 if ( agestr[2] != ':' ) {
500                         /* No valid delimiter found, fail */
501                         return -1;
502                 }
503                 t1 *= 60;
504                 agestr += 3;
505         }
506
507         t2 = atoi( agestr );
508         t1 += t2;
509
510         if ( agestr[2] ) {
511                 /* if there's a delimiter, it can only be a colon */
512                 if ( agestr[2] != ':' )
513                         return -1;
514         } else {
515                 /* If we're at the end of the string, and we started with days,
516                  * fail because we expected to find minutes too.
517                  */
518                 return gotdays ? -1 : t1 * 60;
519         }
520
521         agestr += 3;
522         t2 = atoi( agestr );
523
524         /* last field can only be seconds */
525         if ( agestr[2] && ( agestr[2] != ':' || !gotdays ))
526                 return -1;
527         t1 *= 60;
528         t1 += t2;
529
530         if ( agestr[2] ) {
531                 agestr += 3;
532                 if ( agestr[2] )
533                         return -1;
534                 t1 *= 60;
535                 t1 += atoi( agestr );
536         } else if ( gotdays ) {
537                 /* only got days+hh:mm */
538                 t1 *= 60;
539         }
540         return t1;
541 }
542
543 static void
544 log_age_unparse( int age, struct berval *agebv, size_t size )
545 {
546         int dd, hh, mm, ss, len;
547         char *ptr;
548
549         assert( size > 0 );
550
551         ss = age % 60;
552         age /= 60;
553         mm = age % 60;
554         age /= 60;
555         hh = age % 24;
556         age /= 24;
557         dd = age;
558
559         ptr = agebv->bv_val;
560
561         if ( dd ) {
562                 len = snprintf( ptr, size, "%d+", dd );
563                 assert( len >= 0 && (unsigned) len < size );
564                 size -= len;
565                 ptr += len;
566         }
567         len = snprintf( ptr, size, "%02d:%02d", hh, mm );
568         assert( len >= 0 && (unsigned) len < size );
569         size -= len;
570         ptr += len;
571         if ( ss ) {
572                 len = snprintf( ptr, size, ":%02d", ss );
573                 assert( len >= 0 && (unsigned) len < size );
574                 size -= len;
575                 ptr += len;
576         }
577
578         agebv->bv_len = ptr - agebv->bv_val;
579 }
580
581 static slap_callback nullsc;
582
583 #define PURGE_INCREMENT 100
584
585 typedef struct purge_data {
586         int slots;
587         int used;
588         BerVarray dn;
589         BerVarray ndn;
590         struct berval csn;      /* an arbitrary old CSN */
591 } purge_data;
592
593 static int
594 log_old_lookup( Operation *op, SlapReply *rs )
595 {
596         purge_data *pd = op->o_callback->sc_private;
597         Attribute *a;
598
599         if ( rs->sr_type != REP_SEARCH) return 0;
600
601         if ( slapd_shutdown ) return 0;
602
603         /* Remember max CSN: should always be the last entry
604          * seen, since log entries are ordered chronologically...
605          */
606         a = attr_find( rs->sr_entry->e_attrs,
607                 slap_schema.si_ad_entryCSN );
608         if ( a ) {
609                 ber_len_t len = a->a_nvals[0].bv_len;
610                 /* Paranoid len check, normalized CSNs are always the same length */
611                 if ( len > LDAP_PVT_CSNSTR_BUFSIZE )
612                         len = LDAP_PVT_CSNSTR_BUFSIZE;
613                 if ( memcmp( a->a_nvals[0].bv_val, pd->csn.bv_val, len ) > 0 ) {
614                         AC_MEMCPY( pd->csn.bv_val, a->a_nvals[0].bv_val, len );
615                         pd->csn.bv_len = len;
616                 }
617         }
618         if ( pd->used >= pd->slots ) {
619                 pd->slots += PURGE_INCREMENT;
620                 pd->dn = ch_realloc( pd->dn, pd->slots * sizeof( struct berval ));
621                 pd->ndn = ch_realloc( pd->ndn, pd->slots * sizeof( struct berval ));
622         }
623         ber_dupbv( &pd->dn[pd->used], &rs->sr_entry->e_name );
624         ber_dupbv( &pd->ndn[pd->used], &rs->sr_entry->e_nname );
625         pd->used++;
626         return 0;
627 }
628
629 /* Periodically search for old entries in the log database and delete them */
630 static void *
631 accesslog_purge( void *ctx, void *arg )
632 {
633         struct re_s *rtask = arg;
634         struct log_info *li = rtask->arg;
635
636         Connection conn = {0};
637         OperationBuffer opbuf;
638         Operation *op;
639         SlapReply rs = {REP_RESULT};
640         slap_callback cb = { NULL, log_old_lookup, NULL, NULL, NULL };
641         Filter f;
642         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
643         purge_data pd = {0};
644         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE];
645         char csnbuf[LDAP_PVT_CSNSTR_BUFSIZE];
646         time_t old = slap_get_time();
647
648         connection_fake_init( &conn, &opbuf, ctx );
649         op = &opbuf.ob_op;
650
651         f.f_choice = LDAP_FILTER_LE;
652         f.f_ava = &ava;
653         f.f_next = NULL;
654
655         ava.aa_desc = ad_reqStart;
656         ava.aa_value.bv_val = timebuf;
657         ava.aa_value.bv_len = sizeof(timebuf);
658
659         old -= li->li_age;
660         slap_timestamp( &old, &ava.aa_value );
661
662         op->o_tag = LDAP_REQ_SEARCH;
663         op->o_bd = li->li_db;
664         op->o_dn = li->li_db->be_rootdn;
665         op->o_ndn = li->li_db->be_rootndn;
666         op->o_req_dn = li->li_db->be_suffix[0];
667         op->o_req_ndn = li->li_db->be_nsuffix[0];
668         op->o_callback = &cb;
669         op->ors_scope = LDAP_SCOPE_ONELEVEL;
670         op->ors_deref = LDAP_DEREF_NEVER;
671         op->ors_tlimit = SLAP_NO_LIMIT;
672         op->ors_slimit = SLAP_NO_LIMIT;
673         op->ors_filter = &f;
674         filter2bv_x( op, &f, &op->ors_filterstr );
675         op->ors_attrs = slap_anlist_no_attrs;
676         op->ors_attrsonly = 1;
677         
678         pd.csn.bv_len = sizeof( csnbuf );
679         pd.csn.bv_val = csnbuf;
680         csnbuf[0] = '\0';
681         cb.sc_private = &pd;
682
683         op->o_bd->be_search( op, &rs );
684         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
685
686         if ( pd.used ) {
687                 int i;
688
689                 /* delete the expired entries */
690                 op->o_tag = LDAP_REQ_DELETE;
691                 op->o_callback = &nullsc;
692                 op->o_csn = pd.csn;
693                 op->o_dont_replicate = 1;
694
695                 for (i=0; i<pd.used; i++) {
696                         op->o_req_dn = pd.dn[i];
697                         op->o_req_ndn = pd.ndn[i];
698                         if ( !slapd_shutdown ) {
699                                 rs_reinit( &rs, REP_RESULT );
700                                 op->o_bd->be_delete( op, &rs );
701                         }
702                         ch_free( pd.ndn[i].bv_val );
703                         ch_free( pd.dn[i].bv_val );
704                         ldap_pvt_thread_pool_pausecheck( &connection_pool );
705                 }
706                 ch_free( pd.ndn );
707                 ch_free( pd.dn );
708
709                 {
710                         Modifications mod;
711                         struct berval bv[2];
712                         rs_reinit( &rs, REP_RESULT );
713                         /* update context's entryCSN to reflect oldest CSN */
714                         mod.sml_numvals = 1;
715                         mod.sml_values = bv;
716                         bv[0] = pd.csn;
717                         BER_BVZERO(&bv[1]);
718                         mod.sml_nvalues = NULL;
719                         mod.sml_desc = slap_schema.si_ad_entryCSN;
720                         mod.sml_op = LDAP_MOD_REPLACE;
721                         mod.sml_flags = SLAP_MOD_INTERNAL;
722                         mod.sml_next = NULL;
723
724                         op->o_tag = LDAP_REQ_MODIFY;
725                         op->orm_modlist = &mod;
726                         op->orm_no_opattrs = 1;
727                         op->o_req_dn = li->li_db->be_suffix[0];
728                         op->o_req_ndn = li->li_db->be_nsuffix[0];
729                         op->o_no_schema_check = 1;
730                         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
731                         op->o_bd->be_modify( op, &rs );
732                         if ( mod.sml_next ) {
733                                 slap_mods_free( mod.sml_next, 1 );
734                         }
735                 }
736         }
737
738         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
739         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
740         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
741
742         return NULL;
743 }
744
745 static int
746 log_cf_gen(ConfigArgs *c)
747 {
748         slap_overinst *on = (slap_overinst *)c->bi;
749         struct log_info *li = on->on_bi.bi_private;
750         int rc = 0;
751         slap_mask_t tmask = 0;
752         char agebuf[2*STRLENOF("ddddd+hh:mm:ss  ")];
753         struct berval agebv, cyclebv;
754
755         switch( c->op ) {
756         case SLAP_CONFIG_EMIT:
757                 switch( c->type ) {
758                 case LOG_DB:
759                         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
760                                 value_add_one( &c->rvalue_vals, &li->li_db_suffix );
761                                 value_add_one( &c->rvalue_nvals, &li->li_db_suffix );
762                         } else if ( li->li_db ) {
763                                 value_add_one( &c->rvalue_vals, li->li_db->be_suffix );
764                                 value_add_one( &c->rvalue_nvals, li->li_db->be_nsuffix );
765                         } else {
766                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
767                                         "accesslog: \"logdb <suffix>\" must be specified" );
768                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
769                                         c->log, c->cr_msg, c->value_dn.bv_val );
770                                 rc = 1;
771                                 break;
772                         }
773                         break;
774                 case LOG_OPS:
775                         rc = mask_to_verbs( logops, li->li_ops, &c->rvalue_vals );
776                         break;
777                 case LOG_PURGE:
778                         if ( !li->li_age ) {
779                                 rc = 1;
780                                 break;
781                         }
782                         agebv.bv_val = agebuf;
783                         log_age_unparse( li->li_age, &agebv, sizeof( agebuf ) );
784                         agebv.bv_val[agebv.bv_len] = ' ';
785                         agebv.bv_len++;
786                         cyclebv.bv_val = agebv.bv_val + agebv.bv_len;
787                         log_age_unparse( li->li_cycle, &cyclebv, sizeof( agebuf ) - agebv.bv_len );
788                         agebv.bv_len += cyclebv.bv_len;
789                         value_add_one( &c->rvalue_vals, &agebv );
790                         break;
791                 case LOG_SUCCESS:
792                         if ( li->li_success )
793                                 c->value_int = li->li_success;
794                         else
795                                 rc = 1;
796                         break;
797                 case LOG_OLD:
798                         if ( li->li_oldf ) {
799                                 filter2bv( li->li_oldf, &agebv );
800                                 ber_bvarray_add( &c->rvalue_vals, &agebv );
801                         }
802                         else
803                                 rc = 1;
804                         break;
805                 case LOG_OLDATTR:
806                         if ( li->li_oldattrs ) {
807                                 log_attr *la;
808
809                                 for ( la = li->li_oldattrs; la; la=la->next )
810                                         value_add_one( &c->rvalue_vals, &la->attr->ad_cname );
811                         }
812                         else
813                                 rc = 1;
814                         break;
815                 case LOG_BASE:
816                         if ( li->li_bases ) {
817                                 log_base *lb;
818
819                                 for ( lb = li->li_bases; lb; lb=lb->lb_next )
820                                         value_add_one( &c->rvalue_vals, &lb->lb_line );
821                         }
822                         else
823                                 rc = 1;
824                         break;
825                 }
826                 break;
827         case LDAP_MOD_DELETE:
828                 switch( c->type ) {
829                 case LOG_DB:
830                         /* noop. this should always be a valid backend. */
831                         break;
832                 case LOG_OPS:
833                         if ( c->valx < 0 ) {
834                                 li->li_ops = 0;
835                         } else {
836                                 rc = verbs_to_mask( 1, &c->line, logops, &tmask );
837                                 if ( rc == 0 )
838                                         li->li_ops &= ~tmask;
839                         }
840                         break;
841                 case LOG_PURGE:
842                         if ( li->li_task ) {
843                                 struct re_s *re = li->li_task;
844                                 li->li_task = NULL;
845                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
846                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
847                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
848                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
849                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
850                         }
851                         li->li_age = 0;
852                         li->li_cycle = 0;
853                         break;
854                 case LOG_SUCCESS:
855                         li->li_success = 0;
856                         break;
857                 case LOG_OLD:
858                         if ( li->li_oldf ) {
859                                 filter_free( li->li_oldf );
860                                 li->li_oldf = NULL;
861                         }
862                         break;
863                 case LOG_OLDATTR:
864                         if ( c->valx < 0 ) {
865                                 log_attr *la, *ln;
866
867                                 for ( la = li->li_oldattrs; la; la = ln ) {
868                                         ln = la->next;
869                                         ch_free( la );
870                                 }
871                         } else {
872                                 log_attr *la = NULL, **lp;
873                                 int i;
874
875                                 for ( lp = &li->li_oldattrs, i=0; i < c->valx; i++ ) {
876                                         la = *lp;
877                                         lp = &la->next;
878                                 }
879                                 *lp = la->next;
880                                 ch_free( la );
881                         }
882                         break;
883                 case LOG_BASE:
884                         if ( c->valx < 0 ) {
885                                 log_base *lb, *ln;
886
887                                 for ( lb = li->li_bases; lb; lb = ln ) {
888                                         ln = lb->lb_next;
889                                         ch_free( lb );
890                                 }
891                         } else {
892                                 log_base *lb = NULL, **lp;
893                                 int i;
894
895                                 for ( lp = &li->li_bases, i=0; i < c->valx; i++ ) {
896                                         lb = *lp;
897                                         lp = &lb->lb_next;
898                                 }
899                                 *lp = lb->lb_next;
900                                 ch_free( lb );
901                         }
902                         break;
903                 }
904                 break;
905         default:
906                 switch( c->type ) {
907                 case LOG_DB:
908                         if ( CONFIG_ONLINE_ADD( c )) {
909                                 li->li_db = select_backend( &c->value_ndn, 0 );
910                                 if ( !li->li_db ) {
911                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
912                                                 "<%s> no matching backend found for suffix",
913                                                 c->argv[0] );
914                                         Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
915                                                 c->log, c->cr_msg, c->value_dn.bv_val );
916                                         rc = 1;
917                                 }
918                                 ch_free( c->value_ndn.bv_val );
919                         } else {
920                                 li->li_db_suffix = c->value_ndn;
921                         }
922                         ch_free( c->value_dn.bv_val );
923                         break;
924                 case LOG_OPS:
925                         rc = verbs_to_mask( c->argc, c->argv, logops, &tmask );
926                         if ( rc == 0 )
927                                 li->li_ops |= tmask;
928                         break;
929                 case LOG_PURGE:
930                         li->li_age = log_age_parse( c->argv[1] );
931                         if ( li->li_age < 1 ) {
932                                 rc = 1;
933                         } else {
934                                 li->li_cycle = log_age_parse( c->argv[2] );
935                                 if ( li->li_cycle < 1 ) {
936                                         rc = 1;
937                                 } else if ( slapMode & SLAP_SERVER_MODE ) {
938                                         struct re_s *re = li->li_task;
939                                         if ( re )
940                                                 re->interval.tv_sec = li->li_cycle;
941                                         else {
942                                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
943                                                 li->li_task = ldap_pvt_runqueue_insert( &slapd_rq,
944                                                         li->li_cycle, accesslog_purge, li,
945                                                         "accesslog_purge", li->li_db ?
946                                                                 li->li_db->be_suffix[0].bv_val :
947                                                                 c->be->be_suffix[0].bv_val );
948                                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
949                                         }
950                                 }
951                         }
952                         break;
953                 case LOG_SUCCESS:
954                         li->li_success = c->value_int;
955                         break;
956                 case LOG_OLD:
957                         li->li_oldf = str2filter( c->argv[1] );
958                         if ( !li->li_oldf ) {
959                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "bad filter!" );
960                                 rc = 1;
961                         }
962                         break;
963                 case LOG_OLDATTR: {
964                         int i;
965                         AttributeDescription *ad;
966                         const char *text;
967
968                         for ( i=1; i< c->argc; i++ ) {
969                                 ad = NULL;
970                                 if ( slap_str2ad( c->argv[i], &ad, &text ) == LDAP_SUCCESS ) {
971                                         log_attr *la = ch_malloc( sizeof( log_attr ));
972                                         la->attr = ad;
973                                         la->next = li->li_oldattrs;
974                                         li->li_oldattrs = la;
975                                 } else {
976                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s <%s>: %s",
977                                                 c->argv[0], c->argv[i], text );
978                                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
979                                                 "%s: %s\n", c->log, c->cr_msg, 0 );
980                                         rc = ARG_BAD_CONF;
981                                         break;
982                                 }
983                         }
984                         }
985                         break;
986                 case LOG_BASE: {
987                         slap_mask_t m = 0;
988                         rc = verbstring_to_mask( logops, c->argv[1], '|', &m );
989                         if ( rc == 0 ) {
990                                 struct berval dn, ndn;
991                                 ber_str2bv( c->argv[2], 0, 0, &dn );
992                                 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
993                                 if ( rc == 0 ) {
994                                         log_base *lb;
995                                         struct berval mbv;
996                                         char *ptr;
997                                         mask_to_verbstring( logops, m, '|', &mbv );
998                                         lb = ch_malloc( sizeof( log_base ) + mbv.bv_len + ndn.bv_len + 3 + 1 );
999                                         lb->lb_line.bv_val = (char *)(lb + 1);
1000                                         lb->lb_line.bv_len = mbv.bv_len + ndn.bv_len + 3;
1001                                         ptr = lutil_strcopy( lb->lb_line.bv_val, mbv.bv_val );
1002                                         *ptr++ = ' ';
1003                                         *ptr++ = '"';
1004                                         lb->lb_base.bv_val = ptr;
1005                                         lb->lb_base.bv_len = ndn.bv_len;
1006                                         ptr = lutil_strcopy( ptr, ndn.bv_val );
1007                                         *ptr++ = '"';
1008                                         lb->lb_ops = m;
1009                                         lb->lb_next = li->li_bases;
1010                                         li->li_bases = lb;
1011                                 } else {
1012                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid DN: %s",
1013                                                 c->argv[0], c->argv[2] );
1014                                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
1015                                                 "%s: %s\n", c->log, c->cr_msg, 0 );
1016                                         rc = ARG_BAD_CONF;
1017                                 }
1018                         } else {
1019                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid ops: %s",
1020                                         c->argv[0], c->argv[1] );
1021                                 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
1022                                         "%s: %s\n", c->log, c->cr_msg, 0 );
1023                                 rc = ARG_BAD_CONF;
1024                         }
1025                         }
1026                         break;
1027                 }
1028                 break;
1029         }
1030         return rc;
1031 }
1032
1033 static int
1034 logSchemaControlValidate(
1035         Syntax          *syntax,
1036         struct berval   *valp )
1037 {
1038         struct berval   val, bv;
1039         ber_len_t               i;
1040         int             rc = LDAP_SUCCESS;
1041
1042         assert( valp != NULL );
1043
1044         val = *valp;
1045
1046         /* check minimal size */
1047         if ( val.bv_len < STRLENOF( "{*}" ) ) {
1048                 return LDAP_INVALID_SYNTAX;
1049         }
1050
1051         val.bv_len--;
1052
1053         /* check SEQUENCE boundaries */
1054         if ( val.bv_val[ 0 ] != '{' /*}*/ ||
1055                 val.bv_val[ val.bv_len ] != /*{*/ '}' )
1056         {
1057                 return LDAP_INVALID_SYNTAX;
1058         }
1059
1060         /* extract and check OID */
1061         for ( i = 1; i < val.bv_len; i++ ) {
1062                 if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1063                         break;
1064                 }
1065         }
1066
1067         bv.bv_val = &val.bv_val[ i ];
1068
1069         for ( i++; i < val.bv_len; i++ ) {
1070                 if ( ASCII_SPACE( val.bv_val[ i ] ) )
1071                 {
1072                         break;
1073                 }
1074         }
1075
1076         bv.bv_len = &val.bv_val[ i ] - bv.bv_val;
1077
1078         rc = numericoidValidate( NULL, &bv );
1079         if ( rc != LDAP_SUCCESS ) {
1080                 return rc;
1081         }
1082
1083         if ( i == val.bv_len ) {
1084                 return LDAP_SUCCESS;
1085         }
1086
1087         if ( val.bv_val[ i ] != ' ' ) {
1088                 return LDAP_INVALID_SYNTAX;
1089         }
1090
1091         for ( i++; i < val.bv_len; i++ ) {
1092                 if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1093                         break;
1094                 }
1095         }
1096
1097         if ( i == val.bv_len ) {
1098                 return LDAP_SUCCESS;
1099         }
1100
1101         /* extract and check criticality */
1102         if ( strncasecmp( &val.bv_val[ i ], "criticality ", STRLENOF( "criticality " ) ) == 0 )
1103         {
1104                 i += STRLENOF( "criticality " );
1105                 for ( ; i < val.bv_len; i++ ) {
1106                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1107                                 break;
1108                         }
1109                 }
1110
1111                 if ( i == val.bv_len ) {
1112                         return LDAP_INVALID_SYNTAX;
1113                 }
1114
1115                 bv.bv_val = &val.bv_val[ i ];
1116
1117                 for ( ; i < val.bv_len; i++ ) {
1118                         if ( ASCII_SPACE( val.bv_val[ i ] ) ) {
1119                                 break;
1120                         }
1121                 }
1122
1123                 bv.bv_len = &val.bv_val[ i ] - bv.bv_val;
1124
1125                 if ( !bvmatch( &bv, &slap_true_bv ) && !bvmatch( &bv, &slap_false_bv ) ) 
1126                 {
1127                         return LDAP_INVALID_SYNTAX;
1128                 }
1129
1130                 if ( i == val.bv_len ) {
1131                         return LDAP_SUCCESS;
1132                 }
1133
1134                 if ( val.bv_val[ i ] != ' ' ) {
1135                         return LDAP_INVALID_SYNTAX;
1136                 }
1137
1138                 for ( i++; i < val.bv_len; i++ ) {
1139                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1140                                 break;
1141                         }
1142                 }
1143
1144                 if ( i == val.bv_len ) {
1145                         return LDAP_SUCCESS;
1146                 }
1147         }
1148
1149         /* extract and check controlValue */
1150         if ( strncasecmp( &val.bv_val[ i ], "controlValue ", STRLENOF( "controlValue " ) ) == 0 )
1151         {
1152                 ber_len_t valueStart, valueLen;
1153
1154                 i += STRLENOF( "controlValue " );
1155                 for ( ; i < val.bv_len; i++ ) {
1156                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1157                                 break;
1158                         }
1159                 }
1160
1161                 if ( i == val.bv_len ) {
1162                         return LDAP_INVALID_SYNTAX;
1163                 }
1164
1165                 if ( val.bv_val[ i ] != '"' ) {
1166                         return LDAP_INVALID_SYNTAX;
1167                 }
1168
1169                 i++;
1170                 valueStart = i;
1171
1172                 for ( ; i < val.bv_len; i++ ) {
1173                         if ( val.bv_val[ i ] == '"' ) {
1174                                 break;
1175                         }
1176
1177                         if ( !ASCII_HEX( val.bv_val[ i ] ) ) {
1178                                 return LDAP_INVALID_SYNTAX;
1179                         }
1180                 }
1181
1182                 if ( val.bv_val[ i ] != '"' ) {
1183                         return LDAP_INVALID_SYNTAX;
1184                 }
1185
1186                 valueLen = i - valueStart;
1187                 if ( (valueLen/2)*2 != valueLen ) {
1188                         return LDAP_INVALID_SYNTAX;
1189                 }
1190
1191                 for ( i++; i < val.bv_len; i++ ) {
1192                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1193                                 break;
1194                         }
1195                 }
1196
1197                 if ( i == val.bv_len ) {
1198                         return LDAP_SUCCESS;
1199                 }
1200         }
1201
1202         return LDAP_INVALID_SYNTAX;
1203 }
1204
1205 static int
1206 accesslog_ctrls(
1207         LDAPControl **ctrls,
1208         BerVarray *valsp,
1209         BerVarray *nvalsp,
1210         void *memctx )
1211 {
1212         long            i, rc = 0;
1213
1214         assert( valsp != NULL );
1215         assert( ctrls != NULL );
1216
1217         *valsp = NULL;
1218         *nvalsp = NULL;
1219
1220         for ( i = 0; ctrls[ i ] != NULL; i++ ) {
1221                 struct berval   idx,
1222                                 oid,
1223                                 noid,
1224                                 bv;
1225                 char            *ptr,
1226                                 buf[ 32 ];
1227
1228                 if ( ctrls[ i ]->ldctl_oid == NULL ) {
1229                         return LDAP_PROTOCOL_ERROR;
1230                 }
1231
1232                 idx.bv_len = snprintf( buf, sizeof( buf ), "{%ld}", i );
1233                 idx.bv_val = buf;
1234
1235                 ber_str2bv( ctrls[ i ]->ldctl_oid, 0, 0, &oid );
1236                 noid.bv_len = idx.bv_len + oid.bv_len;
1237                 ptr = noid.bv_val = ber_memalloc_x( noid.bv_len + 1, memctx );
1238                 ptr = lutil_strcopy( ptr, idx.bv_val );
1239                 ptr = lutil_strcopy( ptr, oid.bv_val );
1240
1241                 bv.bv_len = idx.bv_len + STRLENOF( "{}" ) + oid.bv_len;
1242
1243                 if ( ctrls[ i ]->ldctl_iscritical ) {
1244                         bv.bv_len += STRLENOF( " criticality TRUE" );
1245                 }
1246
1247                 if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
1248                         bv.bv_len += STRLENOF( " controlValue \"\"" )
1249                                 + 2 * ctrls[ i ]->ldctl_value.bv_len;
1250                 }
1251
1252                 ptr = bv.bv_val = ber_memalloc_x( bv.bv_len + 1, memctx );
1253                 if ( ptr == NULL ) {
1254                         ber_bvarray_free( *valsp );
1255                         *valsp = NULL;
1256                         ber_bvarray_free( *nvalsp );
1257                         *nvalsp = NULL;
1258                         return LDAP_OTHER;
1259                 }
1260
1261                 ptr = lutil_strcopy( ptr, idx.bv_val );
1262
1263                 *ptr++ = '{' /*}*/ ;
1264                 ptr = lutil_strcopy( ptr, oid.bv_val );
1265
1266                 if ( ctrls[ i ]->ldctl_iscritical ) {
1267                         ptr = lutil_strcopy( ptr, " criticality TRUE" );
1268                 }
1269                 
1270                 if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
1271                         ber_len_t       j;
1272
1273                         ptr = lutil_strcopy( ptr, " controlValue \"" );
1274                         for ( j = 0; j < ctrls[ i ]->ldctl_value.bv_len; j++ ) {
1275                                 *ptr++ = SLAP_ESCAPE_HI(ctrls[ i ]->ldctl_value.bv_val[ j ]);
1276                                 *ptr++ = SLAP_ESCAPE_LO(ctrls[ i ]->ldctl_value.bv_val[ j ]);
1277                         }
1278
1279                         *ptr++ = '"';
1280                 }
1281
1282                 *ptr++ = '}';
1283                 *ptr = '\0';
1284
1285                 ber_bvarray_add_x( valsp, &bv, memctx );
1286                 ber_bvarray_add_x( nvalsp, &noid, memctx );
1287         }
1288
1289         return rc;
1290         
1291 }
1292
1293 static Entry *accesslog_entry( Operation *op, SlapReply *rs, int logop,
1294         Operation *op2 ) {
1295         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1296         log_info *li = on->on_bi.bi_private;
1297
1298         char rdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
1299         char nrdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
1300
1301         struct berval rdn, nrdn, timestamp, ntimestamp, bv;
1302         slap_verbmasks *lo = logops+logop+EN_OFFSET;
1303
1304         Entry *e = entry_alloc();
1305
1306         strcpy( rdnbuf, RDNEQ );
1307         rdn.bv_val = rdnbuf;
1308         strcpy( nrdnbuf, RDNEQ );
1309         nrdn.bv_val = nrdnbuf;
1310
1311         timestamp.bv_val = rdnbuf+STRLENOF(RDNEQ);
1312         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
1313         slap_timestamp( &op->o_time, &timestamp );
1314         snprintf( timestamp.bv_val + timestamp.bv_len-1, sizeof(".123456Z"), ".%06dZ", op->o_tincr );
1315         timestamp.bv_len += STRLENOF(".123456");
1316
1317         rdn.bv_len = STRLENOF(RDNEQ)+timestamp.bv_len;
1318         ad_reqStart->ad_type->sat_equality->smr_normalize(
1319                 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, ad_reqStart->ad_type->sat_syntax,
1320                 ad_reqStart->ad_type->sat_equality, &timestamp, &ntimestamp,
1321                 op->o_tmpmemctx );
1322
1323         strcpy( nrdn.bv_val + STRLENOF(RDNEQ), ntimestamp.bv_val );
1324         nrdn.bv_len = STRLENOF(RDNEQ)+ntimestamp.bv_len;
1325         build_new_dn( &e->e_name, li->li_db->be_suffix, &rdn, NULL );
1326         build_new_dn( &e->e_nname, li->li_db->be_nsuffix, &nrdn, NULL );
1327
1328         attr_merge_one( e, slap_schema.si_ad_objectClass,
1329                 &log_ocs[logop]->soc_cname, NULL );
1330         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
1331                 &log_ocs[logop]->soc_cname, NULL );
1332         attr_merge_one( e, ad_reqStart, &timestamp, &ntimestamp );
1333         op->o_tmpfree( ntimestamp.bv_val, op->o_tmpmemctx );
1334
1335         slap_op_time( &op2->o_time, &op2->o_tincr );
1336
1337         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
1338         slap_timestamp( &op2->o_time, &timestamp );
1339         snprintf( timestamp.bv_val + timestamp.bv_len-1, sizeof(".123456Z"), ".%06dZ", op2->o_tincr );
1340         timestamp.bv_len += STRLENOF(".123456");
1341
1342         attr_merge_normalize_one( e, ad_reqEnd, &timestamp, op->o_tmpmemctx );
1343
1344         /* Exops have OID appended */
1345         if ( logop == LOG_EN_EXTENDED ) {
1346                 bv.bv_len = lo->word.bv_len + op->ore_reqoid.bv_len + 2;
1347                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
1348                 AC_MEMCPY( bv.bv_val, lo->word.bv_val, lo->word.bv_len );
1349                 bv.bv_val[lo->word.bv_len] = '{';
1350                 AC_MEMCPY( bv.bv_val+lo->word.bv_len+1, op->ore_reqoid.bv_val,
1351                         op->ore_reqoid.bv_len );
1352                 bv.bv_val[bv.bv_len-1] = '}';
1353                 bv.bv_val[bv.bv_len] = '\0';
1354                 attr_merge_one( e, ad_reqType, &bv, NULL );
1355         } else {
1356                 attr_merge_one( e, ad_reqType, &lo->word, NULL );
1357         }
1358
1359         rdn.bv_len = snprintf( rdn.bv_val, sizeof( rdnbuf ), "%lu", op->o_connid );
1360         if ( rdn.bv_len < sizeof( rdnbuf ) ) {
1361                 attr_merge_one( e, ad_reqSession, &rdn, NULL );
1362         } /* else? */
1363
1364         if ( BER_BVISNULL( &op->o_dn ) ) {
1365                 attr_merge_one( e, ad_reqAuthzID, (struct berval *)&slap_empty_bv,
1366                         (struct berval *)&slap_empty_bv );
1367         } else {
1368                 attr_merge_one( e, ad_reqAuthzID, &op->o_dn, &op->o_ndn );
1369         }
1370
1371         /* FIXME: need to add reqControls and reqRespControls */
1372         if ( op->o_ctrls ) {
1373                 BerVarray       vals = NULL,
1374                                 nvals = NULL;
1375
1376                 if ( accesslog_ctrls( op->o_ctrls, &vals, &nvals,
1377                         op->o_tmpmemctx ) == LDAP_SUCCESS && vals )
1378                 {
1379                         attr_merge( e, ad_reqControls, vals, nvals );
1380                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1381                         ber_bvarray_free_x( nvals, op->o_tmpmemctx );
1382                 }
1383         }
1384
1385         if ( rs->sr_ctrls ) {
1386                 BerVarray       vals = NULL,
1387                                 nvals = NULL;
1388
1389                 if ( accesslog_ctrls( rs->sr_ctrls, &vals, &nvals,
1390                         op->o_tmpmemctx ) == LDAP_SUCCESS && vals )
1391                 {
1392                         attr_merge( e, ad_reqRespControls, vals, nvals );
1393                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1394                         ber_bvarray_free_x( nvals, op->o_tmpmemctx );
1395                 }
1396
1397         }
1398
1399         return e;
1400 }
1401
1402 static struct berval scopes[] = {
1403         BER_BVC("base"),
1404         BER_BVC("one"),
1405         BER_BVC("sub"),
1406         BER_BVC("subord")
1407 };
1408
1409 static struct berval derefs[] = {
1410         BER_BVC("never"),
1411         BER_BVC("searching"),
1412         BER_BVC("finding"),
1413         BER_BVC("always")
1414 };
1415
1416 static struct berval simple = BER_BVC("SIMPLE");
1417
1418 static void accesslog_val2val(AttributeDescription *ad, struct berval *val,
1419         char c_op, struct berval *dst) {
1420         char *ptr;
1421
1422         dst->bv_len = ad->ad_cname.bv_len + val->bv_len + 2;
1423         if ( c_op ) dst->bv_len++;
1424
1425         dst->bv_val = ch_malloc( dst->bv_len+1 );
1426
1427         ptr = lutil_strcopy( dst->bv_val, ad->ad_cname.bv_val );
1428         *ptr++ = ':';
1429         if ( c_op )
1430                 *ptr++ = c_op;
1431         *ptr++ = ' ';
1432         AC_MEMCPY( ptr, val->bv_val, val->bv_len );
1433         dst->bv_val[dst->bv_len] = '\0';
1434 }
1435
1436 static int
1437 accesslog_op2logop( Operation *op )
1438 {
1439         switch ( op->o_tag ) {
1440         case LDAP_REQ_ADD:              return LOG_EN_ADD;
1441         case LDAP_REQ_DELETE:   return LOG_EN_DELETE;
1442         case LDAP_REQ_MODIFY:   return LOG_EN_MODIFY;
1443         case LDAP_REQ_MODRDN:   return LOG_EN_MODRDN;
1444         case LDAP_REQ_COMPARE:  return LOG_EN_COMPARE;
1445         case LDAP_REQ_SEARCH:   return LOG_EN_SEARCH;
1446         case LDAP_REQ_BIND:             return LOG_EN_BIND;
1447         case LDAP_REQ_EXTENDED: return LOG_EN_EXTENDED;
1448         default:        /* unknown operation type */
1449                 break;
1450         }       /* Unbind and Abandon never reach here */
1451         return LOG_EN_UNKNOWN;
1452 }
1453
1454 static int accesslog_response(Operation *op, SlapReply *rs) {
1455         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1456         log_info *li = on->on_bi.bi_private;
1457         Attribute *a, *last_attr;
1458         Modifications *m;
1459         struct berval *b, uuid = BER_BVNULL;
1460         int i;
1461         int logop, do_graduate = 0;
1462         slap_verbmasks *lo;
1463         Entry *e = NULL, *old = NULL, *e_uuid = NULL;
1464         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE+8];
1465         struct berval bv;
1466         char *ptr;
1467         BerVarray vals;
1468         Operation op2 = {0};
1469         SlapReply rs2 = {REP_RESULT};
1470
1471         if ( rs->sr_type != REP_RESULT && rs->sr_type != REP_EXTENDED )
1472                 return SLAP_CB_CONTINUE;
1473
1474         logop = accesslog_op2logop( op );
1475         lo = logops+logop+EN_OFFSET;
1476         if ( !( li->li_ops & lo->mask )) {
1477                 log_base *lb;
1478
1479                 i = 0;
1480                 for ( lb = li->li_bases; lb; lb=lb->lb_next )
1481                         if (( lb->lb_ops & lo->mask ) && dnIsSuffix( &op->o_req_ndn, &lb->lb_base )) {
1482                                 i = 1;
1483                                 break;
1484                         }
1485                 if ( !i )
1486                         return SLAP_CB_CONTINUE;
1487         }
1488
1489         /* mutex and so were only set for write operations;
1490          * if we got here, the operation must be logged */
1491         if ( lo->mask & LOG_OP_WRITES ) {
1492                 slap_callback *cb;
1493
1494                 /* Most internal ops are not logged */
1495                 if ( op->o_dont_replicate) {
1496                         /* Let contextCSN updates from syncrepl thru; the underlying
1497                          * syncprov needs to see them. Skip others.
1498                          */
1499                         if (( op->o_tag != LDAP_REQ_MODIFY ||
1500                                 op->orm_modlist->sml_op != LDAP_MOD_REPLACE ||
1501                                 op->orm_modlist->sml_desc != slap_schema.si_ad_contextCSN ) &&
1502                                 op->orm_no_opattrs )
1503                         return SLAP_CB_CONTINUE;
1504                 }
1505
1506                 ldap_pvt_thread_mutex_lock( &li->li_log_mutex );
1507                 old = li->li_old;
1508                 uuid = li->li_uuid;
1509                 li->li_old = NULL;
1510                 BER_BVZERO( &li->li_uuid );
1511                 /* Disarm mod_cleanup */
1512                 for ( cb = op->o_callback; cb; cb = cb->sc_next ) {
1513                         if ( cb->sc_private == (void *)on ) {
1514                                 cb->sc_private = NULL;
1515                                 break;
1516                         }
1517                 }
1518 #ifdef RMUTEX_DEBUG
1519                 Debug( LDAP_DEBUG_SYNC,
1520                         "accesslog_response: unlocking rmutex for tid %x\n",
1521                         op->o_tid, 0, 0 );
1522 #endif
1523                 ldap_pvt_thread_rmutex_unlock( &li->li_op_rmutex, op->o_tid );
1524         }
1525
1526         /* ignore these internal reads */
1527         if (( lo->mask & LOG_OP_READS ) && op->o_do_not_cache ) {
1528                 return SLAP_CB_CONTINUE;
1529         }
1530
1531         if ( li->li_success && rs->sr_err != LDAP_SUCCESS )
1532                 goto done;
1533
1534         e = accesslog_entry( op, rs, logop, &op2 );
1535
1536         attr_merge_one( e, ad_reqDN, &op->o_req_dn, &op->o_req_ndn );
1537
1538         if ( rs->sr_text ) {
1539                 ber_str2bv( rs->sr_text, 0, 0, &bv );
1540                 attr_merge_normalize_one( e, ad_reqMessage, &bv, op->o_tmpmemctx );
1541         }
1542         bv.bv_len = snprintf( timebuf, sizeof( timebuf ), "%d", rs->sr_err );
1543         if ( bv.bv_len < sizeof( timebuf ) ) {
1544                 bv.bv_val = timebuf;
1545                 attr_merge_one( e, ad_reqResult, &bv, NULL );
1546         }
1547
1548         last_attr = attr_find( e->e_attrs, ad_reqResult );
1549
1550         e_uuid = old;
1551         switch( logop ) {
1552         case LOG_EN_ADD:
1553         case LOG_EN_DELETE: {
1554                 char c_op;
1555                 Entry *e2;
1556
1557                 if ( logop == LOG_EN_ADD ) {
1558                         e2 = op->ora_e;
1559                         e_uuid = op->ora_e;
1560                         c_op = '+';
1561
1562                 } else {
1563                         if ( !old )
1564                                 break;
1565                         e2 = old;
1566                         c_op = 0;
1567                 }
1568                 /* count all the vals */
1569                 i = 0;
1570                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1571                         i += a->a_numvals;
1572                 }
1573                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1574                 i = 0;
1575                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1576                         if ( a->a_vals ) {
1577                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1578                                         accesslog_val2val( a->a_desc, b, c_op, &vals[i] );
1579                                 }
1580                         }
1581                 }
1582                 vals[i].bv_val = NULL;
1583                 vals[i].bv_len = 0;
1584                 a = attr_alloc( logop == LOG_EN_ADD ? ad_reqMod : ad_reqOld );
1585                 a->a_numvals = i;
1586                 a->a_vals = vals;
1587                 a->a_nvals = vals;
1588                 last_attr->a_next = a;
1589                 break;
1590         }
1591
1592         case LOG_EN_MODRDN:
1593         case LOG_EN_MODIFY:
1594                 /* count all the mods + attributes (ITS#6545) */
1595                 i = 0;
1596                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1597                         if ( m->sml_values ) {
1598                                 i += m->sml_numvals;
1599                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1600                                 m->sml_op == LDAP_MOD_REPLACE )
1601                         {
1602                                 i++;
1603                         }
1604                         if ( m->sml_next && m->sml_desc == m->sml_next->sml_desc ) {
1605                                 i++;
1606                         }
1607                 }
1608                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1609                 i = 0;
1610
1611                 /* init flags on old entry */
1612                 if ( old ) {
1613                         for ( a = old->e_attrs; a; a = a->a_next ) {
1614                                 log_attr *la;
1615                                 a->a_flags = 0;
1616
1617                                 /* look for attrs that are always logged */
1618                                 for ( la = li->li_oldattrs; la; la = la->next ) {
1619                                         if ( a->a_desc == la->attr ) {
1620                                                 a->a_flags = 1;
1621                                         }
1622                                 }
1623                         }
1624                 }
1625
1626                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1627                         /* Mark this attribute as modified */
1628                         if ( old ) {
1629                                 a = attr_find( old->e_attrs, m->sml_desc );
1630                                 if ( a ) {
1631                                         a->a_flags = 1;
1632                                 }
1633                         }
1634
1635                         /* don't log the RDN mods; they're explicitly logged later */
1636                         if ( logop == LOG_EN_MODRDN &&
1637                                 ( m->sml_op == SLAP_MOD_SOFTADD ||
1638                                   m->sml_op == LDAP_MOD_DELETE ) )
1639                         {
1640                                 continue;
1641                         }
1642
1643                         if ( m->sml_values ) {
1644                                 for ( b = m->sml_values; !BER_BVISNULL( b ); b++, i++ ) {
1645                                         char c_op;
1646
1647                                         switch ( m->sml_op ) {
1648                                         case LDAP_MOD_ADD: c_op = '+'; break;
1649                                         case LDAP_MOD_DELETE:   c_op = '-'; break;
1650                                         case LDAP_MOD_REPLACE:  c_op = '='; break;
1651                                         case LDAP_MOD_INCREMENT:        c_op = '#'; break;
1652
1653                                         /* unknown op. there shouldn't be any of these. we
1654                                          * don't know what to do with it, but we shouldn't just
1655                                          * ignore it.
1656                                          */
1657                                         default: c_op = '?'; break;
1658                                         }
1659                                         accesslog_val2val( m->sml_desc, b, c_op, &vals[i] );
1660                                 }
1661                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1662                                 m->sml_op == LDAP_MOD_REPLACE )
1663                         {
1664                                 vals[i].bv_len = m->sml_desc->ad_cname.bv_len + 2;
1665                                 vals[i].bv_val = ch_malloc( vals[i].bv_len + 1 );
1666                                 ptr = lutil_strcopy( vals[i].bv_val,
1667                                         m->sml_desc->ad_cname.bv_val );
1668                                 *ptr++ = ':';
1669                                 if ( m->sml_op == LDAP_MOD_DELETE ) {
1670                                         *ptr++ = '-';
1671                                 } else {
1672                                         *ptr++ = '=';
1673                                 }
1674                                 *ptr = '\0';
1675                                 i++;
1676                         }
1677                         /* ITS#6545: when the same attribute is edited multiple times,
1678                          * record the transition */
1679                         if ( m->sml_next && m->sml_desc == m->sml_next->sml_desc ) {
1680                                 ber_str2bv( ":", STRLENOF(":"), 1, &vals[i] );
1681                                 i++;
1682                         }
1683                 }
1684
1685                 if ( i > 0 ) {
1686                         BER_BVZERO( &vals[i] );
1687                         a = attr_alloc( ad_reqMod );
1688                         a->a_numvals = i;
1689                         a->a_vals = vals;
1690                         a->a_nvals = vals;
1691                         last_attr->a_next = a;
1692                         last_attr = a;
1693
1694                 } else {
1695                         ch_free( vals );
1696                 }
1697
1698                 if ( old ) {
1699                         /* count all the vals */
1700                         i = 0;
1701                         for ( a = old->e_attrs; a != NULL; a = a->a_next ) {
1702                                 if ( a->a_vals && a->a_flags ) {
1703                                         i += a->a_numvals;
1704                                 }
1705                         }
1706                         if ( i ) {
1707                                 vals = ch_malloc( (i + 1) * sizeof( struct berval ) );
1708                                 i = 0;
1709                                 for ( a=old->e_attrs; a; a=a->a_next ) {
1710                                         if ( a->a_vals && a->a_flags ) {
1711                                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1712                                                         accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1713                                                 }
1714                                         }
1715                                 }
1716                                 vals[i].bv_val = NULL;
1717                                 vals[i].bv_len = 0;
1718                                 a = attr_alloc( ad_reqOld );
1719                                 a->a_numvals = i;
1720                                 a->a_vals = vals;
1721                                 a->a_nvals = vals;
1722                                 last_attr->a_next = a;
1723                         }
1724                 }
1725                 if ( logop == LOG_EN_MODIFY ) {
1726                         break;
1727                 }
1728
1729                 /* Now log the actual modRDN info */
1730                 attr_merge_one( e, ad_reqNewRDN, &op->orr_newrdn, &op->orr_nnewrdn );
1731                 attr_merge_one( e, ad_reqDeleteOldRDN, op->orr_deleteoldrdn ?
1732                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1733                         NULL );
1734                 if ( op->orr_newSup ) {
1735                         attr_merge_one( e, ad_reqNewSuperior, op->orr_newSup, op->orr_nnewSup );
1736                 }
1737                 break;
1738
1739         case LOG_EN_COMPARE:
1740                 bv.bv_len = op->orc_ava->aa_desc->ad_cname.bv_len + 1 +
1741                         op->orc_ava->aa_value.bv_len;
1742                 bv.bv_val = op->o_tmpalloc( bv.bv_len+1, op->o_tmpmemctx );
1743                 ptr = lutil_strcopy( bv.bv_val, op->orc_ava->aa_desc->ad_cname.bv_val );
1744                 *ptr++ = '=';
1745                 AC_MEMCPY( ptr, op->orc_ava->aa_value.bv_val, op->orc_ava->aa_value.bv_len );
1746                 bv.bv_val[bv.bv_len] = '\0';
1747                 attr_merge_one( e, ad_reqAssertion, &bv, NULL );
1748                 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1749                 break;
1750
1751         case LOG_EN_SEARCH:
1752                 attr_merge_one( e, ad_reqScope, &scopes[op->ors_scope], NULL );
1753                 attr_merge_one( e, ad_reqDerefAliases, &derefs[op->ors_deref], NULL );
1754                 attr_merge_one( e, ad_reqAttrsOnly, op->ors_attrsonly ?
1755                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1756                         NULL );
1757                 if ( !BER_BVISEMPTY( &op->ors_filterstr ))
1758                         attr_merge_normalize_one( e, ad_reqFilter, &op->ors_filterstr, op->o_tmpmemctx );
1759                 if ( op->ors_attrs ) {
1760                         int j;
1761                         /* count them */
1762                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1763                                 ;
1764                         vals = op->o_tmpalloc( (i+1) * sizeof(struct berval),
1765                                 op->o_tmpmemctx );
1766                         for (i=0, j=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++) {
1767                                 if (!BER_BVISEMPTY(&op->ors_attrs[i].an_name)) {
1768                                         vals[j] = op->ors_attrs[i].an_name;
1769                                         j++;
1770                                 }
1771                         }
1772                         BER_BVZERO(&vals[j]);
1773                         attr_merge_normalize( e, ad_reqAttr, vals, op->o_tmpmemctx );
1774                         op->o_tmpfree( vals, op->o_tmpmemctx );
1775                 }
1776                 bv.bv_val = timebuf;
1777                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", rs->sr_nentries );
1778                 if ( bv.bv_len < sizeof( timebuf ) ) {
1779                         attr_merge_one( e, ad_reqEntries, &bv, NULL );
1780                 } /* else? */
1781
1782                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->ors_tlimit );
1783                 if ( bv.bv_len < sizeof( timebuf ) ) {
1784                         attr_merge_one( e, ad_reqTimeLimit, &bv, NULL );
1785                 } /* else? */
1786
1787                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->ors_slimit );
1788                 if ( bv.bv_len < sizeof( timebuf ) ) {
1789                         attr_merge_one( e, ad_reqSizeLimit, &bv, NULL );
1790                 } /* else? */
1791                 break;
1792
1793         case LOG_EN_BIND:
1794                 bv.bv_val = timebuf;
1795                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->o_protocol );
1796                 if ( bv.bv_len < sizeof( timebuf ) ) {
1797                         attr_merge_one( e, ad_reqVersion, &bv, NULL );
1798                 } /* else? */
1799                 if ( op->orb_method == LDAP_AUTH_SIMPLE ) {
1800                         attr_merge_normalize_one( e, ad_reqMethod, &simple, op->o_tmpmemctx );
1801                 } else {
1802                         bv.bv_len = STRLENOF("SASL()") + op->orb_mech.bv_len;
1803                         bv.bv_val = op->o_tmpalloc( bv.bv_len + 1, op->o_tmpmemctx );
1804                         ptr = lutil_strcopy( bv.bv_val, "SASL(" );
1805                         ptr = lutil_strcopy( ptr, op->orb_mech.bv_val );
1806                         *ptr++ = ')';
1807                         *ptr = '\0';
1808                         attr_merge_normalize_one( e, ad_reqMethod, &bv, op->o_tmpmemctx );
1809                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1810                 }
1811
1812                 break;
1813
1814         case LOG_EN_EXTENDED:
1815                 if ( op->ore_reqdata ) {
1816                         attr_merge_one( e, ad_reqData, op->ore_reqdata, NULL );
1817                 }
1818                 break;
1819
1820         case LOG_EN_UNKNOWN:
1821                 /* we don't know its parameters, don't add any */
1822                 break;
1823         }
1824
1825         if ( e_uuid || !BER_BVISNULL( &uuid ) ) {
1826                 struct berval *pbv = NULL;
1827
1828                 if ( !BER_BVISNULL( &uuid ) ) {
1829                         pbv = &uuid;
1830
1831                 } else {
1832                         a = attr_find( e_uuid->e_attrs, slap_schema.si_ad_entryUUID );
1833                         if ( a ) {
1834                                 pbv = &a->a_vals[0];
1835                         }
1836                 } 
1837
1838                 if ( pbv ) {
1839                         attr_merge_normalize_one( e, ad_reqEntryUUID, pbv, op->o_tmpmemctx );
1840                 }
1841
1842                 if ( !BER_BVISNULL( &uuid ) ) {
1843                         ber_memfree( uuid.bv_val );
1844                         BER_BVZERO( &uuid );
1845                 }
1846         }
1847
1848         op2.o_hdr = op->o_hdr;
1849         op2.o_tag = LDAP_REQ_ADD;
1850         op2.o_bd = li->li_db;
1851         op2.o_dn = li->li_db->be_rootdn;
1852         op2.o_ndn = li->li_db->be_rootndn;
1853         op2.o_req_dn = e->e_name;
1854         op2.o_req_ndn = e->e_nname;
1855         op2.ora_e = e;
1856         op2.o_callback = &nullsc;
1857         op2.o_csn = op->o_csn;
1858         /* contextCSN updates may still reach here */
1859         op2.o_dont_replicate = op->o_dont_replicate;
1860
1861         if (( lo->mask & LOG_OP_WRITES ) && !BER_BVISEMPTY( &op->o_csn )) {
1862                 struct berval maxcsn;
1863                 char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
1864                 int foundit;
1865                 cbuf[0] = '\0';
1866                 maxcsn.bv_val = cbuf;
1867                 maxcsn.bv_len = sizeof(cbuf);
1868                 /* If there was a commit CSN on the main DB,
1869                  * we must propagate it to the log DB for its
1870                  * own syncprov. Otherwise, don't generate one.
1871                  */
1872                 slap_get_commit_csn( op, &maxcsn, &foundit );
1873                 if ( !BER_BVISEMPTY( &maxcsn ) ) {
1874                         slap_queue_csn( &op2, &op->o_csn );
1875                         do_graduate = 1;
1876                 } else {
1877                         attr_merge_normalize_one( e, slap_schema.si_ad_entryCSN,
1878                                 &op->o_csn, op->o_tmpmemctx );
1879                 }
1880         }
1881
1882         op2.o_bd->be_add( &op2, &rs2 );
1883         if ( e == op2.ora_e ) entry_free( e );
1884         e = NULL;
1885         if ( do_graduate ) {
1886                 slap_graduate_commit_csn( &op2 );
1887         }
1888
1889 done:
1890         if ( lo->mask & LOG_OP_WRITES )
1891                 ldap_pvt_thread_mutex_unlock( &li->li_log_mutex );
1892         if ( old ) entry_free( old );
1893         return SLAP_CB_CONTINUE;
1894 }
1895
1896 /* Since Bind success is sent by the frontend, it won't normally enter
1897  * the overlay response callback. Add another callback to make sure it
1898  * gets here.
1899  */
1900 static int
1901 accesslog_bind_resp( Operation *op, SlapReply *rs )
1902 {
1903         BackendDB *be, db;
1904         int rc;
1905         slap_callback *sc;
1906
1907         be = op->o_bd;
1908         db = *be;
1909         op->o_bd = &db;
1910         db.bd_info = op->o_callback->sc_private;
1911         rc = accesslog_response( op, rs );
1912         op->o_bd = be;
1913         sc = op->o_callback;
1914         op->o_callback = sc->sc_next;
1915         op->o_tmpfree( sc, op->o_tmpmemctx );
1916         return rc;
1917 }
1918
1919 static int
1920 accesslog_op_bind( Operation *op, SlapReply *rs )
1921 {
1922         slap_callback *sc;
1923
1924         sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1925         sc->sc_response = accesslog_bind_resp;
1926         sc->sc_private = op->o_bd->bd_info;
1927
1928         if ( op->o_callback ) {
1929                 sc->sc_next = op->o_callback->sc_next;
1930                 op->o_callback->sc_next = sc;
1931         } else {
1932                 op->o_callback = sc;
1933         }
1934         return SLAP_CB_CONTINUE;
1935 }
1936
1937 static int
1938 accesslog_mod_cleanup( Operation *op, SlapReply *rs )
1939 {
1940         slap_callback *sc = op->o_callback;
1941         slap_overinst *on = sc->sc_private;
1942         op->o_callback = sc->sc_next;
1943
1944         op->o_tmpfree( sc, op->o_tmpmemctx );
1945
1946         if ( on ) {
1947                 BackendInfo *bi = op->o_bd->bd_info;
1948                 op->o_bd->bd_info = (BackendInfo *)on;
1949                 accesslog_response( op, rs );
1950                 op->o_bd->bd_info = bi;
1951         }
1952         return 0;
1953 }
1954
1955 static int
1956 accesslog_op_mod( Operation *op, SlapReply *rs )
1957 {
1958         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1959         log_info *li = on->on_bi.bi_private;
1960         slap_verbmasks *lo;
1961         int logop;
1962         int doit = 0;
1963
1964         /* These internal ops are not logged */
1965         if ( op->o_dont_replicate ) {
1966                 /* Let contextCSN updates from syncrepl thru; the underlying
1967                  * syncprov needs to see them. Skip others.
1968                  */
1969                 if (( op->o_tag != LDAP_REQ_MODIFY ||
1970                         op->orm_modlist->sml_op != LDAP_MOD_REPLACE ||
1971                         op->orm_modlist->sml_desc != slap_schema.si_ad_contextCSN ) &&
1972                         op->orm_no_opattrs )
1973                 return SLAP_CB_CONTINUE;
1974                 /* give this a unique timestamp */
1975                 op->o_tincr++;
1976                 if ( op->o_tincr >= 1000000 ) {
1977                         op->o_tincr -= 1000000;
1978                         op->o_time++;
1979                 }
1980         }
1981
1982         logop = accesslog_op2logop( op );
1983         lo = logops+logop+EN_OFFSET;
1984
1985         if ( li->li_ops & lo->mask ) {
1986                 doit = 1;
1987         } else {
1988                 log_base *lb;
1989                 for ( lb = li->li_bases; lb; lb = lb->lb_next )
1990                         if (( lb->lb_ops & lo->mask ) && dnIsSuffix( &op->o_req_ndn, &lb->lb_base )) {
1991                                 doit = 1;
1992                                 break;
1993                         }
1994         }
1995                         
1996         if ( doit ) {
1997                 slap_callback *cb = op->o_tmpcalloc( 1, sizeof( slap_callback ), op->o_tmpmemctx ), *cb2;
1998                 cb->sc_cleanup = accesslog_mod_cleanup;
1999                 cb->sc_private = on;
2000                 for ( cb2 = op->o_callback; cb2->sc_next; cb2 = cb2->sc_next );
2001                 cb2->sc_next = cb;
2002
2003 #ifdef RMUTEX_DEBUG
2004                 Debug( LDAP_DEBUG_SYNC,
2005                         "accesslog_op_mod: locking rmutex for tid %x\n",
2006                         op->o_tid, 0, 0 );
2007 #endif
2008                 ldap_pvt_thread_rmutex_lock( &li->li_op_rmutex, op->o_tid );
2009 #ifdef RMUTEX_DEBUG
2010                 Debug( LDAP_DEBUG_STATS,
2011                         "accesslog_op_mod: locked rmutex for tid %x\n",
2012                         op->o_tid, 0, 0 );
2013 #endif
2014                 if ( li->li_oldf && ( op->o_tag == LDAP_REQ_DELETE ||
2015                         op->o_tag == LDAP_REQ_MODIFY ||
2016                         ( op->o_tag == LDAP_REQ_MODRDN && li->li_oldattrs )))
2017                 {
2018                         int rc;
2019                         Entry *e;
2020
2021                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2022                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
2023                         if ( e ) {
2024                                 if ( test_filter( op, e, li->li_oldf ) == LDAP_COMPARE_TRUE )
2025                                         li->li_old = entry_dup( e );
2026                                 be_entry_release_rw( op, e, 0 );
2027                         }
2028                         op->o_bd->bd_info = (BackendInfo *)on;
2029
2030                 } else {
2031                         int rc;
2032                         Entry *e;
2033
2034                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2035                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
2036                         if ( e ) {
2037                                 Attribute *a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
2038                                 if ( a ) {
2039                                         ber_dupbv( &li->li_uuid, &a->a_vals[0] );
2040                                 }
2041                                 be_entry_release_rw( op, e, 0 );
2042                         }
2043                         op->o_bd->bd_info = (BackendInfo *)on;
2044                 }
2045         }
2046         return SLAP_CB_CONTINUE;
2047 }
2048
2049 /* unbinds are broadcast to all backends; we only log it if this
2050  * backend was used for the original bind.
2051  */
2052 static int
2053 accesslog_unbind( Operation *op, SlapReply *rs )
2054 {
2055         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2056         if ( op->o_conn->c_authz_backend == on->on_info->oi_origdb ) {
2057                 log_info *li = on->on_bi.bi_private;
2058                 Operation op2 = {0};
2059                 void *cids[SLAP_MAX_CIDS];
2060                 SlapReply rs2 = {REP_RESULT};
2061                 Entry *e;
2062
2063                 if ( !( li->li_ops & LOG_OP_UNBIND )) {
2064                         log_base *lb;
2065                         int i = 0;
2066
2067                         for ( lb = li->li_bases; lb; lb=lb->lb_next )
2068                                 if (( lb->lb_ops & LOG_OP_UNBIND ) && dnIsSuffix( &op->o_ndn, &lb->lb_base )) {
2069                                         i = 1;
2070                                         break;
2071                                 }
2072                         if ( !i )
2073                                 return SLAP_CB_CONTINUE;
2074                 }
2075
2076                 e = accesslog_entry( op, rs, LOG_EN_UNBIND, &op2 );
2077                 op2.o_hdr = op->o_hdr;
2078                 op2.o_tag = LDAP_REQ_ADD;
2079                 op2.o_bd = li->li_db;
2080                 op2.o_dn = li->li_db->be_rootdn;
2081                 op2.o_ndn = li->li_db->be_rootndn;
2082                 op2.o_req_dn = e->e_name;
2083                 op2.o_req_ndn = e->e_nname;
2084                 op2.ora_e = e;
2085                 op2.o_callback = &nullsc;
2086                 op2.o_controls = cids;
2087                 memset(cids, 0, sizeof( cids ));
2088
2089                 op2.o_bd->be_add( &op2, &rs2 );
2090                 if ( e == op2.ora_e )
2091                         entry_free( e );
2092         }
2093         return SLAP_CB_CONTINUE;
2094 }
2095
2096 static int
2097 accesslog_abandon( Operation *op, SlapReply *rs )
2098 {
2099         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2100         log_info *li = on->on_bi.bi_private;
2101         Operation op2 = {0};
2102         void *cids[SLAP_MAX_CIDS];
2103         SlapReply rs2 = {REP_RESULT};
2104         Entry *e;
2105         char buf[64];
2106         struct berval bv;
2107
2108         if ( !op->o_time )
2109                 return SLAP_CB_CONTINUE;
2110
2111         if ( !( li->li_ops & LOG_OP_ABANDON )) {
2112                 log_base *lb;
2113                 int i = 0;
2114
2115                 for ( lb = li->li_bases; lb; lb=lb->lb_next )
2116                         if (( lb->lb_ops & LOG_OP_ABANDON ) && dnIsSuffix( &op->o_ndn, &lb->lb_base )) {
2117                                 i = 1;
2118                                 break;
2119                         }
2120                 if ( !i )
2121                         return SLAP_CB_CONTINUE;
2122         }
2123
2124         e = accesslog_entry( op, rs, LOG_EN_ABANDON, &op2 );
2125         bv.bv_val = buf;
2126         bv.bv_len = snprintf( buf, sizeof( buf ), "%d", op->orn_msgid );
2127         if ( bv.bv_len < sizeof( buf ) ) {
2128                 attr_merge_one( e, ad_reqId, &bv, NULL );
2129         } /* else? */
2130
2131         op2.o_hdr = op->o_hdr;
2132         op2.o_tag = LDAP_REQ_ADD;
2133         op2.o_bd = li->li_db;
2134         op2.o_dn = li->li_db->be_rootdn;
2135         op2.o_ndn = li->li_db->be_rootndn;
2136         op2.o_req_dn = e->e_name;
2137         op2.o_req_ndn = e->e_nname;
2138         op2.ora_e = e;
2139         op2.o_callback = &nullsc;
2140         op2.o_controls = cids;
2141         memset(cids, 0, sizeof( cids ));
2142
2143         op2.o_bd->be_add( &op2, &rs2 );
2144         if ( e == op2.ora_e )
2145                 entry_free( e );
2146
2147         return SLAP_CB_CONTINUE;
2148 }
2149
2150 static int
2151 accesslog_operational( Operation *op, SlapReply *rs )
2152 {
2153         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2154         log_info *li = on->on_bi.bi_private;
2155
2156         if ( op->o_sync != SLAP_CONTROL_NONE )
2157                 return SLAP_CB_CONTINUE;
2158
2159         if ( rs->sr_entry != NULL
2160                 && dn_match( &op->o_bd->be_nsuffix[0], &rs->sr_entry->e_nname ) )
2161         {
2162                 Attribute       **ap;
2163
2164                 for ( ap = &rs->sr_operational_attrs; *ap; ap = &(*ap)->a_next )
2165                         /* just count */ ;
2166
2167                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
2168                                 ad_inlist( ad_auditContext, rs->sr_attrs ) )
2169                 {
2170                         *ap = attr_alloc( ad_auditContext );
2171                         attr_valadd( *ap,
2172                                 &li->li_db->be_suffix[0],
2173                                 &li->li_db->be_nsuffix[0], 1 );
2174                 }
2175         }
2176
2177         return SLAP_CB_CONTINUE;
2178 }
2179
2180 static slap_overinst accesslog;
2181
2182 static int
2183 accesslog_db_init(
2184         BackendDB *be,
2185         ConfigReply *cr
2186 )
2187 {
2188         slap_overinst *on = (slap_overinst *)be->bd_info;
2189         log_info *li = ch_calloc(1, sizeof(log_info));
2190
2191         on->on_bi.bi_private = li;
2192         ldap_pvt_thread_rmutex_init( &li->li_op_rmutex );
2193         ldap_pvt_thread_mutex_init( &li->li_log_mutex );
2194         return 0;
2195 }
2196
2197 static int
2198 accesslog_db_destroy(
2199         BackendDB *be,
2200         ConfigReply *cr
2201 )
2202 {
2203         slap_overinst *on = (slap_overinst *)be->bd_info;
2204         log_info *li = on->on_bi.bi_private;
2205         log_attr *la;
2206
2207         if ( li->li_oldf )
2208                 filter_free( li->li_oldf );
2209         for ( la=li->li_oldattrs; la; la=li->li_oldattrs ) {
2210                 li->li_oldattrs = la->next;
2211                 ch_free( la );
2212         }
2213         ldap_pvt_thread_mutex_destroy( &li->li_log_mutex );
2214         ldap_pvt_thread_rmutex_destroy( &li->li_op_rmutex );
2215         free( li );
2216         return LDAP_SUCCESS;
2217 }
2218
2219 /* Create the logdb's root entry if it's missing */
2220 static void *
2221 accesslog_db_root(
2222         void *ctx,
2223         void *arg )
2224 {
2225         struct re_s *rtask = arg;
2226         slap_overinst *on = rtask->arg;
2227         log_info *li = on->on_bi.bi_private;
2228
2229         Connection conn = {0};
2230         OperationBuffer opbuf;
2231         Operation *op;
2232
2233         Entry *e;
2234         int rc;
2235
2236         connection_fake_init( &conn, &opbuf, ctx );
2237         op = &opbuf.ob_op;
2238         op->o_bd = li->li_db;
2239         op->o_dn = li->li_db->be_rootdn;
2240         op->o_ndn = li->li_db->be_rootndn;
2241         rc = be_entry_get_rw( op, li->li_db->be_nsuffix, NULL, NULL, 0, &e );
2242
2243         if ( e ) {
2244                 be_entry_release_rw( op, e, 0 );
2245
2246         } else {
2247                 SlapReply rs = {REP_RESULT};
2248                 struct berval rdn, nrdn, attr;
2249                 char *ptr;
2250                 AttributeDescription *ad = NULL;
2251                 const char *text = NULL;
2252                 Entry *e_ctx;
2253                 BackendDB db;
2254
2255                 e = entry_alloc();
2256                 ber_dupbv( &e->e_name, li->li_db->be_suffix );
2257                 ber_dupbv( &e->e_nname, li->li_db->be_nsuffix );
2258
2259                 attr_merge_one( e, slap_schema.si_ad_objectClass,
2260                         &log_container->soc_cname, NULL );
2261
2262                 dnRdn( &e->e_name, &rdn );
2263                 dnRdn( &e->e_nname, &nrdn );
2264                 ptr = ber_bvchr( &rdn, '=' );
2265
2266                 assert( ptr != NULL );
2267
2268                 attr.bv_val = rdn.bv_val;
2269                 attr.bv_len = ptr - rdn.bv_val;
2270
2271                 slap_bv2ad( &attr, &ad, &text );
2272
2273                 rdn.bv_val = ptr+1;
2274                 rdn.bv_len -= attr.bv_len + 1;
2275                 ptr = ber_bvchr( &nrdn, '=' );
2276                 nrdn.bv_len -= ptr - nrdn.bv_val + 1;
2277                 nrdn.bv_val = ptr+1;
2278                 attr_merge_one( e, ad, &rdn, &nrdn );
2279
2280                 /* Get contextCSN from main DB */
2281                 op->o_bd = on->on_info->oi_origdb;
2282                 rc = be_entry_get_rw( op, op->o_bd->be_nsuffix, NULL,
2283                         slap_schema.si_ad_contextCSN, 0, &e_ctx );
2284
2285                 if ( e_ctx ) {
2286                         Attribute *a;
2287
2288                         a = attr_find( e_ctx->e_attrs, slap_schema.si_ad_contextCSN );
2289                         if ( a ) {
2290                                 /* FIXME: contextCSN could have multiple values!
2291                                  * should select the one with the server's SID */
2292                                 attr_merge_one( e, slap_schema.si_ad_entryCSN,
2293                                         &a->a_vals[0], &a->a_nvals[0] );
2294                                 attr_merge( e, a->a_desc, a->a_vals, a->a_nvals );
2295                         }
2296                         be_entry_release_rw( op, e_ctx, 0 );
2297                 }
2298                 db = *li->li_db;
2299                 op->o_bd = &db;
2300
2301                 op->ora_e = e;
2302                 op->o_req_dn = e->e_name;
2303                 op->o_req_ndn = e->e_nname;
2304                 op->o_callback = &nullsc;
2305                 SLAP_DBFLAGS( op->o_bd ) |= SLAP_DBFLAG_NOLASTMOD;
2306                 rc = op->o_bd->be_add( op, &rs );
2307                 if ( e == op->ora_e )
2308                         entry_free( e );
2309         }
2310         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2311         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2312         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
2313         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2314
2315         return NULL;
2316 }
2317
2318 static int
2319 accesslog_db_open(
2320         BackendDB *be,
2321         ConfigReply *cr
2322 )
2323 {
2324         slap_overinst *on = (slap_overinst *)be->bd_info;
2325         log_info *li = on->on_bi.bi_private;
2326
2327
2328         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
2329                 li->li_db = select_backend( &li->li_db_suffix, 0 );
2330                 ch_free( li->li_db_suffix.bv_val );
2331                 BER_BVZERO( &li->li_db_suffix );
2332         }
2333         if ( li->li_db == NULL ) {
2334                 Debug( LDAP_DEBUG_ANY,
2335                         "accesslog: \"logdb <suffix>\" missing or invalid.\n",
2336                         0, 0, 0 );
2337                 return 1;
2338         }
2339
2340         if ( slapMode & SLAP_TOOL_MODE )
2341                 return 0;
2342
2343         if ( BER_BVISEMPTY( &li->li_db->be_rootndn )) {
2344                 ber_dupbv( &li->li_db->be_rootdn, li->li_db->be_suffix );
2345                 ber_dupbv( &li->li_db->be_rootndn, li->li_db->be_nsuffix );
2346         }
2347
2348         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2349         ldap_pvt_runqueue_insert( &slapd_rq, 3600, accesslog_db_root, on,
2350                 "accesslog_db_root", li->li_db->be_suffix[0].bv_val );
2351         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2352
2353         return 0;
2354 }
2355
2356 int accesslog_initialize()
2357 {
2358         int i, rc;
2359
2360         accesslog.on_bi.bi_type = "accesslog";
2361         accesslog.on_bi.bi_db_init = accesslog_db_init;
2362         accesslog.on_bi.bi_db_destroy = accesslog_db_destroy;
2363         accesslog.on_bi.bi_db_open = accesslog_db_open;
2364
2365         accesslog.on_bi.bi_op_add = accesslog_op_mod;
2366         accesslog.on_bi.bi_op_bind = accesslog_op_bind;
2367         accesslog.on_bi.bi_op_delete = accesslog_op_mod;
2368         accesslog.on_bi.bi_op_modify = accesslog_op_mod;
2369         accesslog.on_bi.bi_op_modrdn = accesslog_op_mod;
2370         accesslog.on_bi.bi_op_unbind = accesslog_unbind;
2371         accesslog.on_bi.bi_op_abandon = accesslog_abandon;
2372         accesslog.on_bi.bi_operational = accesslog_operational;
2373         accesslog.on_response = accesslog_response;
2374
2375         accesslog.on_bi.bi_cf_ocs = log_cfocs;
2376
2377         nullsc.sc_response = slap_null_cb;
2378
2379         rc = config_register_schema( log_cfats, log_cfocs );
2380         if ( rc ) return rc;
2381
2382         /* log schema integration */
2383         for ( i=0; lsyntaxes[i].oid; i++ ) {
2384                 int code;
2385
2386                 code = register_syntax( &lsyntaxes[ i ].syn );
2387                 if ( code != 0 ) {
2388                         Debug( LDAP_DEBUG_ANY,
2389                                 "accesslog_init: register_syntax failed\n",
2390                                 0, 0, 0 );
2391                         return code;
2392                 }
2393
2394                 if ( lsyntaxes[i].mrs != NULL ) {
2395                         code = mr_make_syntax_compat_with_mrs(
2396                                 lsyntaxes[i].oid, lsyntaxes[i].mrs );
2397                         if ( code < 0 ) {
2398                                 Debug( LDAP_DEBUG_ANY,
2399                                         "accesslog_init: "
2400                                         "mr_make_syntax_compat_with_mrs "
2401                                         "failed\n",
2402                                         0, 0, 0 );
2403                                 return code;
2404                         }
2405                 }
2406         }
2407
2408         for ( i=0; lattrs[i].at; i++ ) {
2409                 int code;
2410
2411                 code = register_at( lattrs[i].at, lattrs[i].ad, 0 );
2412                 if ( code ) {
2413                         Debug( LDAP_DEBUG_ANY,
2414                                 "accesslog_init: register_at failed\n",
2415                                 0, 0, 0 );
2416                         return -1;
2417                 }
2418         }
2419
2420         for ( i=0; locs[i].ot; i++ ) {
2421                 int code;
2422
2423                 code = register_oc( locs[i].ot, locs[i].oc, 0 );
2424                 if ( code ) {
2425                         Debug( LDAP_DEBUG_ANY,
2426                                 "accesslog_init: register_oc failed\n",
2427                                 0, 0, 0 );
2428                         return -1;
2429                 }
2430         }
2431
2432         return overlay_register(&accesslog);
2433 }
2434
2435 #if SLAPD_OVER_ACCESSLOG == SLAPD_MOD_DYNAMIC
2436 int
2437 init_module( int argc, char *argv[] )
2438 {
2439         return accesslog_initialize();
2440 }
2441 #endif
2442
2443 #endif /* SLAPD_OVER_ACCESSLOG */