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