]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/accesslog.c
cc6112cdd60cef496365de5723c0b3dcdf006569
[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-2015 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 = { NULL, NULL, NULL, NULL };
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 };
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                 }
705                 ch_free( pd.ndn );
706                 ch_free( pd.dn );
707
708                 {
709                         Modifications mod;
710                         struct berval bv[2];
711                         rs_reinit( &rs, REP_RESULT );
712                         /* update context's entryCSN to reflect oldest CSN */
713                         mod.sml_numvals = 1;
714                         mod.sml_values = bv;
715                         bv[0] = pd.csn;
716                         BER_BVZERO(&bv[1]);
717                         mod.sml_nvalues = NULL;
718                         mod.sml_desc = slap_schema.si_ad_entryCSN;
719                         mod.sml_op = LDAP_MOD_REPLACE;
720                         mod.sml_flags = SLAP_MOD_INTERNAL;
721                         mod.sml_next = NULL;
722
723                         op->o_tag = LDAP_REQ_MODIFY;
724                         op->orm_modlist = &mod;
725                         op->orm_no_opattrs = 1;
726                         op->o_req_dn = li->li_db->be_suffix[0];
727                         op->o_req_ndn = li->li_db->be_nsuffix[0];
728                         op->o_no_schema_check = 1;
729                         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
730                         op->o_bd->be_modify( op, &rs );
731                         if ( mod.sml_next ) {
732                                 slap_mods_free( mod.sml_next, 1 );
733                         }
734                 }
735         }
736
737         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
738         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
739         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
740
741         return NULL;
742 }
743
744 static int
745 log_cf_gen(ConfigArgs *c)
746 {
747         slap_overinst *on = (slap_overinst *)c->bi;
748         struct log_info *li = on->on_bi.bi_private;
749         int rc = 0;
750         slap_mask_t tmask = 0;
751         char agebuf[2*STRLENOF("ddddd+hh:mm:ss  ")];
752         struct berval agebv, cyclebv;
753
754         switch( c->op ) {
755         case SLAP_CONFIG_EMIT:
756                 switch( c->type ) {
757                 case LOG_DB:
758                         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
759                                 value_add_one( &c->rvalue_vals, &li->li_db_suffix );
760                                 value_add_one( &c->rvalue_nvals, &li->li_db_suffix );
761                         } else if ( li->li_db ) {
762                                 value_add_one( &c->rvalue_vals, li->li_db->be_suffix );
763                                 value_add_one( &c->rvalue_nvals, li->li_db->be_nsuffix );
764                         } else {
765                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
766                                         "accesslog: \"logdb <suffix>\" must be specified" );
767                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
768                                         c->log, c->cr_msg, c->value_dn.bv_val );
769                                 rc = 1;
770                                 break;
771                         }
772                         break;
773                 case LOG_OPS:
774                         rc = mask_to_verbs( logops, li->li_ops, &c->rvalue_vals );
775                         break;
776                 case LOG_PURGE:
777                         if ( !li->li_age ) {
778                                 rc = 1;
779                                 break;
780                         }
781                         agebv.bv_val = agebuf;
782                         log_age_unparse( li->li_age, &agebv, sizeof( agebuf ) );
783                         agebv.bv_val[agebv.bv_len] = ' ';
784                         agebv.bv_len++;
785                         cyclebv.bv_val = agebv.bv_val + agebv.bv_len;
786                         log_age_unparse( li->li_cycle, &cyclebv, sizeof( agebuf ) - agebv.bv_len );
787                         agebv.bv_len += cyclebv.bv_len;
788                         value_add_one( &c->rvalue_vals, &agebv );
789                         break;
790                 case LOG_SUCCESS:
791                         if ( li->li_success )
792                                 c->value_int = li->li_success;
793                         else
794                                 rc = 1;
795                         break;
796                 case LOG_OLD:
797                         if ( li->li_oldf ) {
798                                 filter2bv( li->li_oldf, &agebv );
799                                 ber_bvarray_add( &c->rvalue_vals, &agebv );
800                         }
801                         else
802                                 rc = 1;
803                         break;
804                 case LOG_OLDATTR:
805                         if ( li->li_oldattrs ) {
806                                 log_attr *la;
807
808                                 for ( la = li->li_oldattrs; la; la=la->next )
809                                         value_add_one( &c->rvalue_vals, &la->attr->ad_cname );
810                         }
811                         else
812                                 rc = 1;
813                         break;
814                 case LOG_BASE:
815                         if ( li->li_bases ) {
816                                 log_base *lb;
817
818                                 for ( lb = li->li_bases; lb; lb=lb->lb_next )
819                                         value_add_one( &c->rvalue_vals, &lb->lb_line );
820                         }
821                         else
822                                 rc = 1;
823                         break;
824                 }
825                 break;
826         case LDAP_MOD_DELETE:
827                 switch( c->type ) {
828                 case LOG_DB:
829                         /* noop. this should always be a valid backend. */
830                         break;
831                 case LOG_OPS:
832                         if ( c->valx < 0 ) {
833                                 li->li_ops = 0;
834                         } else {
835                                 rc = verbs_to_mask( 1, &c->line, logops, &tmask );
836                                 if ( rc == 0 )
837                                         li->li_ops &= ~tmask;
838                         }
839                         break;
840                 case LOG_PURGE:
841                         if ( li->li_task ) {
842                                 struct re_s *re = li->li_task;
843                                 li->li_task = NULL;
844                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
845                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
846                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
847                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
848                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
849                         }
850                         li->li_age = 0;
851                         li->li_cycle = 0;
852                         break;
853                 case LOG_SUCCESS:
854                         li->li_success = 0;
855                         break;
856                 case LOG_OLD:
857                         if ( li->li_oldf ) {
858                                 filter_free( li->li_oldf );
859                                 li->li_oldf = NULL;
860                         }
861                         break;
862                 case LOG_OLDATTR:
863                         if ( c->valx < 0 ) {
864                                 log_attr *la, *ln;
865
866                                 for ( la = li->li_oldattrs; la; la = ln ) {
867                                         ln = la->next;
868                                         ch_free( la );
869                                 }
870                         } else {
871                                 log_attr *la = NULL, **lp;
872                                 int i;
873
874                                 for ( lp = &li->li_oldattrs, i=0; i < c->valx; i++ ) {
875                                         la = *lp;
876                                         lp = &la->next;
877                                 }
878                                 *lp = la->next;
879                                 ch_free( la );
880                         }
881                         break;
882                 case LOG_BASE:
883                         if ( c->valx < 0 ) {
884                                 log_base *lb, *ln;
885
886                                 for ( lb = li->li_bases; lb; lb = ln ) {
887                                         ln = lb->lb_next;
888                                         ch_free( lb );
889                                 }
890                         } else {
891                                 log_base *lb = NULL, **lp;
892                                 int i;
893
894                                 for ( lp = &li->li_bases, i=0; i < c->valx; i++ ) {
895                                         lb = *lp;
896                                         lp = &lb->lb_next;
897                                 }
898                                 *lp = lb->lb_next;
899                                 ch_free( lb );
900                         }
901                         break;
902                 }
903                 break;
904         default:
905                 switch( c->type ) {
906                 case LOG_DB:
907                         if ( CONFIG_ONLINE_ADD( c )) {
908                                 li->li_db = select_backend( &c->value_ndn, 0 );
909                                 if ( !li->li_db ) {
910                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
911                                                 "<%s> no matching backend found for suffix",
912                                                 c->argv[0] );
913                                         Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
914                                                 c->log, c->cr_msg, c->value_dn.bv_val );
915                                         rc = 1;
916                                 }
917                                 ch_free( c->value_ndn.bv_val );
918                         } else {
919                                 li->li_db_suffix = c->value_ndn;
920                         }
921                         ch_free( c->value_dn.bv_val );
922                         break;
923                 case LOG_OPS:
924                         rc = verbs_to_mask( c->argc, c->argv, logops, &tmask );
925                         if ( rc == 0 )
926                                 li->li_ops |= tmask;
927                         break;
928                 case LOG_PURGE:
929                         li->li_age = log_age_parse( c->argv[1] );
930                         if ( li->li_age < 1 ) {
931                                 rc = 1;
932                         } else {
933                                 li->li_cycle = log_age_parse( c->argv[2] );
934                                 if ( li->li_cycle < 1 ) {
935                                         rc = 1;
936                                 } else if ( slapMode & SLAP_SERVER_MODE ) {
937                                         struct re_s *re = li->li_task;
938                                         if ( re )
939                                                 re->interval.tv_sec = li->li_cycle;
940                                         else {
941                                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
942                                                 li->li_task = ldap_pvt_runqueue_insert( &slapd_rq,
943                                                         li->li_cycle, accesslog_purge, li,
944                                                         "accesslog_purge", li->li_db ?
945                                                                 li->li_db->be_suffix[0].bv_val :
946                                                                 c->be->be_suffix[0].bv_val );
947                                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
948                                         }
949                                 }
950                         }
951                         break;
952                 case LOG_SUCCESS:
953                         li->li_success = c->value_int;
954                         break;
955                 case LOG_OLD:
956                         li->li_oldf = str2filter( c->argv[1] );
957                         if ( !li->li_oldf ) {
958                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "bad filter!" );
959                                 rc = 1;
960                         }
961                         break;
962                 case LOG_OLDATTR: {
963                         int i;
964                         AttributeDescription *ad;
965                         const char *text;
966
967                         for ( i=1; i< c->argc; i++ ) {
968                                 ad = NULL;
969                                 if ( slap_str2ad( c->argv[i], &ad, &text ) == LDAP_SUCCESS ) {
970                                         log_attr *la = ch_malloc( sizeof( log_attr ));
971                                         la->attr = ad;
972                                         la->next = li->li_oldattrs;
973                                         li->li_oldattrs = la;
974                                 } else {
975                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s <%s>: %s",
976                                                 c->argv[0], c->argv[i], text );
977                                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
978                                                 "%s: %s\n", c->log, c->cr_msg, 0 );
979                                         rc = ARG_BAD_CONF;
980                                         break;
981                                 }
982                         }
983                         }
984                         break;
985                 case LOG_BASE: {
986                         slap_mask_t m = 0;
987                         rc = verbstring_to_mask( logops, c->argv[1], '|', &m );
988                         if ( rc == 0 ) {
989                                 struct berval dn, ndn;
990                                 ber_str2bv( c->argv[2], 0, 0, &dn );
991                                 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
992                                 if ( rc == 0 ) {
993                                         log_base *lb;
994                                         struct berval mbv;
995                                         char *ptr;
996                                         mask_to_verbstring( logops, m, '|', &mbv );
997                                         lb = ch_malloc( sizeof( log_base ) + mbv.bv_len + ndn.bv_len + 3 + 1 );
998                                         lb->lb_line.bv_val = (char *)(lb + 1);
999                                         lb->lb_line.bv_len = mbv.bv_len + ndn.bv_len + 3;
1000                                         ptr = lutil_strcopy( lb->lb_line.bv_val, mbv.bv_val );
1001                                         *ptr++ = ' ';
1002                                         *ptr++ = '"';
1003                                         lb->lb_base.bv_val = ptr;
1004                                         lb->lb_base.bv_len = ndn.bv_len;
1005                                         ptr = lutil_strcopy( ptr, ndn.bv_val );
1006                                         *ptr++ = '"';
1007                                         lb->lb_ops = m;
1008                                         lb->lb_next = li->li_bases;
1009                                         li->li_bases = lb;
1010                                 } else {
1011                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid DN: %s",
1012                                                 c->argv[0], c->argv[2] );
1013                                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
1014                                                 "%s: %s\n", c->log, c->cr_msg, 0 );
1015                                         rc = ARG_BAD_CONF;
1016                                 }
1017                         } else {
1018                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid ops: %s",
1019                                         c->argv[0], c->argv[1] );
1020                                 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
1021                                         "%s: %s\n", c->log, c->cr_msg, 0 );
1022                                 rc = ARG_BAD_CONF;
1023                         }
1024                         }
1025                         break;
1026                 }
1027                 break;
1028         }
1029         return rc;
1030 }
1031
1032 static int
1033 logSchemaControlValidate(
1034         Syntax          *syntax,
1035         struct berval   *valp )
1036 {
1037         struct berval   val, bv;
1038         ber_len_t               i;
1039         int             rc = LDAP_SUCCESS;
1040
1041         assert( valp != NULL );
1042
1043         val = *valp;
1044
1045         /* check minimal size */
1046         if ( val.bv_len < STRLENOF( "{*}" ) ) {
1047                 return LDAP_INVALID_SYNTAX;
1048         }
1049
1050         val.bv_len--;
1051
1052         /* check SEQUENCE boundaries */
1053         if ( val.bv_val[ 0 ] != '{' /*}*/ ||
1054                 val.bv_val[ val.bv_len ] != /*{*/ '}' )
1055         {
1056                 return LDAP_INVALID_SYNTAX;
1057         }
1058
1059         /* extract and check OID */
1060         for ( i = 1; i < val.bv_len; i++ ) {
1061                 if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1062                         break;
1063                 }
1064         }
1065
1066         bv.bv_val = &val.bv_val[ i ];
1067
1068         for ( i++; i < val.bv_len; i++ ) {
1069                 if ( ASCII_SPACE( val.bv_val[ i ] ) )
1070                 {
1071                         break;
1072                 }
1073         }
1074
1075         bv.bv_len = &val.bv_val[ i ] - bv.bv_val;
1076
1077         rc = numericoidValidate( NULL, &bv );
1078         if ( rc != LDAP_SUCCESS ) {
1079                 return rc;
1080         }
1081
1082         if ( i == val.bv_len ) {
1083                 return LDAP_SUCCESS;
1084         }
1085
1086         if ( val.bv_val[ i ] != ' ' ) {
1087                 return LDAP_INVALID_SYNTAX;
1088         }
1089
1090         for ( i++; i < val.bv_len; i++ ) {
1091                 if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1092                         break;
1093                 }
1094         }
1095
1096         if ( i == val.bv_len ) {
1097                 return LDAP_SUCCESS;
1098         }
1099
1100         /* extract and check criticality */
1101         if ( strncasecmp( &val.bv_val[ i ], "criticality ", STRLENOF( "criticality " ) ) == 0 )
1102         {
1103                 i += STRLENOF( "criticality " );
1104                 for ( ; i < val.bv_len; i++ ) {
1105                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1106                                 break;
1107                         }
1108                 }
1109
1110                 if ( i == val.bv_len ) {
1111                         return LDAP_INVALID_SYNTAX;
1112                 }
1113
1114                 bv.bv_val = &val.bv_val[ i ];
1115
1116                 for ( ; i < val.bv_len; i++ ) {
1117                         if ( ASCII_SPACE( val.bv_val[ i ] ) ) {
1118                                 break;
1119                         }
1120                 }
1121
1122                 bv.bv_len = &val.bv_val[ i ] - bv.bv_val;
1123
1124                 if ( !bvmatch( &bv, &slap_true_bv ) && !bvmatch( &bv, &slap_false_bv ) ) 
1125                 {
1126                         return LDAP_INVALID_SYNTAX;
1127                 }
1128
1129                 if ( i == val.bv_len ) {
1130                         return LDAP_SUCCESS;
1131                 }
1132
1133                 if ( val.bv_val[ i ] != ' ' ) {
1134                         return LDAP_INVALID_SYNTAX;
1135                 }
1136
1137                 for ( i++; i < val.bv_len; i++ ) {
1138                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1139                                 break;
1140                         }
1141                 }
1142
1143                 if ( i == val.bv_len ) {
1144                         return LDAP_SUCCESS;
1145                 }
1146         }
1147
1148         /* extract and check controlValue */
1149         if ( strncasecmp( &val.bv_val[ i ], "controlValue ", STRLENOF( "controlValue " ) ) == 0 )
1150         {
1151                 ber_len_t valueStart, valueLen;
1152
1153                 i += STRLENOF( "controlValue " );
1154                 for ( ; i < val.bv_len; i++ ) {
1155                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1156                                 break;
1157                         }
1158                 }
1159
1160                 if ( i == val.bv_len ) {
1161                         return LDAP_INVALID_SYNTAX;
1162                 }
1163
1164                 if ( val.bv_val[ i ] != '"' ) {
1165                         return LDAP_INVALID_SYNTAX;
1166                 }
1167
1168                 i++;
1169                 valueStart = i;
1170
1171                 for ( ; i < val.bv_len; i++ ) {
1172                         if ( val.bv_val[ i ] == '"' ) {
1173                                 break;
1174                         }
1175
1176                         if ( !ASCII_HEX( val.bv_val[ i ] ) ) {
1177                                 return LDAP_INVALID_SYNTAX;
1178                         }
1179                 }
1180
1181                 if ( val.bv_val[ i ] != '"' ) {
1182                         return LDAP_INVALID_SYNTAX;
1183                 }
1184
1185                 valueLen = i - valueStart;
1186                 if ( (valueLen/2)*2 != valueLen ) {
1187                         return LDAP_INVALID_SYNTAX;
1188                 }
1189
1190                 for ( i++; i < val.bv_len; i++ ) {
1191                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1192                                 break;
1193                         }
1194                 }
1195
1196                 if ( i == val.bv_len ) {
1197                         return LDAP_SUCCESS;
1198                 }
1199         }
1200
1201         return LDAP_INVALID_SYNTAX;
1202 }
1203
1204 static int
1205 accesslog_ctrls(
1206         LDAPControl **ctrls,
1207         BerVarray *valsp,
1208         BerVarray *nvalsp,
1209         void *memctx )
1210 {
1211         long            i, rc = 0;
1212
1213         assert( valsp != NULL );
1214         assert( ctrls != NULL );
1215
1216         *valsp = NULL;
1217         *nvalsp = NULL;
1218
1219         for ( i = 0; ctrls[ i ] != NULL; i++ ) {
1220                 struct berval   idx,
1221                                 oid,
1222                                 noid,
1223                                 bv;
1224                 char            *ptr,
1225                                 buf[ 32 ];
1226
1227                 if ( ctrls[ i ]->ldctl_oid == NULL ) {
1228                         return LDAP_PROTOCOL_ERROR;
1229                 }
1230
1231                 idx.bv_len = snprintf( buf, sizeof( buf ), "{%ld}", i );
1232                 idx.bv_val = buf;
1233
1234                 ber_str2bv( ctrls[ i ]->ldctl_oid, 0, 0, &oid );
1235                 noid.bv_len = idx.bv_len + oid.bv_len;
1236                 ptr = noid.bv_val = ber_memalloc_x( noid.bv_len + 1, memctx );
1237                 ptr = lutil_strcopy( ptr, idx.bv_val );
1238                 ptr = lutil_strcopy( ptr, oid.bv_val );
1239
1240                 bv.bv_len = idx.bv_len + STRLENOF( "{}" ) + oid.bv_len;
1241
1242                 if ( ctrls[ i ]->ldctl_iscritical ) {
1243                         bv.bv_len += STRLENOF( " criticality TRUE" );
1244                 }
1245
1246                 if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
1247                         bv.bv_len += STRLENOF( " controlValue \"\"" )
1248                                 + 2 * ctrls[ i ]->ldctl_value.bv_len;
1249                 }
1250
1251                 ptr = bv.bv_val = ber_memalloc_x( bv.bv_len + 1, memctx );
1252                 if ( ptr == NULL ) {
1253                         ber_bvarray_free( *valsp );
1254                         *valsp = NULL;
1255                         ber_bvarray_free( *nvalsp );
1256                         *nvalsp = NULL;
1257                         return LDAP_OTHER;
1258                 }
1259
1260                 ptr = lutil_strcopy( ptr, idx.bv_val );
1261
1262                 *ptr++ = '{' /*}*/ ;
1263                 ptr = lutil_strcopy( ptr, oid.bv_val );
1264
1265                 if ( ctrls[ i ]->ldctl_iscritical ) {
1266                         ptr = lutil_strcopy( ptr, " criticality TRUE" );
1267                 }
1268                 
1269                 if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
1270                         ber_len_t       j;
1271
1272                         ptr = lutil_strcopy( ptr, " controlValue \"" );
1273                         for ( j = 0; j < ctrls[ i ]->ldctl_value.bv_len; j++ ) {
1274                                 *ptr++ = SLAP_ESCAPE_HI(ctrls[ i ]->ldctl_value.bv_val[ j ]);
1275                                 *ptr++ = SLAP_ESCAPE_LO(ctrls[ i ]->ldctl_value.bv_val[ j ]);
1276                         }
1277
1278                         *ptr++ = '"';
1279                 }
1280
1281                 *ptr++ = '}';
1282                 *ptr = '\0';
1283
1284                 ber_bvarray_add_x( valsp, &bv, memctx );
1285                 ber_bvarray_add_x( nvalsp, &noid, memctx );
1286         }
1287
1288         return rc;
1289         
1290 }
1291
1292 static Entry *accesslog_entry( Operation *op, SlapReply *rs, int logop,
1293         Operation *op2 ) {
1294         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1295         log_info *li = on->on_bi.bi_private;
1296
1297         char rdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
1298         char nrdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
1299
1300         struct berval rdn, nrdn, timestamp, ntimestamp, bv;
1301         slap_verbmasks *lo = logops+logop+EN_OFFSET;
1302
1303         Entry *e = entry_alloc();
1304
1305         strcpy( rdnbuf, RDNEQ );
1306         rdn.bv_val = rdnbuf;
1307         strcpy( nrdnbuf, RDNEQ );
1308         nrdn.bv_val = nrdnbuf;
1309
1310         timestamp.bv_val = rdnbuf+STRLENOF(RDNEQ);
1311         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
1312         slap_timestamp( &op->o_time, &timestamp );
1313         snprintf( timestamp.bv_val + timestamp.bv_len-1, sizeof(".123456Z"), ".%06dZ", op->o_tincr );
1314         timestamp.bv_len += STRLENOF(".123456");
1315
1316         rdn.bv_len = STRLENOF(RDNEQ)+timestamp.bv_len;
1317         ad_reqStart->ad_type->sat_equality->smr_normalize(
1318                 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, ad_reqStart->ad_type->sat_syntax,
1319                 ad_reqStart->ad_type->sat_equality, &timestamp, &ntimestamp,
1320                 op->o_tmpmemctx );
1321
1322         strcpy( nrdn.bv_val + STRLENOF(RDNEQ), ntimestamp.bv_val );
1323         nrdn.bv_len = STRLENOF(RDNEQ)+ntimestamp.bv_len;
1324         build_new_dn( &e->e_name, li->li_db->be_suffix, &rdn, NULL );
1325         build_new_dn( &e->e_nname, li->li_db->be_nsuffix, &nrdn, NULL );
1326
1327         attr_merge_one( e, slap_schema.si_ad_objectClass,
1328                 &log_ocs[logop]->soc_cname, NULL );
1329         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
1330                 &log_ocs[logop]->soc_cname, NULL );
1331         attr_merge_one( e, ad_reqStart, &timestamp, &ntimestamp );
1332         op->o_tmpfree( ntimestamp.bv_val, op->o_tmpmemctx );
1333
1334         slap_op_time( &op2->o_time, &op2->o_tincr );
1335
1336         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
1337         slap_timestamp( &op2->o_time, &timestamp );
1338         snprintf( timestamp.bv_val + timestamp.bv_len-1, sizeof(".123456Z"), ".%06dZ", op2->o_tincr );
1339         timestamp.bv_len += STRLENOF(".123456");
1340
1341         attr_merge_normalize_one( e, ad_reqEnd, &timestamp, op->o_tmpmemctx );
1342
1343         /* Exops have OID appended */
1344         if ( logop == LOG_EN_EXTENDED ) {
1345                 bv.bv_len = lo->word.bv_len + op->ore_reqoid.bv_len + 2;
1346                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
1347                 AC_MEMCPY( bv.bv_val, lo->word.bv_val, lo->word.bv_len );
1348                 bv.bv_val[lo->word.bv_len] = '{';
1349                 AC_MEMCPY( bv.bv_val+lo->word.bv_len+1, op->ore_reqoid.bv_val,
1350                         op->ore_reqoid.bv_len );
1351                 bv.bv_val[bv.bv_len-1] = '}';
1352                 bv.bv_val[bv.bv_len] = '\0';
1353                 attr_merge_one( e, ad_reqType, &bv, NULL );
1354         } else {
1355                 attr_merge_one( e, ad_reqType, &lo->word, NULL );
1356         }
1357
1358         rdn.bv_len = snprintf( rdn.bv_val, sizeof( rdnbuf ), "%lu", op->o_connid );
1359         if ( rdn.bv_len < sizeof( rdnbuf ) ) {
1360                 attr_merge_one( e, ad_reqSession, &rdn, NULL );
1361         } /* else? */
1362
1363         if ( BER_BVISNULL( &op->o_dn ) ) {
1364                 attr_merge_one( e, ad_reqAuthzID, (struct berval *)&slap_empty_bv,
1365                         (struct berval *)&slap_empty_bv );
1366         } else {
1367                 attr_merge_one( e, ad_reqAuthzID, &op->o_dn, &op->o_ndn );
1368         }
1369
1370         /* FIXME: need to add reqControls and reqRespControls */
1371         if ( op->o_ctrls ) {
1372                 BerVarray       vals = NULL,
1373                                 nvals = NULL;
1374
1375                 if ( accesslog_ctrls( op->o_ctrls, &vals, &nvals,
1376                         op->o_tmpmemctx ) == LDAP_SUCCESS && vals )
1377                 {
1378                         attr_merge( e, ad_reqControls, vals, nvals );
1379                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1380                         ber_bvarray_free_x( nvals, op->o_tmpmemctx );
1381                 }
1382         }
1383
1384         if ( rs->sr_ctrls ) {
1385                 BerVarray       vals = NULL,
1386                                 nvals = NULL;
1387
1388                 if ( accesslog_ctrls( rs->sr_ctrls, &vals, &nvals,
1389                         op->o_tmpmemctx ) == LDAP_SUCCESS && vals )
1390                 {
1391                         attr_merge( e, ad_reqRespControls, vals, nvals );
1392                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1393                         ber_bvarray_free_x( nvals, op->o_tmpmemctx );
1394                 }
1395
1396         }
1397
1398         return e;
1399 }
1400
1401 static struct berval scopes[] = {
1402         BER_BVC("base"),
1403         BER_BVC("one"),
1404         BER_BVC("sub"),
1405         BER_BVC("subord")
1406 };
1407
1408 static struct berval derefs[] = {
1409         BER_BVC("never"),
1410         BER_BVC("searching"),
1411         BER_BVC("finding"),
1412         BER_BVC("always")
1413 };
1414
1415 static struct berval simple = BER_BVC("SIMPLE");
1416
1417 static void accesslog_val2val(AttributeDescription *ad, struct berval *val,
1418         char c_op, struct berval *dst) {
1419         char *ptr;
1420
1421         dst->bv_len = ad->ad_cname.bv_len + val->bv_len + 2;
1422         if ( c_op ) dst->bv_len++;
1423
1424         dst->bv_val = ch_malloc( dst->bv_len+1 );
1425
1426         ptr = lutil_strcopy( dst->bv_val, ad->ad_cname.bv_val );
1427         *ptr++ = ':';
1428         if ( c_op )
1429                 *ptr++ = c_op;
1430         *ptr++ = ' ';
1431         AC_MEMCPY( ptr, val->bv_val, val->bv_len );
1432         dst->bv_val[dst->bv_len] = '\0';
1433 }
1434
1435 static int
1436 accesslog_op2logop( Operation *op )
1437 {
1438         switch ( op->o_tag ) {
1439         case LDAP_REQ_ADD:              return LOG_EN_ADD;
1440         case LDAP_REQ_DELETE:   return LOG_EN_DELETE;
1441         case LDAP_REQ_MODIFY:   return LOG_EN_MODIFY;
1442         case LDAP_REQ_MODRDN:   return LOG_EN_MODRDN;
1443         case LDAP_REQ_COMPARE:  return LOG_EN_COMPARE;
1444         case LDAP_REQ_SEARCH:   return LOG_EN_SEARCH;
1445         case LDAP_REQ_BIND:             return LOG_EN_BIND;
1446         case LDAP_REQ_EXTENDED: return LOG_EN_EXTENDED;
1447         default:        /* unknown operation type */
1448                 break;
1449         }       /* Unbind and Abandon never reach here */
1450         return LOG_EN_UNKNOWN;
1451 }
1452
1453 static int accesslog_response(Operation *op, SlapReply *rs) {
1454         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1455         log_info *li = on->on_bi.bi_private;
1456         Attribute *a, *last_attr;
1457         Modifications *m;
1458         struct berval *b, uuid = BER_BVNULL;
1459         int i;
1460         int logop, do_graduate = 0;
1461         slap_verbmasks *lo;
1462         Entry *e = NULL, *old = NULL, *e_uuid = NULL;
1463         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE+8];
1464         struct berval bv;
1465         char *ptr;
1466         BerVarray vals;
1467         Operation op2 = {0};
1468         SlapReply rs2 = {REP_RESULT};
1469
1470         if ( rs->sr_type != REP_RESULT && rs->sr_type != REP_EXTENDED )
1471                 return SLAP_CB_CONTINUE;
1472
1473         logop = accesslog_op2logop( op );
1474         lo = logops+logop+EN_OFFSET;
1475         if ( !( li->li_ops & lo->mask )) {
1476                 log_base *lb;
1477
1478                 i = 0;
1479                 for ( lb = li->li_bases; lb; lb=lb->lb_next )
1480                         if (( lb->lb_ops & lo->mask ) && dnIsSuffix( &op->o_req_ndn, &lb->lb_base )) {
1481                                 i = 1;
1482                                 break;
1483                         }
1484                 if ( !i )
1485                         return SLAP_CB_CONTINUE;
1486         }
1487
1488         /* mutex and so were only set for write operations;
1489          * if we got here, the operation must be logged */
1490         if ( lo->mask & LOG_OP_WRITES ) {
1491                 slap_callback *cb;
1492
1493                 /* Most internal ops are not logged */
1494                 if ( op->o_dont_replicate) {
1495                         /* Let contextCSN updates from syncrepl thru; the underlying
1496                          * syncprov needs to see them. Skip others.
1497                          */
1498                         if (( op->o_tag != LDAP_REQ_MODIFY ||
1499                                 op->orm_modlist->sml_op != LDAP_MOD_REPLACE ||
1500                                 op->orm_modlist->sml_desc != slap_schema.si_ad_contextCSN ) &&
1501                                 op->orm_no_opattrs )
1502                         return SLAP_CB_CONTINUE;
1503                 }
1504
1505                 ldap_pvt_thread_mutex_lock( &li->li_log_mutex );
1506                 old = li->li_old;
1507                 uuid = li->li_uuid;
1508                 li->li_old = NULL;
1509                 BER_BVZERO( &li->li_uuid );
1510                 /* Disarm mod_cleanup */
1511                 for ( cb = op->o_callback; cb; cb = cb->sc_next ) {
1512                         if ( cb->sc_private == (void *)on ) {
1513                                 cb->sc_private = NULL;
1514                                 break;
1515                         }
1516                 }
1517                 ldap_pvt_thread_rmutex_unlock( &li->li_op_rmutex, op->o_tid );
1518         }
1519
1520         /* ignore these internal reads */
1521         if (( lo->mask & LOG_OP_READS ) && op->o_do_not_cache ) {
1522                 return SLAP_CB_CONTINUE;
1523         }
1524
1525         if ( li->li_success && rs->sr_err != LDAP_SUCCESS )
1526                 goto done;
1527
1528         e = accesslog_entry( op, rs, logop, &op2 );
1529
1530         attr_merge_one( e, ad_reqDN, &op->o_req_dn, &op->o_req_ndn );
1531
1532         if ( rs->sr_text ) {
1533                 ber_str2bv( rs->sr_text, 0, 0, &bv );
1534                 attr_merge_normalize_one( e, ad_reqMessage, &bv, op->o_tmpmemctx );
1535         }
1536         bv.bv_len = snprintf( timebuf, sizeof( timebuf ), "%d", rs->sr_err );
1537         if ( bv.bv_len < sizeof( timebuf ) ) {
1538                 bv.bv_val = timebuf;
1539                 attr_merge_one( e, ad_reqResult, &bv, NULL );
1540         }
1541
1542         last_attr = attr_find( e->e_attrs, ad_reqResult );
1543
1544         e_uuid = old;
1545         switch( logop ) {
1546         case LOG_EN_ADD:
1547         case LOG_EN_DELETE: {
1548                 char c_op;
1549                 Entry *e2;
1550
1551                 if ( logop == LOG_EN_ADD ) {
1552                         e2 = op->ora_e;
1553                         e_uuid = op->ora_e;
1554                         c_op = '+';
1555
1556                 } else {
1557                         if ( !old )
1558                                 break;
1559                         e2 = old;
1560                         c_op = 0;
1561                 }
1562                 /* count all the vals */
1563                 i = 0;
1564                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1565                         i += a->a_numvals;
1566                 }
1567                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1568                 i = 0;
1569                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1570                         if ( a->a_vals ) {
1571                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1572                                         accesslog_val2val( a->a_desc, b, c_op, &vals[i] );
1573                                 }
1574                         }
1575                 }
1576                 vals[i].bv_val = NULL;
1577                 vals[i].bv_len = 0;
1578                 a = attr_alloc( logop == LOG_EN_ADD ? ad_reqMod : ad_reqOld );
1579                 a->a_numvals = i;
1580                 a->a_vals = vals;
1581                 a->a_nvals = vals;
1582                 last_attr->a_next = a;
1583                 break;
1584         }
1585
1586         case LOG_EN_MODRDN:
1587         case LOG_EN_MODIFY:
1588                 /* count all the mods */
1589                 i = 0;
1590                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1591                         if ( m->sml_values ) {
1592                                 i += m->sml_numvals;
1593                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1594                                 m->sml_op == LDAP_MOD_REPLACE )
1595                         {
1596                                 i++;
1597                         }
1598                 }
1599                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1600                 i = 0;
1601
1602                 /* init flags on old entry */
1603                 if ( old ) {
1604                         for ( a = old->e_attrs; a; a = a->a_next ) {
1605                                 log_attr *la;
1606                                 a->a_flags = 0;
1607
1608                                 /* look for attrs that are always logged */
1609                                 for ( la = li->li_oldattrs; la; la = la->next ) {
1610                                         if ( a->a_desc == la->attr ) {
1611                                                 a->a_flags = 1;
1612                                         }
1613                                 }
1614                         }
1615                 }
1616
1617                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1618                         /* Mark this attribute as modified */
1619                         if ( old ) {
1620                                 a = attr_find( old->e_attrs, m->sml_desc );
1621                                 if ( a ) {
1622                                         a->a_flags = 1;
1623                                 }
1624                         }
1625
1626                         /* don't log the RDN mods; they're explicitly logged later */
1627                         if ( logop == LOG_EN_MODRDN &&
1628                                 ( m->sml_op == SLAP_MOD_SOFTADD ||
1629                                   m->sml_op == LDAP_MOD_DELETE ) )
1630                         {
1631                                 continue;
1632                         }
1633
1634                         if ( m->sml_values ) {
1635                                 for ( b = m->sml_values; !BER_BVISNULL( b ); b++, i++ ) {
1636                                         char c_op;
1637
1638                                         switch ( m->sml_op ) {
1639                                         case LDAP_MOD_ADD: c_op = '+'; break;
1640                                         case LDAP_MOD_DELETE:   c_op = '-'; break;
1641                                         case LDAP_MOD_REPLACE:  c_op = '='; break;
1642                                         case LDAP_MOD_INCREMENT:        c_op = '#'; break;
1643
1644                                         /* unknown op. there shouldn't be any of these. we
1645                                          * don't know what to do with it, but we shouldn't just
1646                                          * ignore it.
1647                                          */
1648                                         default: c_op = '?'; break;
1649                                         }
1650                                         accesslog_val2val( m->sml_desc, b, c_op, &vals[i] );
1651                                 }
1652                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1653                                 m->sml_op == LDAP_MOD_REPLACE )
1654                         {
1655                                 vals[i].bv_len = m->sml_desc->ad_cname.bv_len + 2;
1656                                 vals[i].bv_val = ch_malloc( vals[i].bv_len + 1 );
1657                                 ptr = lutil_strcopy( vals[i].bv_val,
1658                                         m->sml_desc->ad_cname.bv_val );
1659                                 *ptr++ = ':';
1660                                 if ( m->sml_op == LDAP_MOD_DELETE ) {
1661                                         *ptr++ = '-';
1662                                 } else {
1663                                         *ptr++ = '=';
1664                                 }
1665                                 *ptr = '\0';
1666                                 i++;
1667                         }
1668                 }
1669
1670                 if ( i > 0 ) {
1671                         BER_BVZERO( &vals[i] );
1672                         a = attr_alloc( ad_reqMod );
1673                         a->a_numvals = i;
1674                         a->a_vals = vals;
1675                         a->a_nvals = vals;
1676                         last_attr->a_next = a;
1677                         last_attr = a;
1678
1679                 } else {
1680                         ch_free( vals );
1681                 }
1682
1683                 if ( old ) {
1684                         /* count all the vals */
1685                         i = 0;
1686                         for ( a = old->e_attrs; a != NULL; a = a->a_next ) {
1687                                 if ( a->a_vals && a->a_flags ) {
1688                                         i += a->a_numvals;
1689                                 }
1690                         }
1691                         if ( i ) {
1692                                 vals = ch_malloc( (i + 1) * sizeof( struct berval ) );
1693                                 i = 0;
1694                                 for ( a=old->e_attrs; a; a=a->a_next ) {
1695                                         if ( a->a_vals && a->a_flags ) {
1696                                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1697                                                         accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1698                                                 }
1699                                         }
1700                                 }
1701                                 vals[i].bv_val = NULL;
1702                                 vals[i].bv_len = 0;
1703                                 a = attr_alloc( ad_reqOld );
1704                                 a->a_numvals = i;
1705                                 a->a_vals = vals;
1706                                 a->a_nvals = vals;
1707                                 last_attr->a_next = a;
1708                         }
1709                 }
1710                 if ( logop == LOG_EN_MODIFY ) {
1711                         break;
1712                 }
1713
1714                 /* Now log the actual modRDN info */
1715                 attr_merge_one( e, ad_reqNewRDN, &op->orr_newrdn, &op->orr_nnewrdn );
1716                 attr_merge_one( e, ad_reqDeleteOldRDN, op->orr_deleteoldrdn ?
1717                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1718                         NULL );
1719                 if ( op->orr_newSup ) {
1720                         attr_merge_one( e, ad_reqNewSuperior, op->orr_newSup, op->orr_nnewSup );
1721                 }
1722                 break;
1723
1724         case LOG_EN_COMPARE:
1725                 bv.bv_len = op->orc_ava->aa_desc->ad_cname.bv_len + 1 +
1726                         op->orc_ava->aa_value.bv_len;
1727                 bv.bv_val = op->o_tmpalloc( bv.bv_len+1, op->o_tmpmemctx );
1728                 ptr = lutil_strcopy( bv.bv_val, op->orc_ava->aa_desc->ad_cname.bv_val );
1729                 *ptr++ = '=';
1730                 AC_MEMCPY( ptr, op->orc_ava->aa_value.bv_val, op->orc_ava->aa_value.bv_len );
1731                 bv.bv_val[bv.bv_len] = '\0';
1732                 attr_merge_one( e, ad_reqAssertion, &bv, NULL );
1733                 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1734                 break;
1735
1736         case LOG_EN_SEARCH:
1737                 attr_merge_one( e, ad_reqScope, &scopes[op->ors_scope], NULL );
1738                 attr_merge_one( e, ad_reqDerefAliases, &derefs[op->ors_deref], NULL );
1739                 attr_merge_one( e, ad_reqAttrsOnly, op->ors_attrsonly ?
1740                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1741                         NULL );
1742                 if ( !BER_BVISEMPTY( &op->ors_filterstr ))
1743                         attr_merge_normalize_one( e, ad_reqFilter, &op->ors_filterstr, op->o_tmpmemctx );
1744                 if ( op->ors_attrs ) {
1745                         int j;
1746                         /* count them */
1747                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1748                                 ;
1749                         vals = op->o_tmpalloc( (i+1) * sizeof(struct berval),
1750                                 op->o_tmpmemctx );
1751                         for (i=0, j=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++) {
1752                                 if (!BER_BVISEMPTY(&op->ors_attrs[i].an_name)) {
1753                                         vals[j] = op->ors_attrs[i].an_name;
1754                                         j++;
1755                                 }
1756                         }
1757                         BER_BVZERO(&vals[j]);
1758                         attr_merge_normalize( e, ad_reqAttr, vals, op->o_tmpmemctx );
1759                         op->o_tmpfree( vals, op->o_tmpmemctx );
1760                 }
1761                 bv.bv_val = timebuf;
1762                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", rs->sr_nentries );
1763                 if ( bv.bv_len < sizeof( timebuf ) ) {
1764                         attr_merge_one( e, ad_reqEntries, &bv, NULL );
1765                 } /* else? */
1766
1767                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->ors_tlimit );
1768                 if ( bv.bv_len < sizeof( timebuf ) ) {
1769                         attr_merge_one( e, ad_reqTimeLimit, &bv, NULL );
1770                 } /* else? */
1771
1772                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->ors_slimit );
1773                 if ( bv.bv_len < sizeof( timebuf ) ) {
1774                         attr_merge_one( e, ad_reqSizeLimit, &bv, NULL );
1775                 } /* else? */
1776                 break;
1777
1778         case LOG_EN_BIND:
1779                 bv.bv_val = timebuf;
1780                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->o_protocol );
1781                 if ( bv.bv_len < sizeof( timebuf ) ) {
1782                         attr_merge_one( e, ad_reqVersion, &bv, NULL );
1783                 } /* else? */
1784                 if ( op->orb_method == LDAP_AUTH_SIMPLE ) {
1785                         attr_merge_normalize_one( e, ad_reqMethod, &simple, op->o_tmpmemctx );
1786                 } else {
1787                         bv.bv_len = STRLENOF("SASL()") + op->orb_mech.bv_len;
1788                         bv.bv_val = op->o_tmpalloc( bv.bv_len + 1, op->o_tmpmemctx );
1789                         ptr = lutil_strcopy( bv.bv_val, "SASL(" );
1790                         ptr = lutil_strcopy( ptr, op->orb_mech.bv_val );
1791                         *ptr++ = ')';
1792                         *ptr = '\0';
1793                         attr_merge_normalize_one( e, ad_reqMethod, &bv, op->o_tmpmemctx );
1794                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1795                 }
1796
1797                 break;
1798
1799         case LOG_EN_EXTENDED:
1800                 if ( op->ore_reqdata ) {
1801                         attr_merge_one( e, ad_reqData, op->ore_reqdata, NULL );
1802                 }
1803                 break;
1804
1805         case LOG_EN_UNKNOWN:
1806                 /* we don't know its parameters, don't add any */
1807                 break;
1808         }
1809
1810         if ( e_uuid || !BER_BVISNULL( &uuid ) ) {
1811                 struct berval *pbv = NULL;
1812
1813                 if ( !BER_BVISNULL( &uuid ) ) {
1814                         pbv = &uuid;
1815
1816                 } else {
1817                         a = attr_find( e_uuid->e_attrs, slap_schema.si_ad_entryUUID );
1818                         if ( a ) {
1819                                 pbv = &a->a_vals[0];
1820                         }
1821                 } 
1822
1823                 if ( pbv ) {
1824                         attr_merge_normalize_one( e, ad_reqEntryUUID, pbv, op->o_tmpmemctx );
1825                 }
1826
1827                 if ( !BER_BVISNULL( &uuid ) ) {
1828                         ber_memfree( uuid.bv_val );
1829                         BER_BVZERO( &uuid );
1830                 }
1831         }
1832
1833         op2.o_hdr = op->o_hdr;
1834         op2.o_tag = LDAP_REQ_ADD;
1835         op2.o_bd = li->li_db;
1836         op2.o_dn = li->li_db->be_rootdn;
1837         op2.o_ndn = li->li_db->be_rootndn;
1838         op2.o_req_dn = e->e_name;
1839         op2.o_req_ndn = e->e_nname;
1840         op2.ora_e = e;
1841         op2.o_callback = &nullsc;
1842         op2.o_csn = op->o_csn;
1843         /* contextCSN updates may still reach here */
1844         op2.o_dont_replicate = op->o_dont_replicate;
1845
1846         if (( lo->mask & LOG_OP_WRITES ) && !BER_BVISEMPTY( &op->o_csn )) {
1847                 struct berval maxcsn;
1848                 char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
1849                 int foundit;
1850                 cbuf[0] = '\0';
1851                 maxcsn.bv_val = cbuf;
1852                 maxcsn.bv_len = sizeof(cbuf);
1853                 /* If there was a commit CSN on the main DB,
1854                  * we must propagate it to the log DB for its
1855                  * own syncprov. Otherwise, don't generate one.
1856                  */
1857                 slap_get_commit_csn( op, &maxcsn, &foundit );
1858                 if ( !BER_BVISEMPTY( &maxcsn ) ) {
1859                         slap_queue_csn( &op2, &op->o_csn );
1860                         do_graduate = 1;
1861                 } else {
1862                         attr_merge_normalize_one( e, slap_schema.si_ad_entryCSN,
1863                                 &op->o_csn, op->o_tmpmemctx );
1864                 }
1865         }
1866
1867         op2.o_bd->be_add( &op2, &rs2 );
1868         if ( e == op2.ora_e ) entry_free( e );
1869         e = NULL;
1870         if ( do_graduate ) {
1871                 slap_graduate_commit_csn( &op2 );
1872         }
1873
1874 done:
1875         if ( lo->mask & LOG_OP_WRITES )
1876                 ldap_pvt_thread_mutex_unlock( &li->li_log_mutex );
1877         if ( old ) entry_free( old );
1878         return SLAP_CB_CONTINUE;
1879 }
1880
1881 /* Since Bind success is sent by the frontend, it won't normally enter
1882  * the overlay response callback. Add another callback to make sure it
1883  * gets here.
1884  */
1885 static int
1886 accesslog_bind_resp( Operation *op, SlapReply *rs )
1887 {
1888         BackendDB *be, db;
1889         int rc;
1890         slap_callback *sc;
1891
1892         be = op->o_bd;
1893         db = *be;
1894         op->o_bd = &db;
1895         db.bd_info = op->o_callback->sc_private;
1896         rc = accesslog_response( op, rs );
1897         op->o_bd = be;
1898         sc = op->o_callback;
1899         op->o_callback = sc->sc_next;
1900         op->o_tmpfree( sc, op->o_tmpmemctx );
1901         return rc;
1902 }
1903
1904 static int
1905 accesslog_op_bind( Operation *op, SlapReply *rs )
1906 {
1907         slap_callback *sc;
1908
1909         sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1910         sc->sc_response = accesslog_bind_resp;
1911         sc->sc_private = op->o_bd->bd_info;
1912
1913         if ( op->o_callback ) {
1914                 sc->sc_next = op->o_callback->sc_next;
1915                 op->o_callback->sc_next = sc;
1916         } else {
1917                 op->o_callback = sc;
1918         }
1919         return SLAP_CB_CONTINUE;
1920 }
1921
1922 static int
1923 accesslog_mod_cleanup( Operation *op, SlapReply *rs )
1924 {
1925         slap_callback *sc = op->o_callback;
1926         slap_overinst *on = sc->sc_private;
1927         op->o_callback = sc->sc_next;
1928
1929         op->o_tmpfree( sc, op->o_tmpmemctx );
1930
1931         if ( on ) {
1932                 BackendInfo *bi = op->o_bd->bd_info;
1933                 op->o_bd->bd_info = (BackendInfo *)on;
1934                 accesslog_response( op, rs );
1935                 op->o_bd->bd_info = bi;
1936         }
1937         return 0;
1938 }
1939
1940 static int
1941 accesslog_op_mod( Operation *op, SlapReply *rs )
1942 {
1943         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1944         log_info *li = on->on_bi.bi_private;
1945         slap_verbmasks *lo;
1946         int logop;
1947         int doit = 0;
1948
1949         /* These internal ops are not logged */
1950         if ( op->o_dont_replicate ) {
1951                 /* Let contextCSN updates from syncrepl thru; the underlying
1952                  * syncprov needs to see them. Skip others.
1953                  */
1954                 if (( op->o_tag != LDAP_REQ_MODIFY ||
1955                         op->orm_modlist->sml_op != LDAP_MOD_REPLACE ||
1956                         op->orm_modlist->sml_desc != slap_schema.si_ad_contextCSN ) &&
1957                         op->orm_no_opattrs )
1958                 return SLAP_CB_CONTINUE;
1959                 /* give this a unique timestamp */
1960                 op->o_tincr++;
1961         }
1962
1963         logop = accesslog_op2logop( op );
1964         lo = logops+logop+EN_OFFSET;
1965
1966         if ( li->li_ops & lo->mask ) {
1967                 doit = 1;
1968         } else {
1969                 log_base *lb;
1970                 for ( lb = li->li_bases; lb; lb = lb->lb_next )
1971                         if (( lb->lb_ops & lo->mask ) && dnIsSuffix( &op->o_req_ndn, &lb->lb_base )) {
1972                                 doit = 1;
1973                                 break;
1974                         }
1975         }
1976                         
1977         if ( doit ) {
1978                 slap_callback *cb = op->o_tmpalloc( sizeof( slap_callback ), op->o_tmpmemctx ), *cb2;
1979                 cb->sc_cleanup = accesslog_mod_cleanup;
1980                 cb->sc_response = NULL;
1981                 cb->sc_private = on;
1982                 cb->sc_next = NULL;
1983                 for ( cb2 = op->o_callback; cb2->sc_next; cb2 = cb2->sc_next );
1984                 cb2->sc_next = cb;
1985
1986                 ldap_pvt_thread_rmutex_lock( &li->li_op_rmutex, op->o_tid );
1987                 if ( li->li_oldf && ( op->o_tag == LDAP_REQ_DELETE ||
1988                         op->o_tag == LDAP_REQ_MODIFY ||
1989                         ( op->o_tag == LDAP_REQ_MODRDN && li->li_oldattrs )))
1990                 {
1991                         int rc;
1992                         Entry *e;
1993
1994                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1995                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1996                         if ( e ) {
1997                                 if ( test_filter( op, e, li->li_oldf ) == LDAP_COMPARE_TRUE )
1998                                         li->li_old = entry_dup( e );
1999                                 be_entry_release_rw( op, e, 0 );
2000                         }
2001                         op->o_bd->bd_info = (BackendInfo *)on;
2002
2003                 } else {
2004                         int rc;
2005                         Entry *e;
2006
2007                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2008                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
2009                         if ( e ) {
2010                                 Attribute *a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
2011                                 if ( a ) {
2012                                         ber_dupbv( &li->li_uuid, &a->a_vals[0] );
2013                                 }
2014                                 be_entry_release_rw( op, e, 0 );
2015                         }
2016                         op->o_bd->bd_info = (BackendInfo *)on;
2017                 }
2018         }
2019         return SLAP_CB_CONTINUE;
2020 }
2021
2022 /* unbinds are broadcast to all backends; we only log it if this
2023  * backend was used for the original bind.
2024  */
2025 static int
2026 accesslog_unbind( Operation *op, SlapReply *rs )
2027 {
2028         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2029         if ( op->o_conn->c_authz_backend == on->on_info->oi_origdb ) {
2030                 log_info *li = on->on_bi.bi_private;
2031                 Operation op2 = {0};
2032                 void *cids[SLAP_MAX_CIDS];
2033                 SlapReply rs2 = {REP_RESULT};
2034                 Entry *e;
2035
2036                 if ( !( li->li_ops & LOG_OP_UNBIND )) {
2037                         log_base *lb;
2038                         int i = 0;
2039
2040                         for ( lb = li->li_bases; lb; lb=lb->lb_next )
2041                                 if (( lb->lb_ops & LOG_OP_UNBIND ) && dnIsSuffix( &op->o_ndn, &lb->lb_base )) {
2042                                         i = 1;
2043                                         break;
2044                                 }
2045                         if ( !i )
2046                                 return SLAP_CB_CONTINUE;
2047                 }
2048
2049                 e = accesslog_entry( op, rs, LOG_EN_UNBIND, &op2 );
2050                 op2.o_hdr = op->o_hdr;
2051                 op2.o_tag = LDAP_REQ_ADD;
2052                 op2.o_bd = li->li_db;
2053                 op2.o_dn = li->li_db->be_rootdn;
2054                 op2.o_ndn = li->li_db->be_rootndn;
2055                 op2.o_req_dn = e->e_name;
2056                 op2.o_req_ndn = e->e_nname;
2057                 op2.ora_e = e;
2058                 op2.o_callback = &nullsc;
2059                 op2.o_controls = cids;
2060                 memset(cids, 0, sizeof( cids ));
2061
2062                 op2.o_bd->be_add( &op2, &rs2 );
2063                 if ( e == op2.ora_e )
2064                         entry_free( e );
2065         }
2066         return SLAP_CB_CONTINUE;
2067 }
2068
2069 static int
2070 accesslog_abandon( Operation *op, SlapReply *rs )
2071 {
2072         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2073         log_info *li = on->on_bi.bi_private;
2074         Operation op2 = {0};
2075         void *cids[SLAP_MAX_CIDS];
2076         SlapReply rs2 = {REP_RESULT};
2077         Entry *e;
2078         char buf[64];
2079         struct berval bv;
2080
2081         if ( !op->o_time )
2082                 return SLAP_CB_CONTINUE;
2083
2084         if ( !( li->li_ops & LOG_OP_ABANDON )) {
2085                 log_base *lb;
2086                 int i = 0;
2087
2088                 for ( lb = li->li_bases; lb; lb=lb->lb_next )
2089                         if (( lb->lb_ops & LOG_OP_ABANDON ) && dnIsSuffix( &op->o_ndn, &lb->lb_base )) {
2090                                 i = 1;
2091                                 break;
2092                         }
2093                 if ( !i )
2094                         return SLAP_CB_CONTINUE;
2095         }
2096
2097         e = accesslog_entry( op, rs, LOG_EN_ABANDON, &op2 );
2098         bv.bv_val = buf;
2099         bv.bv_len = snprintf( buf, sizeof( buf ), "%d", op->orn_msgid );
2100         if ( bv.bv_len < sizeof( buf ) ) {
2101                 attr_merge_one( e, ad_reqId, &bv, NULL );
2102         } /* else? */
2103
2104         op2.o_hdr = op->o_hdr;
2105         op2.o_tag = LDAP_REQ_ADD;
2106         op2.o_bd = li->li_db;
2107         op2.o_dn = li->li_db->be_rootdn;
2108         op2.o_ndn = li->li_db->be_rootndn;
2109         op2.o_req_dn = e->e_name;
2110         op2.o_req_ndn = e->e_nname;
2111         op2.ora_e = e;
2112         op2.o_callback = &nullsc;
2113         op2.o_controls = cids;
2114         memset(cids, 0, sizeof( cids ));
2115
2116         op2.o_bd->be_add( &op2, &rs2 );
2117         if ( e == op2.ora_e )
2118                 entry_free( e );
2119
2120         return SLAP_CB_CONTINUE;
2121 }
2122
2123 static int
2124 accesslog_operational( Operation *op, SlapReply *rs )
2125 {
2126         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2127         log_info *li = on->on_bi.bi_private;
2128
2129         if ( op->o_sync != SLAP_CONTROL_NONE )
2130                 return SLAP_CB_CONTINUE;
2131
2132         if ( rs->sr_entry != NULL
2133                 && dn_match( &op->o_bd->be_nsuffix[0], &rs->sr_entry->e_nname ) )
2134         {
2135                 Attribute       **ap;
2136
2137                 for ( ap = &rs->sr_operational_attrs; *ap; ap = &(*ap)->a_next )
2138                         /* just count */ ;
2139
2140                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
2141                                 ad_inlist( ad_auditContext, rs->sr_attrs ) )
2142                 {
2143                         *ap = attr_alloc( ad_auditContext );
2144                         attr_valadd( *ap,
2145                                 &li->li_db->be_suffix[0],
2146                                 &li->li_db->be_nsuffix[0], 1 );
2147                 }
2148         }
2149
2150         return SLAP_CB_CONTINUE;
2151 }
2152
2153 static slap_overinst accesslog;
2154
2155 static int
2156 accesslog_db_init(
2157         BackendDB *be,
2158         ConfigReply *cr
2159 )
2160 {
2161         slap_overinst *on = (slap_overinst *)be->bd_info;
2162         log_info *li = ch_calloc(1, sizeof(log_info));
2163
2164         on->on_bi.bi_private = li;
2165         ldap_pvt_thread_rmutex_init( &li->li_op_rmutex );
2166         ldap_pvt_thread_mutex_init( &li->li_log_mutex );
2167         return 0;
2168 }
2169
2170 static int
2171 accesslog_db_destroy(
2172         BackendDB *be,
2173         ConfigReply *cr
2174 )
2175 {
2176         slap_overinst *on = (slap_overinst *)be->bd_info;
2177         log_info *li = on->on_bi.bi_private;
2178         log_attr *la;
2179
2180         if ( li->li_oldf )
2181                 filter_free( li->li_oldf );
2182         for ( la=li->li_oldattrs; la; la=li->li_oldattrs ) {
2183                 li->li_oldattrs = la->next;
2184                 ch_free( la );
2185         }
2186         ldap_pvt_thread_mutex_destroy( &li->li_log_mutex );
2187         ldap_pvt_thread_rmutex_destroy( &li->li_op_rmutex );
2188         free( li );
2189         return LDAP_SUCCESS;
2190 }
2191
2192 /* Create the logdb's root entry if it's missing */
2193 static void *
2194 accesslog_db_root(
2195         void *ctx,
2196         void *arg )
2197 {
2198         struct re_s *rtask = arg;
2199         slap_overinst *on = rtask->arg;
2200         log_info *li = on->on_bi.bi_private;
2201
2202         Connection conn = {0};
2203         OperationBuffer opbuf;
2204         Operation *op;
2205
2206         Entry *e;
2207         int rc;
2208
2209         connection_fake_init( &conn, &opbuf, ctx );
2210         op = &opbuf.ob_op;
2211         op->o_bd = li->li_db;
2212         op->o_dn = li->li_db->be_rootdn;
2213         op->o_ndn = li->li_db->be_rootndn;
2214         rc = be_entry_get_rw( op, li->li_db->be_nsuffix, NULL, NULL, 0, &e );
2215
2216         if ( e ) {
2217                 be_entry_release_rw( op, e, 0 );
2218
2219         } else {
2220                 SlapReply rs = {REP_RESULT};
2221                 struct berval rdn, nrdn, attr;
2222                 char *ptr;
2223                 AttributeDescription *ad = NULL;
2224                 const char *text = NULL;
2225                 Entry *e_ctx;
2226                 BackendDB db;
2227
2228                 e = entry_alloc();
2229                 ber_dupbv( &e->e_name, li->li_db->be_suffix );
2230                 ber_dupbv( &e->e_nname, li->li_db->be_nsuffix );
2231
2232                 attr_merge_one( e, slap_schema.si_ad_objectClass,
2233                         &log_container->soc_cname, NULL );
2234
2235                 dnRdn( &e->e_name, &rdn );
2236                 dnRdn( &e->e_nname, &nrdn );
2237                 ptr = ber_bvchr( &rdn, '=' );
2238
2239                 assert( ptr != NULL );
2240
2241                 attr.bv_val = rdn.bv_val;
2242                 attr.bv_len = ptr - rdn.bv_val;
2243
2244                 slap_bv2ad( &attr, &ad, &text );
2245
2246                 rdn.bv_val = ptr+1;
2247                 rdn.bv_len -= attr.bv_len + 1;
2248                 ptr = ber_bvchr( &nrdn, '=' );
2249                 nrdn.bv_len -= ptr - nrdn.bv_val + 1;
2250                 nrdn.bv_val = ptr+1;
2251                 attr_merge_one( e, ad, &rdn, &nrdn );
2252
2253                 /* Get contextCSN from main DB */
2254                 op->o_bd = on->on_info->oi_origdb;
2255                 rc = be_entry_get_rw( op, op->o_bd->be_nsuffix, NULL,
2256                         slap_schema.si_ad_contextCSN, 0, &e_ctx );
2257
2258                 if ( e_ctx ) {
2259                         Attribute *a;
2260
2261                         a = attr_find( e_ctx->e_attrs, slap_schema.si_ad_contextCSN );
2262                         if ( a ) {
2263                                 /* FIXME: contextCSN could have multiple values!
2264                                  * should select the one with the server's SID */
2265                                 attr_merge_one( e, slap_schema.si_ad_entryCSN,
2266                                         &a->a_vals[0], &a->a_nvals[0] );
2267                                 attr_merge( e, a->a_desc, a->a_vals, a->a_nvals );
2268                         }
2269                         be_entry_release_rw( op, e_ctx, 0 );
2270                 }
2271                 db = *li->li_db;
2272                 op->o_bd = &db;
2273
2274                 op->ora_e = e;
2275                 op->o_req_dn = e->e_name;
2276                 op->o_req_ndn = e->e_nname;
2277                 op->o_callback = &nullsc;
2278                 SLAP_DBFLAGS( op->o_bd ) |= SLAP_DBFLAG_NOLASTMOD;
2279                 rc = op->o_bd->be_add( op, &rs );
2280                 if ( e == op->ora_e )
2281                         entry_free( e );
2282         }
2283         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2284         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2285         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
2286         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2287
2288         return NULL;
2289 }
2290
2291 static int
2292 accesslog_db_open(
2293         BackendDB *be,
2294         ConfigReply *cr
2295 )
2296 {
2297         slap_overinst *on = (slap_overinst *)be->bd_info;
2298         log_info *li = on->on_bi.bi_private;
2299
2300
2301         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
2302                 li->li_db = select_backend( &li->li_db_suffix, 0 );
2303                 ch_free( li->li_db_suffix.bv_val );
2304                 BER_BVZERO( &li->li_db_suffix );
2305         }
2306         if ( li->li_db == NULL ) {
2307                 Debug( LDAP_DEBUG_ANY,
2308                         "accesslog: \"logdb <suffix>\" missing or invalid.\n",
2309                         0, 0, 0 );
2310                 return 1;
2311         }
2312
2313         if ( slapMode & SLAP_TOOL_MODE )
2314                 return 0;
2315
2316         if ( BER_BVISEMPTY( &li->li_db->be_rootndn )) {
2317                 ber_dupbv( &li->li_db->be_rootdn, li->li_db->be_suffix );
2318                 ber_dupbv( &li->li_db->be_rootndn, li->li_db->be_nsuffix );
2319         }
2320
2321         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2322         ldap_pvt_runqueue_insert( &slapd_rq, 3600, accesslog_db_root, on,
2323                 "accesslog_db_root", li->li_db->be_suffix[0].bv_val );
2324         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2325
2326         return 0;
2327 }
2328
2329 int accesslog_initialize()
2330 {
2331         int i, rc;
2332
2333         accesslog.on_bi.bi_type = "accesslog";
2334         accesslog.on_bi.bi_db_init = accesslog_db_init;
2335         accesslog.on_bi.bi_db_destroy = accesslog_db_destroy;
2336         accesslog.on_bi.bi_db_open = accesslog_db_open;
2337
2338         accesslog.on_bi.bi_op_add = accesslog_op_mod;
2339         accesslog.on_bi.bi_op_bind = accesslog_op_bind;
2340         accesslog.on_bi.bi_op_delete = accesslog_op_mod;
2341         accesslog.on_bi.bi_op_modify = accesslog_op_mod;
2342         accesslog.on_bi.bi_op_modrdn = accesslog_op_mod;
2343         accesslog.on_bi.bi_op_unbind = accesslog_unbind;
2344         accesslog.on_bi.bi_op_abandon = accesslog_abandon;
2345         accesslog.on_bi.bi_operational = accesslog_operational;
2346         accesslog.on_response = accesslog_response;
2347
2348         accesslog.on_bi.bi_cf_ocs = log_cfocs;
2349
2350         nullsc.sc_response = slap_null_cb;
2351
2352         rc = config_register_schema( log_cfats, log_cfocs );
2353         if ( rc ) return rc;
2354
2355         /* log schema integration */
2356         for ( i=0; lsyntaxes[i].oid; i++ ) {
2357                 int code;
2358
2359                 code = register_syntax( &lsyntaxes[ i ].syn );
2360                 if ( code != 0 ) {
2361                         Debug( LDAP_DEBUG_ANY,
2362                                 "accesslog_init: register_syntax failed\n",
2363                                 0, 0, 0 );
2364                         return code;
2365                 }
2366
2367                 if ( lsyntaxes[i].mrs != NULL ) {
2368                         code = mr_make_syntax_compat_with_mrs(
2369                                 lsyntaxes[i].oid, lsyntaxes[i].mrs );
2370                         if ( code < 0 ) {
2371                                 Debug( LDAP_DEBUG_ANY,
2372                                         "accesslog_init: "
2373                                         "mr_make_syntax_compat_with_mrs "
2374                                         "failed\n",
2375                                         0, 0, 0 );
2376                                 return code;
2377                         }
2378                 }
2379         }
2380
2381         for ( i=0; lattrs[i].at; i++ ) {
2382                 int code;
2383
2384                 code = register_at( lattrs[i].at, lattrs[i].ad, 0 );
2385                 if ( code ) {
2386                         Debug( LDAP_DEBUG_ANY,
2387                                 "accesslog_init: register_at failed\n",
2388                                 0, 0, 0 );
2389                         return -1;
2390                 }
2391 #ifndef LDAP_DEVEL
2392                 (*lattrs[i].ad)->ad_type->sat_flags |= SLAP_AT_HIDE;
2393 #endif
2394         }
2395
2396         for ( i=0; locs[i].ot; i++ ) {
2397                 int code;
2398
2399                 code = register_oc( locs[i].ot, locs[i].oc, 0 );
2400                 if ( code ) {
2401                         Debug( LDAP_DEBUG_ANY,
2402                                 "accesslog_init: register_oc failed\n",
2403                                 0, 0, 0 );
2404                         return -1;
2405                 }
2406 #ifndef LDAP_DEVEL
2407                 (*locs[i].oc)->soc_flags |= SLAP_OC_HIDE;
2408 #endif
2409         }
2410
2411         return overlay_register(&accesslog);
2412 }
2413
2414 #if SLAPD_OVER_ACCESSLOG == SLAPD_MOD_DYNAMIC
2415 int
2416 init_module( int argc, char *argv[] )
2417 {
2418         return accesslog_initialize();
2419 }
2420 #endif
2421
2422 #endif /* SLAPD_OVER_ACCESSLOG */