]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/accesslog.c
More for a_numvals
[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                         i += a->a_numvals;
1369                 }
1370                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1371                 i = 0;
1372                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1373                         if ( a->a_vals ) {
1374                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1375                                         accesslog_val2val( a->a_desc, b, c_op, &vals[i] );
1376                                 }
1377                         }
1378                 }
1379                 vals[i].bv_val = NULL;
1380                 vals[i].bv_len = 0;
1381                 a = attr_alloc( logop == LOG_EN_ADD ? ad_reqMod : ad_reqOld );
1382                 a->a_numvals = i;
1383                 a->a_vals = vals;
1384                 a->a_nvals = vals;
1385                 last_attr->a_next = a;
1386                 break;
1387         }
1388
1389         case LOG_EN_MODRDN:
1390         case LOG_EN_MODIFY:
1391                 /* count all the mods */
1392                 i = 0;
1393                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1394                         if ( m->sml_values ) {
1395                                 i += m->sml_numvals;
1396                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1397                                 m->sml_op == LDAP_MOD_REPLACE )
1398                         {
1399                                 i++;
1400                         }
1401                 }
1402                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1403                 i = 0;
1404
1405                 /* init flags on old entry */
1406                 if ( old ) {
1407                         for ( a = old->e_attrs; a; a = a->a_next ) {
1408                                 log_attr *la;
1409                                 a->a_flags = 0;
1410
1411                                 /* look for attrs that are always logged */
1412                                 for ( la = li->li_oldattrs; la; la = la->next ) {
1413                                         if ( a->a_desc == la->attr ) {
1414                                                 a->a_flags = 1;
1415                                         }
1416                                 }
1417                         }
1418                 }
1419
1420                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1421                         /* Mark this attribute as modified */
1422                         if ( old ) {
1423                                 a = attr_find( old->e_attrs, m->sml_desc );
1424                                 if ( a ) {
1425                                         a->a_flags = 1;
1426                                 }
1427                         }
1428
1429                         /* don't log the RDN mods; they're explicitly logged later */
1430                         if ( logop == LOG_EN_MODRDN &&
1431                                 ( m->sml_op == SLAP_MOD_SOFTADD ||
1432                                   m->sml_op == LDAP_MOD_DELETE ) )
1433                         {
1434                                 continue;
1435                         }
1436
1437                         if ( m->sml_values ) {
1438                                 for ( b = m->sml_values; !BER_BVISNULL( b ); b++, i++ ) {
1439                                         char c_op;
1440
1441                                         switch ( m->sml_op ) {
1442                                         case LDAP_MOD_ADD: c_op = '+'; break;
1443                                         case LDAP_MOD_DELETE:   c_op = '-'; break;
1444                                         case LDAP_MOD_REPLACE:  c_op = '='; break;
1445                                         case LDAP_MOD_INCREMENT:        c_op = '#'; break;
1446
1447                                         /* unknown op. there shouldn't be any of these. we
1448                                          * don't know what to do with it, but we shouldn't just
1449                                          * ignore it.
1450                                          */
1451                                         default: c_op = '?'; break;
1452                                         }
1453                                         accesslog_val2val( m->sml_desc, b, c_op, &vals[i] );
1454                                 }
1455                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1456                                 m->sml_op == LDAP_MOD_REPLACE )
1457                         {
1458                                 vals[i].bv_len = m->sml_desc->ad_cname.bv_len + 2;
1459                                 vals[i].bv_val = ch_malloc( vals[i].bv_len + 1 );
1460                                 ptr = lutil_strcopy( vals[i].bv_val,
1461                                         m->sml_desc->ad_cname.bv_val );
1462                                 *ptr++ = ':';
1463                                 if ( m->sml_op == LDAP_MOD_DELETE ) {
1464                                         *ptr++ = '-';
1465                                 } else {
1466                                         *ptr++ = '=';
1467                                 }
1468                                 *ptr = '\0';
1469                                 i++;
1470                         }
1471                 }
1472
1473                 if ( i > 0 ) {
1474                         BER_BVZERO( &vals[i] );
1475                         a = attr_alloc( ad_reqMod );
1476                         a->a_numvals = i;
1477                         a->a_vals = vals;
1478                         a->a_nvals = vals;
1479                         last_attr->a_next = a;
1480                         last_attr = a;
1481
1482                 } else {
1483                         ch_free( vals );
1484                 }
1485
1486                 if ( old ) {
1487                         /* count all the vals */
1488                         i = 0;
1489                         for ( a = old->e_attrs; a != NULL; a = a->a_next ) {
1490                                 if ( a->a_vals && a->a_flags ) {
1491                                         i += a->a_numvals;
1492                                 }
1493                         }
1494                         vals = ch_malloc( (i + 1) * sizeof( struct berval ) );
1495                         i = 0;
1496                         for ( a=old->e_attrs; a; a=a->a_next ) {
1497                                 if ( a->a_vals && a->a_flags ) {
1498                                         for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1499                                                 accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1500                                         }
1501                                 }
1502                         }
1503                         vals[i].bv_val = NULL;
1504                         vals[i].bv_len = 0;
1505                         a = attr_alloc( ad_reqOld );
1506                         a->a_numvals = i;
1507                         a->a_vals = vals;
1508                         a->a_nvals = vals;
1509                         last_attr->a_next = a;
1510                 }
1511                 if ( logop == LOG_EN_MODIFY ) {
1512                         break;
1513                 }
1514
1515                 /* Now log the actual modRDN info */
1516                 attr_merge_one( e, ad_reqNewRDN, &op->orr_newrdn, &op->orr_nnewrdn );
1517                 attr_merge_one( e, ad_reqDeleteOldRDN, op->orr_deleteoldrdn ?
1518                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1519                         NULL );
1520                 if ( op->orr_newSup ) {
1521                         attr_merge_one( e, ad_reqNewSuperior, op->orr_newSup, op->orr_nnewSup );
1522                 }
1523                 break;
1524
1525         case LOG_EN_COMPARE:
1526                 bv.bv_len = op->orc_ava->aa_desc->ad_cname.bv_len + 1 +
1527                         op->orc_ava->aa_value.bv_len;
1528                 bv.bv_val = op->o_tmpalloc( bv.bv_len+1, op->o_tmpmemctx );
1529                 ptr = lutil_strcopy( bv.bv_val, op->orc_ava->aa_desc->ad_cname.bv_val );
1530                 *ptr++ = '=';
1531                 AC_MEMCPY( ptr, op->orc_ava->aa_value.bv_val, op->orc_ava->aa_value.bv_len );
1532                 bv.bv_val[bv.bv_len] = '\0';
1533                 attr_merge_one( e, ad_reqAssertion, &bv, NULL );
1534                 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1535                 break;
1536
1537         case LOG_EN_SEARCH:
1538                 attr_merge_one( e, ad_reqScope, &scopes[op->ors_scope], NULL );
1539                 attr_merge_one( e, ad_reqDerefAliases, &derefs[op->ors_deref], NULL );
1540                 attr_merge_one( e, ad_reqAttrsOnly, op->ors_attrsonly ?
1541                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1542                         NULL );
1543                 if ( !BER_BVISEMPTY( &op->ors_filterstr ))
1544                         attr_merge_one( e, ad_reqFilter, &op->ors_filterstr, NULL );
1545                 if ( op->ors_attrs ) {
1546                         /* count them */
1547                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1548                                 ;
1549                         vals = op->o_tmpalloc( (i+1) * sizeof(struct berval),
1550                                 op->o_tmpmemctx );
1551                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1552                                 vals[i] = op->ors_attrs[i].an_name;
1553                         vals[i].bv_val = NULL;
1554                         vals[i].bv_len = 0;
1555                         attr_merge( e, ad_reqAttr, vals, NULL );
1556                         op->o_tmpfree( vals, op->o_tmpmemctx );
1557                 }
1558                 bv.bv_val = timebuf;
1559                 bv.bv_len = sprintf( bv.bv_val, "%d", rs->sr_nentries );
1560                 attr_merge_one( e, ad_reqEntries, &bv, NULL );
1561
1562                 bv.bv_len = sprintf( bv.bv_val, "%d", op->ors_tlimit );
1563                 attr_merge_one( e, ad_reqTimeLimit, &bv, NULL );
1564
1565                 bv.bv_len = sprintf( bv.bv_val, "%d", op->ors_slimit );
1566                 attr_merge_one( e, ad_reqSizeLimit, &bv, NULL );
1567                 break;
1568
1569         case LOG_EN_BIND:
1570                 bv.bv_val = timebuf;
1571                 bv.bv_len = sprintf( bv.bv_val, "%d", op->o_protocol );
1572                 attr_merge_one( e, ad_reqVersion, &bv, NULL );
1573                 if ( op->orb_method == LDAP_AUTH_SIMPLE ) {
1574                         attr_merge_one( e, ad_reqMethod, &simple, NULL );
1575                 } else {
1576                         bv.bv_len = STRLENOF("SASL()") + op->orb_mech.bv_len;
1577                         bv.bv_val = op->o_tmpalloc( bv.bv_len + 1, op->o_tmpmemctx );
1578                         ptr = lutil_strcopy( bv.bv_val, "SASL(" );
1579                         ptr = lutil_strcopy( ptr, op->orb_mech.bv_val );
1580                         *ptr++ = ')';
1581                         *ptr = '\0';
1582                         attr_merge_one( e, ad_reqMethod, &bv, NULL );
1583                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1584                 }
1585
1586                 break;
1587
1588         case LOG_EN_EXTENDED:
1589                 if ( op->ore_reqdata ) {
1590                         attr_merge_one( e, ad_reqData, op->ore_reqdata, NULL );
1591                 }
1592                 break;
1593
1594         case LOG_EN_UNKNOWN:
1595                 /* we don't know its parameters, don't add any */
1596                 break;
1597         }
1598
1599         op2.o_hdr = op->o_hdr;
1600         op2.o_tag = LDAP_REQ_ADD;
1601         op2.o_bd = li->li_db;
1602         op2.o_dn = li->li_db->be_rootdn;
1603         op2.o_ndn = li->li_db->be_rootndn;
1604         op2.o_req_dn = e->e_name;
1605         op2.o_req_ndn = e->e_nname;
1606         op2.ora_e = e;
1607         op2.o_callback = &nullsc;
1608
1609         if (( lo->mask & LOG_OP_WRITES ) && !BER_BVISEMPTY( &op->o_csn )) {
1610                 slap_queue_csn( &op2, &op->o_csn );
1611         }
1612
1613         op2.o_bd->be_add( &op2, &rs2 );
1614         if ( e == op2.ora_e ) entry_free( e );
1615         e = NULL;
1616
1617 done:
1618         if ( lo->mask & LOG_OP_WRITES )
1619                 ldap_pvt_thread_mutex_unlock( &li->li_log_mutex );
1620         if ( old ) entry_free( old );
1621         return SLAP_CB_CONTINUE;
1622 }
1623
1624 /* Since Bind success is sent by the frontend, it won't normally enter
1625  * the overlay response callback. Add another callback to make sure it
1626  * gets here.
1627  */
1628 static int
1629 accesslog_bind_resp( Operation *op, SlapReply *rs )
1630 {
1631         BackendDB *be, db;
1632         int rc;
1633         slap_callback *sc;
1634
1635         be = op->o_bd;
1636         db = *be;
1637         op->o_bd = &db;
1638         db.bd_info = op->o_callback->sc_private;
1639         rc = accesslog_response( op, rs );
1640         op->o_bd = be;
1641         sc = op->o_callback;
1642         op->o_callback = sc->sc_next;
1643         op->o_tmpfree( sc, op->o_tmpmemctx );
1644         return rc;
1645 }
1646
1647 static int
1648 accesslog_op_bind( Operation *op, SlapReply *rs )
1649 {
1650         slap_callback *sc;
1651
1652         sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1653         sc->sc_response = accesslog_bind_resp;
1654         sc->sc_private = op->o_bd->bd_info;
1655
1656         if ( op->o_callback ) {
1657                 sc->sc_next = op->o_callback->sc_next;
1658                 op->o_callback->sc_next = sc;
1659         } else {
1660                 op->o_callback = sc;
1661         }
1662         return SLAP_CB_CONTINUE;
1663 }
1664
1665 static int
1666 accesslog_op_mod( Operation *op, SlapReply *rs )
1667 {
1668         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1669         log_info *li = on->on_bi.bi_private;
1670
1671         if ( li->li_ops & LOG_OP_WRITES ) {
1672                 ldap_pvt_thread_rmutex_lock( &li->li_op_rmutex, op->o_tid );
1673                 if ( li->li_oldf && ( op->o_tag == LDAP_REQ_DELETE ||
1674                         op->o_tag == LDAP_REQ_MODIFY ||
1675                         ( op->o_tag == LDAP_REQ_MODRDN && li->li_oldattrs ))) {
1676                         int rc;
1677                         Entry *e;
1678
1679                         op->o_bd->bd_info = on->on_info->oi_orig;
1680                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1681                         if ( e ) {
1682                                 if ( test_filter( op, e, li->li_oldf ) == LDAP_COMPARE_TRUE )
1683                                         li->li_old = entry_dup( e );
1684                                 be_entry_release_rw( op, e, 0 );
1685                         }
1686                         op->o_bd->bd_info = (BackendInfo *)on;
1687                 }
1688         }
1689         return SLAP_CB_CONTINUE;
1690 }
1691
1692 /* unbinds are broadcast to all backends; we only log it if this
1693  * backend was used for the original bind.
1694  */
1695 static int
1696 accesslog_unbind( Operation *op, SlapReply *rs )
1697 {
1698         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1699         if ( op->o_conn->c_authz_backend == on->on_info->oi_origdb ) {
1700                 log_info *li = on->on_bi.bi_private;
1701                 Operation op2 = {0};
1702                 void *cids[SLAP_MAX_CIDS];
1703                 SlapReply rs2 = {REP_RESULT};
1704                 Entry *e;
1705
1706                 if ( !( li->li_ops & LOG_OP_UNBIND ))
1707                         return SLAP_CB_CONTINUE;
1708
1709                 e = accesslog_entry( op, rs, LOG_EN_UNBIND, &op2 );
1710                 op2.o_hdr = op->o_hdr;
1711                 op2.o_tag = LDAP_REQ_ADD;
1712                 op2.o_bd = li->li_db;
1713                 op2.o_dn = li->li_db->be_rootdn;
1714                 op2.o_ndn = li->li_db->be_rootndn;
1715                 op2.o_req_dn = e->e_name;
1716                 op2.o_req_ndn = e->e_nname;
1717                 op2.ora_e = e;
1718                 op2.o_callback = &nullsc;
1719                 op2.o_controls = cids;
1720                 memset(cids, 0, sizeof( cids ));
1721
1722                 op2.o_bd->be_add( &op2, &rs2 );
1723                 if ( e == op2.ora_e )
1724                         entry_free( e );
1725         }
1726         return SLAP_CB_CONTINUE;
1727 }
1728
1729 static int
1730 accesslog_abandon( Operation *op, SlapReply *rs )
1731 {
1732         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1733         log_info *li = on->on_bi.bi_private;
1734         Operation op2 = {0};
1735         void *cids[SLAP_MAX_CIDS];
1736         SlapReply rs2 = {REP_RESULT};
1737         Entry *e;
1738         char buf[64];
1739         struct berval bv;
1740
1741         if ( !op->o_time || !( li->li_ops & LOG_OP_ABANDON ))
1742                 return SLAP_CB_CONTINUE;
1743
1744         e = accesslog_entry( op, rs, LOG_EN_ABANDON, &op2 );
1745         bv.bv_val = buf;
1746         bv.bv_len = sprintf( buf, "%d", op->orn_msgid );
1747         attr_merge_one( e, ad_reqId, &bv, NULL );
1748
1749         op2.o_hdr = op->o_hdr;
1750         op2.o_tag = LDAP_REQ_ADD;
1751         op2.o_bd = li->li_db;
1752         op2.o_dn = li->li_db->be_rootdn;
1753         op2.o_ndn = li->li_db->be_rootndn;
1754         op2.o_req_dn = e->e_name;
1755         op2.o_req_ndn = e->e_nname;
1756         op2.ora_e = e;
1757         op2.o_callback = &nullsc;
1758         op2.o_controls = cids;
1759         memset(cids, 0, sizeof( cids ));
1760
1761         op2.o_bd->be_add( &op2, &rs2 );
1762         if ( e == op2.ora_e )
1763                 entry_free( e );
1764
1765         return SLAP_CB_CONTINUE;
1766 }
1767
1768 static int
1769 accesslog_operational( Operation *op, SlapReply *rs )
1770 {
1771         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1772         log_info *li = on->on_bi.bi_private;
1773
1774         if ( rs->sr_entry != NULL
1775                 && dn_match( &op->o_bd->be_nsuffix[0], &rs->sr_entry->e_nname ) )
1776         {
1777                 Attribute       **ap;
1778
1779                 for ( ap = &rs->sr_operational_attrs; *ap; ap = &(*ap)->a_next )
1780                         /* just count */ ;
1781
1782                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
1783                                 ad_inlist( ad_auditContext, rs->sr_attrs ) )
1784                 {
1785                         *ap = attr_alloc( ad_auditContext );
1786                         attr_valadd( *ap,
1787                                 &li->li_db->be_suffix[0],
1788                                 &li->li_db->be_nsuffix[0], 1 );
1789                 }
1790         }
1791
1792         return SLAP_CB_CONTINUE;
1793 }
1794
1795 static slap_overinst accesslog;
1796
1797 static int
1798 accesslog_db_init(
1799         BackendDB *be,
1800         ConfigReply *cr
1801 )
1802 {
1803         slap_overinst *on = (slap_overinst *)be->bd_info;
1804         log_info *li = ch_calloc(1, sizeof(log_info));
1805
1806         on->on_bi.bi_private = li;
1807         ldap_pvt_thread_rmutex_init( &li->li_op_rmutex );
1808         ldap_pvt_thread_mutex_init( &li->li_log_mutex );
1809         return 0;
1810 }
1811
1812 static int
1813 accesslog_db_destroy(
1814         BackendDB *be,
1815         ConfigReply *cr
1816 )
1817 {
1818         slap_overinst *on = (slap_overinst *)be->bd_info;
1819         log_info *li = on->on_bi.bi_private;
1820         log_attr *la;
1821
1822         if ( li->li_oldf )
1823                 filter_free( li->li_oldf );
1824         for ( la=li->li_oldattrs; la; la=li->li_oldattrs ) {
1825                 li->li_oldattrs = la->next;
1826                 ch_free( la );
1827         }
1828         ldap_pvt_thread_mutex_destroy( &li->li_log_mutex );
1829         ldap_pvt_thread_rmutex_destroy( &li->li_op_rmutex );
1830         free( li );
1831         return LDAP_SUCCESS;
1832 }
1833
1834 /* Create the logdb's root entry if it's missing */
1835 static void *
1836 accesslog_db_root(
1837         void *ctx,
1838         void *arg )
1839 {
1840         struct re_s *rtask = arg;
1841         slap_overinst *on = rtask->arg;
1842         log_info *li = on->on_bi.bi_private;
1843
1844         Connection conn = {0};
1845         OperationBuffer opbuf;
1846         Operation *op;
1847
1848         Entry *e;
1849         int rc;
1850
1851         connection_fake_init( &conn, &opbuf, ctx );
1852         op = &opbuf.ob_op;
1853         op->o_bd = li->li_db;
1854         op->o_dn = li->li_db->be_rootdn;
1855         op->o_ndn = li->li_db->be_rootndn;
1856         rc = be_entry_get_rw( op, li->li_db->be_nsuffix, NULL, NULL, 0, &e );
1857
1858         if ( e ) {
1859                 be_entry_release_rw( op, e, 0 );
1860
1861         } else {
1862                 SlapReply rs = {REP_RESULT};
1863                 struct berval rdn, nrdn, attr;
1864                 char *ptr;
1865                 AttributeDescription *ad = NULL;
1866                 const char *text = NULL;
1867                 Entry *e_ctx;
1868
1869                 e = entry_alloc();
1870                 ber_dupbv( &e->e_name, li->li_db->be_suffix );
1871                 ber_dupbv( &e->e_nname, li->li_db->be_nsuffix );
1872
1873                 attr_merge_one( e, slap_schema.si_ad_objectClass,
1874                         &log_container->soc_cname, NULL );
1875
1876                 dnRdn( &e->e_name, &rdn );
1877                 dnRdn( &e->e_nname, &nrdn );
1878                 ptr = ber_bvchr( &rdn, '=' );
1879
1880                 assert( ptr != NULL );
1881
1882                 attr.bv_val = rdn.bv_val;
1883                 attr.bv_len = ptr - rdn.bv_val;
1884
1885                 slap_bv2ad( &attr, &ad, &text );
1886
1887                 rdn.bv_val = ptr+1;
1888                 rdn.bv_len -= attr.bv_len + 1;
1889                 ptr = ber_bvchr( &nrdn, '=' );
1890                 nrdn.bv_len -= ptr - nrdn.bv_val + 1;
1891                 nrdn.bv_val = ptr+1;
1892                 attr_merge_one( e, ad, &rdn, &nrdn );
1893
1894                 /* Get contextCSN from main DB */
1895                 op->o_bd = on->on_info->oi_origdb;
1896                 rc = be_entry_get_rw( op, op->o_bd->be_nsuffix, NULL,
1897                         slap_schema.si_ad_contextCSN, 0, &e_ctx );
1898
1899                 if ( e_ctx ) {
1900                         Attribute *a;
1901
1902                         a = attr_find( e_ctx->e_attrs, slap_schema.si_ad_contextCSN );
1903                         if ( a ) {
1904                                 /* FIXME: contextCSN could have multiple values!
1905                                  * should select the one with the server's SID */
1906                                 attr_merge_one( e, slap_schema.si_ad_entryCSN,
1907                                         &a->a_vals[0], &a->a_nvals[0] );
1908                                 attr_merge( e, a->a_desc, a->a_vals, a->a_nvals );
1909                         }
1910                         be_entry_release_rw( op, e_ctx, 0 );
1911                 }
1912                 op->o_bd = li->li_db;
1913
1914                 op->ora_e = e;
1915                 op->o_req_dn = e->e_name;
1916                 op->o_req_ndn = e->e_nname;
1917                 op->o_callback = &nullsc;
1918                 SLAP_DBFLAGS( op->o_bd ) |= SLAP_DBFLAG_NOLASTMOD;
1919                 rc = op->o_bd->be_add( op, &rs );
1920                 SLAP_DBFLAGS( op->o_bd ) ^= SLAP_DBFLAG_NOLASTMOD;
1921                 if ( e == op->ora_e )
1922                         entry_free( e );
1923         }
1924         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1925         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1926         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1927         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1928
1929         return NULL;
1930 }
1931
1932 static int
1933 accesslog_db_open(
1934         BackendDB *be,
1935         ConfigReply *cr
1936 )
1937 {
1938         slap_overinst *on = (slap_overinst *)be->bd_info;
1939         log_info *li = on->on_bi.bi_private;
1940
1941
1942         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
1943                 li->li_db = select_backend( &li->li_db_suffix, 0 );
1944                 ch_free( li->li_db_suffix.bv_val );
1945                 BER_BVZERO( &li->li_db_suffix );
1946         }
1947         if ( li->li_db == NULL ) {
1948                 Debug( LDAP_DEBUG_ANY,
1949                         "accesslog: \"logdb <suffix>\" missing or invalid.\n",
1950                         0, 0, 0 );
1951                 return 1;
1952         }
1953
1954         if ( slapMode & SLAP_TOOL_MODE )
1955                 return 0;
1956
1957         if ( BER_BVISEMPTY( &li->li_db->be_rootndn )) {
1958                 ber_dupbv( &li->li_db->be_rootdn, li->li_db->be_suffix );
1959                 ber_dupbv( &li->li_db->be_rootndn, li->li_db->be_nsuffix );
1960         }
1961
1962         ldap_pvt_runqueue_insert( &slapd_rq, 3600, accesslog_db_root, on,
1963                 "accesslog_db_root", li->li_db->be_suffix[0].bv_val );
1964
1965         return 0;
1966 }
1967
1968 int accesslog_initialize()
1969 {
1970         int i, rc;
1971
1972         accesslog.on_bi.bi_type = "accesslog";
1973         accesslog.on_bi.bi_db_init = accesslog_db_init;
1974         accesslog.on_bi.bi_db_destroy = accesslog_db_destroy;
1975         accesslog.on_bi.bi_db_open = accesslog_db_open;
1976
1977         accesslog.on_bi.bi_op_add = accesslog_op_mod;
1978         accesslog.on_bi.bi_op_bind = accesslog_op_bind;
1979         accesslog.on_bi.bi_op_delete = accesslog_op_mod;
1980         accesslog.on_bi.bi_op_modify = accesslog_op_mod;
1981         accesslog.on_bi.bi_op_modrdn = accesslog_op_mod;
1982         accesslog.on_bi.bi_op_unbind = accesslog_unbind;
1983         accesslog.on_bi.bi_op_abandon = accesslog_abandon;
1984         accesslog.on_bi.bi_operational = accesslog_operational;
1985         accesslog.on_response = accesslog_response;
1986
1987         accesslog.on_bi.bi_cf_ocs = log_cfocs;
1988
1989         nullsc.sc_response = slap_null_cb;
1990
1991         rc = config_register_schema( log_cfats, log_cfocs );
1992         if ( rc ) return rc;
1993
1994         /* log schema integration */
1995         for ( i=0; lsyntaxes[i].oid; i++ ) {
1996                 int code;
1997
1998                 code = register_syntax( &lsyntaxes[ i ].syn );
1999                 if ( code != 0 ) {
2000                         Debug( LDAP_DEBUG_ANY,
2001                                 "accesslog_init: register_syntax failed\n",
2002                                 0, 0, 0 );
2003                         return code;
2004                 }
2005
2006                 if ( lsyntaxes[i].mrs != NULL ) {
2007                         code = mr_make_syntax_compat_with_mrs(
2008                                 lsyntaxes[i].oid, lsyntaxes[i].mrs );
2009                         if ( code < 0 ) {
2010                                 Debug( LDAP_DEBUG_ANY,
2011                                         "accesslog_init: "
2012                                         "mr_make_syntax_compat_with_mrs "
2013                                         "failed\n",
2014                                         0, 0, 0 );
2015                                 return code;
2016                         }
2017                 }
2018         }
2019
2020         for ( i=0; lattrs[i].at; i++ ) {
2021                 int code;
2022
2023                 code = register_at( lattrs[i].at, lattrs[i].ad, 0 );
2024                 if ( code ) {
2025                         Debug( LDAP_DEBUG_ANY,
2026                                 "accesslog_init: register_at failed\n",
2027                                 0, 0, 0 );
2028                         return -1;
2029                 }
2030 #ifndef LDAP_DEVEL
2031                 (*lattrs[i].ad)->ad_type->sat_flags |= SLAP_AT_HIDE;
2032 #endif
2033         }
2034
2035         for ( i=0; locs[i].ot; i++ ) {
2036                 int code;
2037
2038                 code = register_oc( locs[i].ot, locs[i].oc, 0 );
2039                 if ( code ) {
2040                         Debug( LDAP_DEBUG_ANY,
2041                                 "accesslog_init: register_oc failed\n",
2042                                 0, 0, 0 );
2043                         return -1;
2044                 }
2045 #ifndef LDAP_DEVEL
2046                 (*locs[i].oc)->soc_flags |= SLAP_OC_HIDE;
2047 #endif
2048         }
2049
2050         return overlay_register(&accesslog);
2051 }
2052
2053 #if SLAPD_OVER_ACCESSLOG == SLAPD_MOD_DYNAMIC
2054 int
2055 init_module( int argc, char *argv[] )
2056 {
2057         return accesslog_initialize();
2058 }
2059 #endif
2060
2061 #endif /* SLAPD_OVER_ACCESSLOG */