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