]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/accesslog.c
b57c197cf7e26cd2b0f70a4dc774744078f761ea
[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-2006 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         slap_mask_t li_ops;
62         int li_age;
63         int li_cycle;
64         struct re_s *li_task;
65         Filter *li_oldf;
66         Entry *li_old;
67         log_attr *li_oldattrs;
68         int li_success;
69         ldap_pvt_thread_rmutex_t li_op_rmutex;
70         ldap_pvt_thread_mutex_t li_log_mutex;
71 } log_info;
72
73 static ConfigDriver log_cf_gen;
74
75 enum {
76         LOG_DB = 1,
77         LOG_OPS,
78         LOG_PURGE,
79         LOG_SUCCESS,
80         LOG_OLD,
81         LOG_OLDATTR
82 };
83
84 static ConfigTable log_cfats[] = {
85         { "logdb", "suffix", 2, 2, 0, ARG_DN|ARG_MAGIC|LOG_DB,
86                 log_cf_gen, "( OLcfgOvAt:4.1 NAME 'olcAccessLogDB' "
87                         "DESC 'Suffix of database for log content' "
88                         "SUP distinguishedName SINGLE-VALUE )", NULL, NULL },
89         { "logops", "op|writes|reads|session|all", 2, 0, 0,
90                 ARG_MAGIC|LOG_OPS,
91                 log_cf_gen, "( OLcfgOvAt:4.2 NAME 'olcAccessLogOps' "
92                         "DESC 'Operation types to log' "
93                         "EQUALITY caseIgnoreMatch "
94                         "SYNTAX OMsDirectoryString )", NULL, NULL },
95         { "logpurge", "age> <interval", 3, 3, 0, ARG_MAGIC|LOG_PURGE,
96                 log_cf_gen, "( OLcfgOvAt:4.3 NAME 'olcAccessLogPurge' "
97                         "DESC 'Log cleanup parameters' "
98                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
99         { "logsuccess", NULL, 2, 2, 0, ARG_MAGIC|ARG_ON_OFF|LOG_SUCCESS,
100                 log_cf_gen, "( OLcfgOvAt:4.4 NAME 'olcAccessLogSuccess' "
101                         "DESC 'Log successful ops only' "
102                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
103         { "logold", "filter", 2, 2, 0, ARG_MAGIC|LOG_OLD,
104                 log_cf_gen, "( OLcfgOvAt:4.5 NAME 'olcAccessLogOld' "
105                         "DESC 'Log old values when modifying entries matching the filter' "
106                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
107         { "logoldattr", "attrs", 2, 0, 0, ARG_MAGIC|LOG_OLDATTR,
108                 log_cf_gen, "( OLcfgOvAt:4.6 NAME 'olcAccessLogOldAttr' "
109                         "DESC 'Log old values of these attributes even if unmodified' "
110                         "SYNTAX OMsDirectoryString )", NULL, NULL },
111         { NULL }
112 };
113
114 static ConfigOCs log_cfocs[] = {
115         { "( OLcfgOvOc:4.1 "
116                 "NAME 'olcAccessLogConfig' "
117                 "DESC 'Access log configuration' "
118                 "SUP olcOverlayConfig "
119                 "MUST olcAccessLogDB "
120                 "MAY ( olcAccessLogOps $ olcAccessLogPurge $ olcAccessLogSuccess $ "
121                         "olcAccessLogOld $ olcAccessLogOldAttr ) )",
122                         Cft_Overlay, log_cfats },
123         { NULL }
124 };
125
126 static slap_verbmasks logops[] = {
127         { BER_BVC("all"),               LOG_OP_ALL },
128         { BER_BVC("writes"),    LOG_OP_WRITES },
129         { BER_BVC("session"),   LOG_OP_SESSION },
130         { BER_BVC("reads"),             LOG_OP_READS },
131         { BER_BVC("add"),               LOG_OP_ADD },
132         { BER_BVC("delete"),    LOG_OP_DELETE },
133         { BER_BVC("modify"),    LOG_OP_MODIFY },
134         { BER_BVC("modrdn"),    LOG_OP_MODRDN },
135         { BER_BVC("compare"),   LOG_OP_COMPARE },
136         { BER_BVC("search"),    LOG_OP_SEARCH },
137         { BER_BVC("bind"),              LOG_OP_BIND },
138         { BER_BVC("unbind"),    LOG_OP_UNBIND },
139         { BER_BVC("abandon"),   LOG_OP_ABANDON },
140         { BER_BVC("extended"),  LOG_OP_EXTENDED },
141         { BER_BVC("unknown"),   LOG_OP_UNKNOWN },
142         { BER_BVNULL, 0 }
143 };
144
145 /* Start with "add" in logops */
146 #define EN_OFFSET       4
147
148 enum {
149         LOG_EN_ADD = 0,
150         LOG_EN_DELETE,
151         LOG_EN_MODIFY,
152         LOG_EN_MODRDN,
153         LOG_EN_COMPARE,
154         LOG_EN_SEARCH,
155         LOG_EN_BIND,
156         LOG_EN_UNBIND,
157         LOG_EN_ABANDON,
158         LOG_EN_EXTENDED,
159         LOG_EN_UNKNOWN,
160         LOG_EN__COUNT
161 };
162
163 static ObjectClass *log_ocs[LOG_EN__COUNT], *log_container;
164
165 #define LOG_SCHEMA_ROOT "1.3.6.1.4.1.4203.666.11.5"
166
167 #define LOG_SCHEMA_AT LOG_SCHEMA_ROOT ".1"
168 #define LOG_SCHEMA_OC LOG_SCHEMA_ROOT ".2"
169
170 static AttributeDescription *ad_reqDN, *ad_reqStart, *ad_reqEnd, *ad_reqType,
171         *ad_reqSession, *ad_reqResult, *ad_reqAuthzID, *ad_reqControls,
172         *ad_reqRespControls, *ad_reqMethod, *ad_reqAssertion, *ad_reqNewRDN,
173         *ad_reqNewSuperior, *ad_reqDeleteOldRDN, *ad_reqMod,
174         *ad_reqScope, *ad_reqFilter, *ad_reqAttr, *ad_reqEntries,
175         *ad_reqSizeLimit, *ad_reqTimeLimit, *ad_reqAttrsOnly, *ad_reqData,
176         *ad_reqId, *ad_reqMessage, *ad_reqVersion, *ad_reqDerefAliases,
177         *ad_reqReferral, *ad_reqOld;
178
179 static struct {
180         char *at;
181         AttributeDescription **ad;
182 } lattrs[] = {
183         { "( " LOG_SCHEMA_AT ".1 NAME 'reqDN' "
184                 "DESC 'Target DN of request' "
185                 "EQUALITY distinguishedNameMatch "
186                 "SYNTAX OMsDN "
187                 "SINGLE-VALUE )", &ad_reqDN },
188         { "( " LOG_SCHEMA_AT ".2 NAME 'reqStart' "
189                 "DESC 'Start time of request' "
190                 "EQUALITY generalizedTimeMatch "
191                 "ORDERING generalizedTimeOrderingMatch "
192                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
193                 "SINGLE-VALUE )", &ad_reqStart },
194         { "( " LOG_SCHEMA_AT ".3 NAME 'reqEnd' "
195                 "DESC 'End time of request' "
196                 "EQUALITY generalizedTimeMatch "
197                 "ORDERING generalizedTimeOrderingMatch "
198                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
199                 "SINGLE-VALUE )", &ad_reqEnd },
200         { "( " LOG_SCHEMA_AT ".4 NAME 'reqType' "
201                 "DESC 'Type of request' "
202                 "EQUALITY caseIgnoreMatch "
203                 "SYNTAX OMsDirectoryString "
204                 "SINGLE-VALUE )", &ad_reqType },
205         { "( " LOG_SCHEMA_AT ".5 NAME 'reqSession' "
206                 "DESC 'Session ID of request' "
207                 "EQUALITY caseIgnoreMatch "
208                 "SYNTAX OMsDirectoryString "
209                 "SINGLE-VALUE )", &ad_reqSession },
210         { "( " LOG_SCHEMA_AT ".6 NAME 'reqAuthzID' "
211                 "DESC 'Authorization ID of requestor' "
212                 "EQUALITY distinguishedNameMatch "
213                 "SYNTAX OMsDN "
214                 "SINGLE-VALUE )", &ad_reqAuthzID },
215         { "( " LOG_SCHEMA_AT ".7 NAME 'reqResult' "
216                 "DESC 'Result code of request' "
217                 "EQUALITY integerMatch "
218                 "ORDERING integerOrderingMatch "
219                 "SYNTAX OMsInteger "
220                 "SINGLE-VALUE )", &ad_reqResult },
221         { "( " LOG_SCHEMA_AT ".8 NAME 'reqMessage' "
222                 "DESC 'Error text of request' "
223                 "EQUALITY caseIgnoreMatch "
224                 "SUBSTR caseIgnoreSubstringsMatch "
225                 "SYNTAX OMsDirectoryString "
226                 "SINGLE-VALUE )", &ad_reqMessage },
227         { "( " LOG_SCHEMA_AT ".9 NAME 'reqReferral' "
228                 "DESC 'Referrals returned for request' "
229                 "SUP labeledURI )", &ad_reqReferral },
230         { "( " LOG_SCHEMA_AT ".10 NAME 'reqControls' "
231                 "DESC 'Request controls' "
232                 "SYNTAX OMsOctetString )", &ad_reqControls },
233         { "( " LOG_SCHEMA_AT ".11 NAME 'reqRespControls' "
234                 "DESC 'Response controls of request' "
235                 "SYNTAX OMsOctetString )", &ad_reqRespControls },
236         { "( " LOG_SCHEMA_AT ".12 NAME 'reqId' "
237                 "DESC 'ID of Request to Abandon' "
238                 "EQUALITY integerMatch "
239                 "ORDERING integerOrderingMatch "
240                 "SYNTAX OMsInteger "
241                 "SINGLE-VALUE )", &ad_reqId },
242         { "( " LOG_SCHEMA_AT ".13 NAME 'reqVersion' "
243                 "DESC 'Protocol version of Bind request' "
244                 "EQUALITY integerMatch "
245                 "ORDERING integerOrderingMatch "
246                 "SYNTAX OMsInteger "
247                 "SINGLE-VALUE )", &ad_reqVersion },
248         { "( " LOG_SCHEMA_AT ".14 NAME 'reqMethod' "
249                 "DESC 'Bind method of request' "
250                 "EQUALITY caseIgnoreMatch "
251                 "SYNTAX OMsDirectoryString "
252                 "SINGLE-VALUE )", &ad_reqMethod },
253         { "( " LOG_SCHEMA_AT ".15 NAME 'reqAssertion' "
254                 "DESC 'Compare Assertion of request' "
255                 "SYNTAX OMsDirectoryString "
256                 "SINGLE-VALUE )", &ad_reqAssertion },
257         { "( " LOG_SCHEMA_AT ".16 NAME 'reqMod' "
258                 "DESC 'Modifications of request' "
259                 "EQUALITY octetStringMatch "
260                 "SUBSTR octetStringSubstringsMatch "
261                 "SYNTAX OMsOctetString )", &ad_reqMod },
262         { "( " LOG_SCHEMA_AT ".17 NAME 'reqOld' "
263                 "DESC 'Old values of entry before request completed' "
264                 "EQUALITY octetStringMatch "
265                 "SUBSTR octetStringSubstringsMatch "
266                 "SYNTAX OMsOctetString )", &ad_reqOld },
267         { "( " LOG_SCHEMA_AT ".18 NAME 'reqNewRDN' "
268                 "DESC 'New RDN of request' "
269                 "EQUALITY distinguishedNameMatch "
270                 "SYNTAX OMsDN "
271                 "SINGLE-VALUE )", &ad_reqNewRDN },
272         { "( " LOG_SCHEMA_AT ".19 NAME 'reqDeleteOldRDN' "
273                 "DESC 'Delete old RDN' "
274                 "EQUALITY booleanMatch "
275                 "SYNTAX OMsBoolean "
276                 "SINGLE-VALUE )", &ad_reqDeleteOldRDN },
277         { "( " LOG_SCHEMA_AT ".20 NAME 'reqNewSuperior' "
278                 "DESC 'New superior DN of request' "
279                 "EQUALITY distinguishedNameMatch "
280                 "SYNTAX OMsDN "
281                 "SINGLE-VALUE )", &ad_reqNewSuperior },
282         { "( " LOG_SCHEMA_AT ".21 NAME 'reqScope' "
283                 "DESC 'Scope of request' "
284                 "EQUALITY caseIgnoreMatch "
285                 "SYNTAX OMsDirectoryString "
286                 "SINGLE-VALUE )", &ad_reqScope },
287         { "( " LOG_SCHEMA_AT ".22 NAME 'reqDerefAliases' "
288                 "DESC 'Disposition of Aliases in request' "
289                 "EQUALITY caseIgnoreMatch "
290                 "SYNTAX OMsDirectoryString "
291                 "SINGLE-VALUE )", &ad_reqDerefAliases },
292         { "( " LOG_SCHEMA_AT ".23 NAME 'reqAttrsOnly' "
293                 "DESC 'Attributes and values of request' "
294                 "EQUALITY booleanMatch "
295                 "SYNTAX OMsBoolean "
296                 "SINGLE-VALUE )", &ad_reqAttrsOnly },
297         { "( " LOG_SCHEMA_AT ".24 NAME 'reqFilter' "
298                 "DESC 'Filter of request' "
299                 "EQUALITY caseIgnoreMatch "
300                 "SUBSTR caseIgnoreSubstringsMatch "
301                 "SYNTAX OMsDirectoryString "
302                 "SINGLE-VALUE )", &ad_reqFilter },
303         { "( " LOG_SCHEMA_AT ".25 NAME 'reqAttr' "
304                 "DESC 'Attributes of request' "
305                 "EQUALITY caseIgnoreMatch "
306                 "SYNTAX OMsDirectoryString )", &ad_reqAttr },
307         { "( " LOG_SCHEMA_AT ".26 NAME 'reqSizeLimit' "
308                 "DESC 'Size limit of request' "
309                 "EQUALITY integerMatch "
310                 "ORDERING integerOrderingMatch "
311                 "SYNTAX OMsInteger "
312                 "SINGLE-VALUE )", &ad_reqSizeLimit },
313         { "( " LOG_SCHEMA_AT ".27 NAME 'reqTimeLimit' "
314                 "DESC 'Time limit of request' "
315                 "EQUALITY integerMatch "
316                 "ORDERING integerOrderingMatch "
317                 "SYNTAX OMsInteger "
318                 "SINGLE-VALUE )", &ad_reqTimeLimit },
319         { "( " LOG_SCHEMA_AT ".28 NAME 'reqEntries' "
320                 "DESC 'Number of entries returned' "
321                 "EQUALITY integerMatch "
322                 "ORDERING integerOrderingMatch "
323                 "SYNTAX OMsInteger "
324                 "SINGLE-VALUE )", &ad_reqEntries },
325         { "( " LOG_SCHEMA_AT ".29 NAME 'reqData' "
326                 "DESC 'Data of extended request' "
327                 "EQUALITY octetStringMatch "
328                 "SUBSTR octetStringSubstringsMatch "
329                 "SYNTAX OMsOctetString "
330                 "SINGLE-VALUE )", &ad_reqData },
331         { NULL, NULL }
332 };
333
334 static struct {
335         char *ot;
336         ObjectClass **oc;
337 } locs[] = {
338         { "( " LOG_SCHEMA_OC ".0 NAME 'auditContainer' "
339                 "DESC 'AuditLog container' "
340                 "SUP top STRUCTURAL "
341                 "MAY ( cn $ reqStart $ reqEnd ) )", &log_container },
342         { "( " LOG_SCHEMA_OC ".1 NAME 'auditObject' "
343                 "DESC 'OpenLDAP request auditing' "
344                 "SUP top STRUCTURAL "
345                 "MUST ( reqStart $ reqType $ reqSession ) "
346                 "MAY ( reqDN $ reqAuthzID $ reqControls $ reqRespControls $ reqEnd $ "
347                         "reqResult $ reqMessage $ reqReferral ) )",
348                                 &log_ocs[LOG_EN_UNBIND] },
349         { "( " LOG_SCHEMA_OC ".2 NAME 'auditReadObject' "
350                 "DESC 'OpenLDAP read request record' "
351                 "SUP auditObject STRUCTURAL )", NULL },
352         { "( " LOG_SCHEMA_OC ".3 NAME 'auditWriteObject' "
353                 "DESC 'OpenLDAP write request record' "
354                 "SUP auditObject STRUCTURAL )", NULL },
355         { "( " LOG_SCHEMA_OC ".4 NAME 'auditAbandon' "
356                 "DESC 'Abandon operation' "
357                 "SUP auditObject STRUCTURAL "
358                 "MUST reqId )", &log_ocs[LOG_EN_ABANDON] },
359         { "( " LOG_SCHEMA_OC ".5 NAME 'auditAdd' "
360                 "DESC 'Add operation' "
361                 "SUP auditWriteObject STRUCTURAL "
362                 "MUST reqMod )", &log_ocs[LOG_EN_ADD] },
363         { "( " LOG_SCHEMA_OC ".6 NAME 'auditBind' "
364                 "DESC 'Bind operation' "
365                 "SUP auditObject STRUCTURAL "
366                 "MUST ( reqVersion $ reqMethod ) )", &log_ocs[LOG_EN_BIND] },
367         { "( " LOG_SCHEMA_OC ".7 NAME 'auditCompare' "
368                 "DESC 'Compare operation' "
369                 "SUP auditReadObject STRUCTURAL "
370                 "MUST reqAssertion )", &log_ocs[LOG_EN_COMPARE] },
371         { "( " LOG_SCHEMA_OC ".8 NAME 'auditDelete' "
372                 "DESC 'Delete operation' "
373                 "SUP auditWriteObject STRUCTURAL "
374                 "MAY reqOld )", &log_ocs[LOG_EN_DELETE] },
375         { "( " LOG_SCHEMA_OC ".9 NAME 'auditModify' "
376                 "DESC 'Modify operation' "
377                 "SUP auditWriteObject STRUCTURAL "
378                 "MAY reqOld MUST reqMod )", &log_ocs[LOG_EN_MODIFY] },
379         { "( " LOG_SCHEMA_OC ".10 NAME 'auditModRDN' "
380                 "DESC 'ModRDN operation' "
381                 "SUP auditWriteObject STRUCTURAL "
382                 "MUST ( reqNewRDN $ reqDeleteOldRDN ) "
383                 "MAY ( reqNewSuperior $ reqOld ) )", &log_ocs[LOG_EN_MODRDN] },
384         { "( " LOG_SCHEMA_OC ".11 NAME 'auditSearch' "
385                 "DESC 'Search operation' "
386                 "SUP auditReadObject STRUCTURAL "
387                 "MUST ( reqScope $ reqDerefAliases $ reqAttrsonly ) "
388                 "MAY ( reqFilter $ reqAttr $ reqEntries $ reqSizeLimit $ "
389                         "reqTimeLimit ) )", &log_ocs[LOG_EN_SEARCH] },
390         { "( " LOG_SCHEMA_OC ".12 NAME 'auditExtended' "
391                 "DESC 'Extended operation' "
392                 "SUP auditObject STRUCTURAL "
393                 "MAY reqData )", &log_ocs[LOG_EN_EXTENDED] },
394         { NULL, NULL }
395 };
396
397 #define RDNEQ   "reqStart="
398
399 /* Our time intervals are of the form [ddd+]hh:mm[:ss]
400  * If a field is present, it must be two digits. (Except for
401  * days, which can be arbitrary width.)
402  */
403 static int
404 log_age_parse(char *agestr)
405 {
406         int t1, t2;
407         int gotdays = 0;
408         char *endptr;
409
410         t1 = strtol( agestr, &endptr, 10 );
411         /* Is there a days delimiter? */
412         if ( *endptr == '+' ) {
413                 /* 32 bit time only covers about 68 years */
414                 if ( t1 < 0 || t1 > 25000 )
415                         return -1;
416                 t1 *= 24;
417                 gotdays = 1;
418                 agestr = endptr + 1;
419         } else {
420                 if ( agestr[2] != ':' ) {
421                         /* No valid delimiter found, fail */
422                         return -1;
423                 }
424                 t1 *= 60;
425                 agestr += 3;
426         }
427
428         t2 = atoi( agestr );
429         t1 += t2;
430
431         if ( agestr[2] ) {
432                 /* if there's a delimiter, it can only be a colon */
433                 if ( agestr[2] != ':' )
434                         return -1;
435         } else {
436                 /* If we're at the end of the string, and we started with days,
437                  * fail because we expected to find minutes too.
438                  */
439                 return gotdays ? -1 : t1 * 60;
440         }
441
442         agestr += 3;
443         t2 = atoi( agestr );
444
445         /* last field can only be seconds */
446         if ( agestr[2] && ( agestr[2] != ':' || !gotdays ))
447                 return -1;
448         t1 *= 60;
449         t1 += t2;
450
451         if ( agestr[2] ) {
452                 agestr += 3;
453                 if ( agestr[2] )
454                         return -1;
455                 t1 *= 60;
456                 t1 += atoi( agestr );
457         } else if ( gotdays ) {
458                 /* only got days+hh:mm */
459                 t1 *= 60;
460         }
461         return t1;
462 }
463
464 static void
465 log_age_unparse( int age, struct berval *agebv )
466 {
467         int dd, hh, mm, ss;
468         char *ptr;
469
470         ss = age % 60;
471         age /= 60;
472         mm = age % 60;
473         age /= 60;
474         hh = age % 24;
475         age /= 24;
476         dd = age;
477
478         ptr = agebv->bv_val;
479
480         if ( dd ) 
481                 ptr += sprintf( ptr, "%d+", dd );
482         ptr += sprintf( ptr, "%02d:%02d", hh, mm );
483         if ( ss )
484                 ptr += sprintf( ptr, ":%02d", ss );
485
486         agebv->bv_len = ptr - agebv->bv_val;
487 }
488
489 static slap_callback nullsc = { NULL, NULL, NULL, NULL };
490
491 #define PURGE_INCREMENT 100
492
493 typedef struct purge_data {
494         int slots;
495         int used;
496         BerVarray dn;
497         BerVarray ndn;
498 } purge_data;
499
500 static int
501 log_old_lookup( Operation *op, SlapReply *rs )
502 {
503         purge_data *pd = op->o_callback->sc_private;
504
505         if ( rs->sr_type != REP_SEARCH) return 0;
506
507         if ( slapd_shutdown ) return 0;
508
509         if ( pd->used >= pd->slots ) {
510                 pd->slots += PURGE_INCREMENT;
511                 pd->dn = ch_realloc( pd->dn, pd->slots * sizeof( struct berval ));
512                 pd->ndn = ch_realloc( pd->ndn, pd->slots * sizeof( struct berval ));
513         }
514         ber_dupbv( &pd->dn[pd->used], &rs->sr_entry->e_name );
515         ber_dupbv( &pd->ndn[pd->used], &rs->sr_entry->e_nname );
516         pd->used++;
517         return 0;
518 }
519
520 /* Periodically search for old entries in the log database and delete them */
521 static void *
522 accesslog_purge( void *ctx, void *arg )
523 {
524         struct re_s *rtask = arg;
525         struct log_info *li = rtask->arg;
526
527         Connection conn = {0};
528         OperationBuffer opbuf;
529         Operation *op = (Operation *) &opbuf;
530         SlapReply rs = {REP_RESULT};
531         slap_callback cb = { NULL, log_old_lookup, NULL, NULL };
532         Filter f;
533         AttributeAssertion ava = {0};
534         purge_data pd = {0};
535         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE];
536         time_t old = slap_get_time();
537
538         connection_fake_init( &conn, op, ctx );
539
540         f.f_choice = LDAP_FILTER_LE;
541         f.f_ava = &ava;
542         f.f_next = NULL;
543
544         ava.aa_desc = ad_reqStart;
545         ava.aa_value.bv_val = timebuf;
546         ava.aa_value.bv_len = sizeof(timebuf);
547
548         old -= li->li_age;
549         slap_timestamp( &old, &ava.aa_value );
550
551         op->o_tag = LDAP_REQ_SEARCH;
552         op->o_bd = li->li_db;
553         op->o_dn = li->li_db->be_rootdn;
554         op->o_ndn = li->li_db->be_rootndn;
555         op->o_req_dn = li->li_db->be_suffix[0];
556         op->o_req_ndn = li->li_db->be_nsuffix[0];
557         op->o_callback = &cb;
558         op->ors_scope = LDAP_SCOPE_ONELEVEL;
559         op->ors_deref = LDAP_DEREF_NEVER;
560         op->ors_tlimit = SLAP_NO_LIMIT;
561         op->ors_slimit = SLAP_NO_LIMIT;
562         op->ors_filter = &f;
563         filter2bv_x( op, &f, &op->ors_filterstr );
564         op->ors_attrs = slap_anlist_no_attrs;
565         op->ors_attrsonly = 1;
566         
567         cb.sc_private = &pd;
568
569         op->o_bd->be_search( op, &rs );
570         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
571
572         if ( pd.used ) {
573                 int i;
574
575                 op->o_tag = LDAP_REQ_DELETE;
576                 op->o_callback = &nullsc;
577
578                 for (i=0; i<pd.used; i++) {
579                         op->o_req_dn = pd.dn[i];
580                         op->o_req_ndn = pd.ndn[i];
581                         if ( !slapd_shutdown )
582                                 op->o_bd->be_delete( op, &rs );
583                         ch_free( pd.ndn[i].bv_val );
584                         ch_free( pd.dn[i].bv_val );
585                 }
586                 ch_free( pd.ndn );
587                 ch_free( pd.dn );
588         }
589
590         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
591         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
592         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
593
594         return NULL;
595 }
596
597 static int
598 log_cf_gen(ConfigArgs *c)
599 {
600         slap_overinst *on = (slap_overinst *)c->bi;
601         struct log_info *li = on->on_bi.bi_private;
602         int rc = 0;
603         slap_mask_t tmask = 0;
604         char agebuf[2*STRLENOF("ddddd+hh:mm:ss  ")];
605         struct berval agebv, cyclebv;
606
607         switch( c->op ) {
608         case SLAP_CONFIG_EMIT:
609                 switch( c->type ) {
610                 case LOG_DB:
611                         if ( li->li_db == NULL ) {
612                                 snprintf( c->msg, sizeof( c->msg ),
613                                         "accesslog: \"logdb <suffix>\" must be specified" );
614                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
615                                         c->log, c->msg, c->value_dn.bv_val );
616                                 rc = 1;
617                                 break;
618                         }
619                         value_add( &c->rvalue_vals, li->li_db->be_suffix );
620                         value_add( &c->rvalue_nvals, li->li_db->be_nsuffix );
621                         break;
622                 case LOG_OPS:
623                         rc = mask_to_verbs( logops, li->li_ops, &c->rvalue_vals );
624                         break;
625                 case LOG_PURGE:
626                         if ( !li->li_age ) {
627                                 rc = 1;
628                                 break;
629                         }
630                         agebv.bv_val = agebuf;
631                         log_age_unparse( li->li_age, &agebv );
632                         agebv.bv_val[agebv.bv_len] = ' ';
633                         agebv.bv_len++;
634                         cyclebv.bv_val = agebv.bv_val + agebv.bv_len;
635                         log_age_unparse( li->li_cycle, &cyclebv );
636                         agebv.bv_len += cyclebv.bv_len;
637                         value_add_one( &c->rvalue_vals, &agebv );
638                         break;
639                 case LOG_SUCCESS:
640                         if ( li->li_success )
641                                 c->value_int = li->li_success;
642                         else
643                                 rc = 1;
644                         break;
645                 case LOG_OLD:
646                         if ( li->li_oldf ) {
647                                 filter2bv( li->li_oldf, &agebv );
648                                 ber_bvarray_add( &c->rvalue_vals, &agebv );
649                         }
650                         else
651                                 rc = 1;
652                         break;
653                 case LOG_OLDATTR:
654                         if ( li->li_oldattrs ) {
655                                 log_attr *la;
656
657                                 for ( la = li->li_oldattrs; la; la=la->next )
658                                         value_add_one( &c->rvalue_vals, &la->attr->ad_cname );
659                         }
660                         else
661                                 rc = 1;
662                         break;
663                 }
664                 break;
665         case LDAP_MOD_DELETE:
666                 switch( c->type ) {
667                 case LOG_DB:
668                         /* noop. this should always be a valid backend. */
669                         break;
670                 case LOG_OPS:
671                         if ( c->valx < 0 ) {
672                                 li->li_ops = 0;
673                         } else {
674                                 rc = verbs_to_mask( 1, &c->line, logops, &tmask );
675                                 if ( rc == 0 )
676                                         li->li_ops &= ~tmask;
677                         }
678                         break;
679                 case LOG_PURGE:
680                         if ( li->li_task ) {
681                                 struct re_s *re = li->li_task;
682                                 li->li_task = NULL;
683                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
684                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
685                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
686                         }
687                         li->li_age = 0;
688                         li->li_cycle = 0;
689                         break;
690                 case LOG_SUCCESS:
691                         li->li_success = 0;
692                         break;
693                 case LOG_OLD:
694                         if ( li->li_oldf ) {
695                                 filter_free( li->li_oldf );
696                                 li->li_oldf = NULL;
697                         }
698                         break;
699                 case LOG_OLDATTR:
700                         if ( c->valx < 0 ) {
701                                 log_attr *la, *ln;
702
703                                 for ( la = li->li_oldattrs; la; la = ln ) {
704                                         ln = la->next;
705                                         ch_free( la );
706                                 }
707                         } else {
708                                 log_attr *la = NULL, **lp;
709                                 int i;
710
711                                 for ( lp = &li->li_oldattrs, i=0; i < c->valx; i++ ) {
712                                         la = *lp;
713                                         lp = &la->next;
714                                 }
715                                 *lp = la->next;
716                                 ch_free( la );
717                         }
718                         break;
719                 }
720                 break;
721         default:
722                 switch( c->type ) {
723                 case LOG_DB:
724                         li->li_db = select_backend( &c->value_ndn, 0, 0 );
725                         if ( !li->li_db ) {
726                                 snprintf( c->msg, sizeof( c->msg ),
727                                         "<%s> no matching backend found for suffix",
728                                         c->argv[0] );
729                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
730                                         c->log, c->msg, c->value_dn.bv_val );
731                                 rc = 1;
732                         } else if ( BER_BVISEMPTY( &li->li_db->be_rootdn )) {
733                                 snprintf( c->msg, sizeof( c->msg ),
734                                         "<%s> no rootDN was configured for suffix",
735                                         c->argv[0] );
736                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
737                                         c->log, c->msg, c->value_dn.bv_val );
738                                 rc = 1;
739                         }
740                         ch_free( c->value_dn.bv_val );
741                         ch_free( c->value_ndn.bv_val );
742                         break;
743                 case LOG_OPS:
744                         rc = verbs_to_mask( c->argc, c->argv, logops, &tmask );
745                         if ( rc == 0 )
746                                 li->li_ops |= tmask;
747                         break;
748                 case LOG_PURGE:
749                         li->li_age = log_age_parse( c->argv[1] );
750                         if ( li->li_age < 1 ) {
751                                 rc = 1;
752                         } else {
753                                 li->li_cycle = log_age_parse( c->argv[2] );
754                                 if ( li->li_cycle < 1 ) {
755                                         rc = 1;
756                                 } else if ( slapMode & SLAP_SERVER_MODE ) {
757                                         struct re_s *re = li->li_task;
758                                         if ( re )
759                                                 re->interval.tv_sec = li->li_cycle;
760                                         else
761                                                 li->li_task = ldap_pvt_runqueue_insert( &slapd_rq,
762                                                         li->li_cycle, accesslog_purge, li,
763                                                         "accesslog_purge", li->li_db ?
764                                                                 li->li_db->be_suffix[0].bv_val :
765                                                                 c->be->be_suffix[0].bv_val );
766                                 }
767                         }
768                         break;
769                 case LOG_SUCCESS:
770                         li->li_success = c->value_int;
771                         break;
772                 case LOG_OLD:
773                         li->li_oldf = str2filter( c->argv[1] );
774                         if ( !li->li_oldf ) {
775                                 sprintf( c->msg, "bad filter!" );
776                                 rc = 1;
777                         }
778                         break;
779                 case LOG_OLDATTR: {
780                         int i;
781                         AttributeDescription *ad;
782                         const char *text;
783
784                         for ( i=1; i< c->argc; i++ ) {
785                                 ad = NULL;
786                                 if ( slap_str2ad( c->argv[i], &ad, &text ) == LDAP_SUCCESS ) {
787                                         log_attr *la = ch_malloc( sizeof( log_attr ));
788                                         la->attr = ad;
789                                         la->next = li->li_oldattrs;
790                                         li->li_oldattrs = la;
791                                 } else {
792                                         sprintf( c->msg, "%s: %s", c->argv[i], text );
793                                         rc = ARG_BAD_CONF;
794                                         break;
795                                 }
796                         }
797                         }
798                         break;
799                 }
800                 break;
801         }
802         return rc;
803 }
804
805 static Entry *accesslog_entry( Operation *op, int logop,
806         Operation *op2 ) {
807         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
808         log_info *li = on->on_bi.bi_private;
809
810         char rdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
811         char nrdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
812
813         struct berval rdn, nrdn, timestamp, ntimestamp, bv;
814         slap_verbmasks *lo = logops+logop+EN_OFFSET;
815
816         Entry *e = entry_alloc();
817
818         strcpy( rdnbuf, RDNEQ );
819         rdn.bv_val = rdnbuf;
820         strcpy( nrdnbuf, RDNEQ );
821         nrdn.bv_val = nrdnbuf;
822
823         timestamp.bv_val = rdnbuf+STRLENOF(RDNEQ);
824         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
825         slap_timestamp( &op->o_time, &timestamp );
826         sprintf( timestamp.bv_val + timestamp.bv_len-1, ".%06dZ", op->o_tincr );
827         timestamp.bv_len += 7;
828
829         rdn.bv_len = STRLENOF(RDNEQ)+timestamp.bv_len;
830         ad_reqStart->ad_type->sat_equality->smr_normalize(
831                 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, ad_reqStart->ad_type->sat_syntax,
832                 ad_reqStart->ad_type->sat_equality, &timestamp, &ntimestamp,
833                 op->o_tmpmemctx );
834
835         strcpy( nrdn.bv_val + STRLENOF(RDNEQ), ntimestamp.bv_val );
836         nrdn.bv_len = STRLENOF(RDNEQ)+ntimestamp.bv_len;
837         build_new_dn( &e->e_name, li->li_db->be_suffix, &rdn, NULL );
838         build_new_dn( &e->e_nname, li->li_db->be_nsuffix, &nrdn, NULL );
839
840         attr_merge_one( e, slap_schema.si_ad_objectClass,
841                 &log_ocs[logop]->soc_cname, NULL );
842         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
843                 &log_ocs[logop]->soc_cname, NULL );
844         attr_merge_one( e, ad_reqStart, &timestamp, &ntimestamp );
845         op->o_tmpfree( ntimestamp.bv_val, op->o_tmpmemctx );
846
847         slap_op_time( &op2->o_time, &op2->o_tincr );
848
849         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
850         slap_timestamp( &op2->o_time, &timestamp );
851         sprintf( timestamp.bv_val + timestamp.bv_len-1, ".%06dZ", op2->o_tincr );
852         timestamp.bv_len += 7;
853
854         attr_merge_normalize_one( e, ad_reqEnd, &timestamp, op->o_tmpmemctx );
855
856         /* Exops have OID appended */
857         if ( logop == LOG_EN_EXTENDED ) {
858                 bv.bv_len = lo->word.bv_len + op->ore_reqoid.bv_len + 2;
859                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
860                 AC_MEMCPY( bv.bv_val, lo->word.bv_val, lo->word.bv_len );
861                 bv.bv_val[lo->word.bv_len] = '{';
862                 AC_MEMCPY( bv.bv_val+lo->word.bv_len+1, op->ore_reqoid.bv_val,
863                         op->ore_reqoid.bv_len );
864                 bv.bv_val[bv.bv_len-1] = '}';
865                 bv.bv_val[bv.bv_len] = '\0';
866                 attr_merge_one( e, ad_reqType, &bv, NULL );
867         } else {
868                 attr_merge_one( e, ad_reqType, &lo->word, NULL );
869         }
870
871         rdn.bv_len = sprintf( rdn.bv_val, "%lu", op->o_connid );
872         attr_merge_one( e, ad_reqSession, &rdn, NULL );
873
874         if ( BER_BVISNULL( &op->o_dn )) 
875                 attr_merge_one( e, ad_reqAuthzID, (struct berval *)&slap_empty_bv,
876                         (struct berval *)&slap_empty_bv );
877         else
878                 attr_merge_one( e, ad_reqAuthzID, &op->o_dn, &op->o_ndn );
879
880         /* FIXME: need to add reqControls and reqRespControls */
881
882         return e;
883 }
884
885 static struct berval scopes[] = {
886         BER_BVC("base"),
887         BER_BVC("one"),
888         BER_BVC("sub"),
889         BER_BVC("subord")
890 };
891
892 static struct berval derefs[] = {
893         BER_BVC("never"),
894         BER_BVC("searching"),
895         BER_BVC("finding"),
896         BER_BVC("always")
897 };
898
899 static struct berval simple = BER_BVC("SIMPLE");
900
901 static void accesslog_val2val(AttributeDescription *ad, struct berval *val,
902         char c_op, struct berval *dst) {
903         char *ptr;
904
905         dst->bv_len = ad->ad_cname.bv_len + val->bv_len + 2;
906         if ( c_op ) dst->bv_len++;
907
908         dst->bv_val = ch_malloc( dst->bv_len+1 );
909
910         ptr = lutil_strcopy( dst->bv_val, ad->ad_cname.bv_val );
911         *ptr++ = ':';
912         if ( c_op )
913                 *ptr++ = c_op;
914         *ptr++ = ' ';
915         AC_MEMCPY( ptr, val->bv_val, val->bv_len );
916         dst->bv_val[dst->bv_len] = '\0';
917 }
918
919 static int accesslog_response(Operation *op, SlapReply *rs) {
920         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
921         log_info *li = on->on_bi.bi_private;
922         Attribute *a, *last_attr;
923         Modifications *m;
924         struct berval *b;
925         int i;
926         int logop;
927         slap_verbmasks *lo;
928         Entry *e = NULL, *old = NULL;
929         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE+8];
930         struct berval bv;
931         char *ptr;
932         BerVarray vals;
933         Operation op2 = {0};
934         SlapReply rs2 = {REP_RESULT};
935
936         if ( rs->sr_type != REP_RESULT && rs->sr_type != REP_EXTENDED )
937                 return SLAP_CB_CONTINUE;
938
939         switch ( op->o_tag ) {
940         case LDAP_REQ_ADD:              logop = LOG_EN_ADD; break;
941         case LDAP_REQ_DELETE:   logop = LOG_EN_DELETE; break;
942         case LDAP_REQ_MODIFY:   logop = LOG_EN_MODIFY; break;
943         case LDAP_REQ_MODRDN:   logop = LOG_EN_MODRDN; break;
944         case LDAP_REQ_COMPARE:  logop = LOG_EN_COMPARE; break;
945         case LDAP_REQ_SEARCH:   logop = LOG_EN_SEARCH; break;
946         case LDAP_REQ_BIND:             logop = LOG_EN_BIND; break;
947         case LDAP_REQ_EXTENDED: logop = LOG_EN_EXTENDED; break;
948         default:        /* unknown operation type */
949                 logop = LOG_EN_UNKNOWN; break;
950         }       /* Unbind and Abandon never reach here */
951
952         lo = logops+logop+EN_OFFSET;
953         if ( !( li->li_ops & lo->mask ))
954                 return SLAP_CB_CONTINUE;
955
956         if ( lo->mask & LOG_OP_WRITES ) {
957                 ldap_pvt_thread_mutex_lock( &li->li_log_mutex );
958                 old = li->li_old;
959                 li->li_old = NULL;
960                 ldap_pvt_thread_rmutex_unlock( &li->li_op_rmutex, op->o_tid );
961         }
962
963         if ( li->li_success && rs->sr_err != LDAP_SUCCESS )
964                 goto done;
965
966         e = accesslog_entry( op, logop, &op2 );
967
968         attr_merge_one( e, ad_reqDN, &op->o_req_dn, &op->o_req_ndn );
969
970         if ( rs->sr_text ) {
971                 ber_str2bv( rs->sr_text, 0, 0, &bv );
972                 attr_merge_one( e, ad_reqMessage, &bv, NULL );
973         }
974         bv.bv_len = sprintf( timebuf, "%d", rs->sr_err );
975         bv.bv_val = timebuf;
976
977         attr_merge_one( e, ad_reqResult, &bv, NULL );
978
979         last_attr = attr_find( e->e_attrs, ad_reqResult );
980
981         switch( logop ) {
982         case LOG_EN_ADD:
983         case LOG_EN_DELETE: {
984                 char c_op;
985                 Entry *e2;
986
987                 if ( logop == LOG_EN_ADD ) {
988                         e2 = op->ora_e;
989                         c_op = '+';
990                 } else {
991                         if ( !old )
992                                 break;
993                         e2 = old;
994                         c_op = 0;
995                 }
996                 /* count all the vals */
997                 i = 0;
998                 for ( a=e2->e_attrs; a; a=a->a_next ) {
999                         if ( a->a_vals ) {
1000                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++) {
1001                                         i++;
1002                                 }
1003                         }
1004                 }
1005                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1006                 i = 0;
1007                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1008                         if ( a->a_vals ) {
1009                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1010                                         accesslog_val2val( a->a_desc, b, c_op, &vals[i] );
1011                                 }
1012                         }
1013                 }
1014                 vals[i].bv_val = NULL;
1015                 vals[i].bv_len = 0;
1016                 a = attr_alloc( logop == LOG_EN_ADD ? ad_reqMod : ad_reqOld );
1017                 a->a_vals = vals;
1018                 a->a_nvals = vals;
1019                 last_attr->a_next = a;
1020                 break;
1021         }
1022
1023         case LOG_EN_MODIFY:
1024                 /* count all the mods */
1025                 i = 0;
1026                 for ( m=op->orm_modlist; m; m=m->sml_next ) {
1027                         if ( m->sml_values ) {
1028                                 for (b=m->sml_values; !BER_BVISNULL( b ); b++) {
1029                                         i++;
1030                                 }
1031                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1032                                 m->sml_op == LDAP_MOD_REPLACE ) {
1033                                 i++;
1034                         }
1035                 }
1036                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1037                 i = 0;
1038
1039                 /* init flags on old entry */
1040                 if ( old ) {
1041                         for ( a=old->e_attrs; a; a=a->a_next ) {
1042                                 log_attr *la;
1043                                 a->a_flags = 0;
1044
1045                                 /* look for attrs that are always logged */
1046                                 for ( la=li->li_oldattrs; la; la=la->next )
1047                                         if ( a->a_desc == la->attr )
1048                                                 a->a_flags = 1;
1049                         }
1050                 }
1051
1052                 for ( m=op->orm_modlist; m; m=m->sml_next ) {
1053                         /* Mark this attribute as modified */
1054                         if ( old ) {
1055                                 a = attr_find( old->e_attrs, m->sml_desc );
1056                                 if ( a )
1057                                         a->a_flags = 1;
1058                         }
1059                         if ( m->sml_values ) {
1060                                 for (b=m->sml_values; !BER_BVISNULL( b ); b++,i++) {
1061                                         char c_op;
1062
1063                                         switch( m->sml_op ) {
1064                                         case LDAP_MOD_ADD: c_op = '+'; break;
1065                                         case LDAP_MOD_DELETE:   c_op = '-'; break;
1066                                         case LDAP_MOD_REPLACE:  c_op = '='; break;
1067                                         case LDAP_MOD_INCREMENT:        c_op = '#'; break;
1068
1069                                         /* unknown op. there shouldn't be any of these. we
1070                                          * don't know what to do with it, but we shouldn't just
1071                                          * ignore it.
1072                                          */
1073                                         default: c_op = '?'; break;
1074                                         }
1075                                         accesslog_val2val( m->sml_desc, b, c_op, &vals[i] );
1076                                 }
1077                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1078                                 m->sml_op == LDAP_MOD_REPLACE ) {
1079                                 vals[i].bv_len = m->sml_desc->ad_cname.bv_len + 2;
1080                                 vals[i].bv_val = ch_malloc( vals[i].bv_len+1 );
1081                                 ptr = lutil_strcopy( vals[i].bv_val,
1082                                         m->sml_desc->ad_cname.bv_val );
1083                                 *ptr++ = ':';
1084                                 if ( m->sml_op == LDAP_MOD_DELETE )
1085                                         *ptr++ = '-';
1086                                 else
1087                                         *ptr++ = '=';
1088                                 *ptr = '\0';
1089                                 i++;
1090                         }
1091                 }
1092                 vals[i].bv_val = NULL;
1093                 vals[i].bv_len = 0;
1094                 a = attr_alloc( ad_reqMod );
1095                 a->a_vals = vals;
1096                 a->a_nvals = vals;
1097                 last_attr->a_next = a;
1098
1099                 if ( old ) {
1100                         last_attr = a;
1101                         /* count all the vals */
1102                         i = 0;
1103                         for ( a=old->e_attrs; a; a=a->a_next ) {
1104                                 if ( a->a_vals && a->a_flags ) {
1105                                         for (b=a->a_vals; !BER_BVISNULL( b ); b++) {
1106                                         i++;
1107                                         }
1108                                 }
1109                         }
1110                         vals = ch_malloc( (i+1) * sizeof( struct berval ));
1111                         i = 0;
1112                         for ( a=old->e_attrs; a; a=a->a_next ) {
1113                                 if ( a->a_vals && a->a_flags ) {
1114                                         for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1115                                                 accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1116                                         }
1117                                 }
1118                         }
1119                         vals[i].bv_val = NULL;
1120                         vals[i].bv_len = 0;
1121                         a = attr_alloc( ad_reqOld );
1122                         a->a_vals = vals;
1123                         a->a_nvals = vals;
1124                         last_attr->a_next = a;
1125                 }
1126                 break;
1127
1128         case LOG_EN_MODRDN:
1129                 if ( old ) {
1130                         /* count all the vals */
1131                         i = 0;
1132                         for ( a=old->e_attrs; a; a=a->a_next ) {
1133                                 log_attr *la;
1134
1135                                 /* look for attrs that are always logged */
1136                                 for ( la=li->li_oldattrs; la; la=la->next ) {
1137                                         if ( a->a_desc == la->attr ) {
1138                                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++) {
1139                                                         i++;
1140                                                 }
1141                                         }
1142                                 }
1143                         }
1144                         vals = ch_malloc( (i+1) * sizeof( struct berval ));
1145                         i = 0;
1146                         for ( a=old->e_attrs; a; a=a->a_next ) {
1147                                 log_attr *la;
1148                                 for ( la=li->li_oldattrs; la; la=la->next ) {
1149                                         if ( a->a_desc == la->attr ) {
1150                                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1151                                                         accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1152                                                 }
1153                                         }
1154                                 }
1155                         }
1156                         vals[i].bv_val = NULL;
1157                         vals[i].bv_len = 0;
1158                         a = attr_alloc( ad_reqOld );
1159                         a->a_vals = vals;
1160                         a->a_nvals = vals;
1161                         last_attr->a_next = a;
1162                 }
1163                 attr_merge_one( e, ad_reqNewRDN, &op->orr_newrdn, &op->orr_nnewrdn );
1164                 attr_merge_one( e, ad_reqDeleteOldRDN, op->orr_deleteoldrdn ?
1165                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1166                         NULL );
1167                 if ( op->orr_newSup ) {
1168                         attr_merge_one( e, ad_reqNewSuperior, op->orr_newSup, op->orr_nnewSup );
1169                 }
1170                 break;
1171
1172         case LOG_EN_COMPARE:
1173                 bv.bv_len = op->orc_ava->aa_desc->ad_cname.bv_len + 1 +
1174                         op->orc_ava->aa_value.bv_len;
1175                 bv.bv_val = op->o_tmpalloc( bv.bv_len+1, op->o_tmpmemctx );
1176                 ptr = lutil_strcopy( bv.bv_val, op->orc_ava->aa_desc->ad_cname.bv_val );
1177                 *ptr++ = '=';
1178                 AC_MEMCPY( ptr, op->orc_ava->aa_value.bv_val, op->orc_ava->aa_value.bv_len );
1179                 bv.bv_val[bv.bv_len] = '\0';
1180                 attr_merge_one( e, ad_reqAssertion, &bv, NULL );
1181                 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1182                 break;
1183
1184         case LOG_EN_SEARCH:
1185                 attr_merge_one( e, ad_reqScope, &scopes[op->ors_scope], NULL );
1186                 attr_merge_one( e, ad_reqDerefAliases, &derefs[op->ors_deref], NULL );
1187                 attr_merge_one( e, ad_reqAttrsOnly, op->ors_attrsonly ?
1188                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1189                         NULL );
1190                 if ( !BER_BVISEMPTY( &op->ors_filterstr ))
1191                         attr_merge_one( e, ad_reqFilter, &op->ors_filterstr, NULL );
1192                 if ( op->ors_attrs ) {
1193                         /* count them */
1194                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1195                                 ;
1196                         vals = op->o_tmpalloc( (i+1) * sizeof(struct berval),
1197                                 op->o_tmpmemctx );
1198                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1199                                 vals[i] = op->ors_attrs[i].an_name;
1200                         vals[i].bv_val = NULL;
1201                         vals[i].bv_len = 0;
1202                         attr_merge( e, ad_reqAttr, vals, NULL );
1203                         op->o_tmpfree( vals, op->o_tmpmemctx );
1204                 }
1205                 bv.bv_val = timebuf;
1206                 bv.bv_len = sprintf( bv.bv_val, "%d", rs->sr_nentries );
1207                 attr_merge_one( e, ad_reqEntries, &bv, NULL );
1208
1209                 bv.bv_len = sprintf( bv.bv_val, "%d", op->ors_tlimit );
1210                 attr_merge_one( e, ad_reqTimeLimit, &bv, NULL );
1211
1212                 bv.bv_len = sprintf( bv.bv_val, "%d", op->ors_slimit );
1213                 attr_merge_one( e, ad_reqSizeLimit, &bv, NULL );
1214                 break;
1215
1216         case LOG_EN_BIND:
1217                 bv.bv_val = timebuf;
1218                 bv.bv_len = sprintf( bv.bv_val, "%d", op->o_protocol );
1219                 attr_merge_one( e, ad_reqVersion, &bv, NULL );
1220                 if ( op->orb_method == LDAP_AUTH_SIMPLE ) {
1221                         attr_merge_one( e, ad_reqMethod, &simple, NULL );
1222                 } else {
1223                         bv.bv_len = STRLENOF("SASL()") + op->orb_tmp_mech.bv_len;
1224                         bv.bv_val = op->o_tmpalloc( bv.bv_len + 1, op->o_tmpmemctx );
1225                         ptr = lutil_strcopy( bv.bv_val, "SASL(" );
1226                         ptr = lutil_strcopy( ptr, op->orb_tmp_mech.bv_val );
1227                         *ptr++ = ')';
1228                         *ptr = '\0';
1229                         attr_merge_one( e, ad_reqMethod, &bv, NULL );
1230                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1231                 }
1232
1233                 break;
1234
1235         case LOG_EN_EXTENDED:
1236                 if ( op->ore_reqdata ) {
1237                         attr_merge_one( e, ad_reqData, op->ore_reqdata, NULL );
1238                 }
1239                 break;
1240
1241         case LOG_EN_UNKNOWN:
1242                 /* we don't know its parameters, don't add any */
1243                 break;
1244         }
1245
1246         op2.o_hdr = op->o_hdr;
1247         op2.o_tag = LDAP_REQ_ADD;
1248         op2.o_bd = li->li_db;
1249         op2.o_dn = li->li_db->be_rootdn;
1250         op2.o_ndn = li->li_db->be_rootndn;
1251         op2.o_req_dn = e->e_name;
1252         op2.o_req_ndn = e->e_nname;
1253         op2.ora_e = e;
1254         op2.o_callback = &nullsc;
1255
1256         if (( lo->mask & LOG_OP_WRITES ) && !BER_BVISEMPTY( &op->o_csn )) {
1257                 slap_queue_csn( &op2, &op->o_csn );
1258         }
1259
1260         op2.o_bd->be_add( &op2, &rs2 );
1261
1262 done:
1263         if ( lo->mask & LOG_OP_WRITES )
1264                 ldap_pvt_thread_mutex_unlock( &li->li_log_mutex );
1265         if ( e ) entry_free( e );
1266         if ( old ) entry_free( old );
1267         return SLAP_CB_CONTINUE;
1268 }
1269
1270 /* Since Bind success is sent by the frontend, it won't normally enter
1271  * the overlay response callback. Add another callback to make sure it
1272  * gets here.
1273  */
1274 static int
1275 accesslog_bind_resp( Operation *op, SlapReply *rs )
1276 {
1277         BackendDB *be, db;
1278         int rc;
1279         slap_callback *sc;
1280
1281         be = op->o_bd;
1282         db = *be;
1283         op->o_bd = &db;
1284         db.bd_info = op->o_callback->sc_private;
1285         rc = accesslog_response( op, rs );
1286         op->o_bd = be;
1287         sc = op->o_callback;
1288         op->o_callback = sc->sc_next;
1289         op->o_tmpfree( sc, op->o_tmpmemctx );
1290         return rc;
1291 }
1292
1293 static int
1294 accesslog_op_bind( Operation *op, SlapReply *rs )
1295 {
1296         slap_callback *sc;
1297
1298         sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1299         sc->sc_response = accesslog_bind_resp;
1300         sc->sc_private = op->o_bd->bd_info;
1301
1302         if ( op->o_callback ) {
1303                 sc->sc_next = op->o_callback->sc_next;
1304                 op->o_callback->sc_next = sc;
1305         } else {
1306                 op->o_callback = sc;
1307         }
1308         return SLAP_CB_CONTINUE;
1309 }
1310
1311 static int
1312 accesslog_op_mod( Operation *op, SlapReply *rs )
1313 {
1314         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1315         log_info *li = on->on_bi.bi_private;
1316
1317         if ( li->li_ops & LOG_OP_WRITES ) {
1318                 ldap_pvt_thread_rmutex_lock( &li->li_op_rmutex, op->o_tid );
1319                 if ( li->li_oldf && ( op->o_tag == LDAP_REQ_DELETE ||
1320                         op->o_tag == LDAP_REQ_MODIFY ||
1321                         ( op->o_tag == LDAP_REQ_MODRDN && li->li_oldattrs ))) {
1322                         int rc;
1323                         Entry *e;
1324
1325                         op->o_bd->bd_info = on->on_info->oi_orig;
1326                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1327                         if ( e ) {
1328                                 if ( test_filter( op, e, li->li_oldf ) == LDAP_COMPARE_TRUE )
1329                                         li->li_old = entry_dup( e );
1330                                 be_entry_release_rw( op, e, 0 );
1331                         }
1332                         op->o_bd->bd_info = (BackendInfo *)on;
1333                 }
1334         }
1335         return SLAP_CB_CONTINUE;
1336 }
1337
1338 /* unbinds are broadcast to all backends; we only log it if this
1339  * backend was used for the original bind.
1340  */
1341 static int
1342 accesslog_unbind( Operation *op, SlapReply *rs )
1343 {
1344         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1345         if ( op->o_conn->c_authz_backend == on->on_info->oi_origdb ) {
1346                 log_info *li = on->on_bi.bi_private;
1347                 Operation op2 = {0};
1348                 void *cids[SLAP_MAX_CIDS];
1349                 SlapReply rs2 = {REP_RESULT};
1350                 Entry *e;
1351
1352                 if ( !( li->li_ops & LOG_OP_UNBIND ))
1353                         return SLAP_CB_CONTINUE;
1354
1355                 e = accesslog_entry( op, LOG_EN_UNBIND, &op2 );
1356                 op2.o_hdr = op->o_hdr;
1357                 op2.o_tag = LDAP_REQ_ADD;
1358                 op2.o_bd = li->li_db;
1359                 op2.o_dn = li->li_db->be_rootdn;
1360                 op2.o_ndn = li->li_db->be_rootndn;
1361                 op2.o_req_dn = e->e_name;
1362                 op2.o_req_ndn = e->e_nname;
1363                 op2.ora_e = e;
1364                 op2.o_callback = &nullsc;
1365                 op2.o_controls = cids;
1366                 memset(cids, 0, sizeof( cids ));
1367
1368                 op2.o_bd->be_add( &op2, &rs2 );
1369                 entry_free( e );
1370         }
1371         return SLAP_CB_CONTINUE;
1372 }
1373
1374 static int
1375 accesslog_abandon( Operation *op, SlapReply *rs )
1376 {
1377         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1378         log_info *li = on->on_bi.bi_private;
1379         Operation op2 = {0};
1380         void *cids[SLAP_MAX_CIDS];
1381         SlapReply rs2 = {REP_RESULT};
1382         Entry *e;
1383         char buf[64];
1384         struct berval bv;
1385
1386         if ( !op->o_time || !( li->li_ops & LOG_OP_ABANDON ))
1387                 return SLAP_CB_CONTINUE;
1388
1389         e = accesslog_entry( op, LOG_EN_ABANDON, &op2 );
1390         bv.bv_val = buf;
1391         bv.bv_len = sprintf( buf, "%d", op->orn_msgid );
1392         attr_merge_one( e, ad_reqId, &bv, NULL );
1393
1394         op2.o_hdr = op->o_hdr;
1395         op2.o_tag = LDAP_REQ_ADD;
1396         op2.o_bd = li->li_db;
1397         op2.o_dn = li->li_db->be_rootdn;
1398         op2.o_ndn = li->li_db->be_rootndn;
1399         op2.o_req_dn = e->e_name;
1400         op2.o_req_ndn = e->e_nname;
1401         op2.ora_e = e;
1402         op2.o_callback = &nullsc;
1403         op2.o_controls = cids;
1404         memset(cids, 0, sizeof( cids ));
1405
1406         op2.o_bd->be_add( &op2, &rs2 );
1407         entry_free( e );
1408
1409         return SLAP_CB_CONTINUE;
1410 }
1411
1412 static slap_overinst accesslog;
1413
1414 static int
1415 accesslog_db_init(
1416         BackendDB *be
1417 )
1418 {
1419         slap_overinst *on = (slap_overinst *)be->bd_info;
1420         log_info *li = ch_calloc(1, sizeof(log_info));
1421
1422         on->on_bi.bi_private = li;
1423         ldap_pvt_thread_rmutex_init( &li->li_op_rmutex );
1424         ldap_pvt_thread_mutex_init( &li->li_log_mutex );
1425         return 0;
1426 }
1427
1428 static int
1429 accesslog_db_destroy(
1430         BackendDB *be
1431 )
1432 {
1433         slap_overinst *on = (slap_overinst *)be->bd_info;
1434         log_info *li = on->on_bi.bi_private;
1435         log_attr *la;
1436
1437         if ( li->li_oldf )
1438                 filter_free( li->li_oldf );
1439         for ( la=li->li_oldattrs; la; la=li->li_oldattrs ) {
1440                 li->li_oldattrs = la->next;
1441                 ch_free( la );
1442         }
1443         ldap_pvt_thread_mutex_destroy( &li->li_log_mutex );
1444         ldap_pvt_thread_rmutex_destroy( &li->li_op_rmutex );
1445         free( li );
1446         return LDAP_SUCCESS;
1447 }
1448
1449 static int
1450 accesslog_db_open(
1451         BackendDB *be
1452 )
1453 {
1454         slap_overinst *on = (slap_overinst *)be->bd_info;
1455         log_info *li = on->on_bi.bi_private;
1456
1457         Connection conn;
1458         OperationBuffer opbuf;
1459         Operation *op = (Operation *) &opbuf;
1460         Entry *e;
1461         int rc;
1462         void *thrctx;
1463
1464         if ( li->li_db == NULL ) {
1465                 Debug( LDAP_DEBUG_ANY,
1466                         "accesslog: \"logdb <suffix>\" must be specified.\n",
1467                         0, 0, 0 );
1468                 return 1;
1469         }
1470
1471         if ( slapMode & SLAP_TOOL_MODE )
1472                 return 0;
1473
1474         thrctx = ldap_pvt_thread_pool_context();
1475         connection_fake_init( &conn, op, thrctx );
1476         op->o_bd = li->li_db;
1477         op->o_dn = li->li_db->be_rootdn;
1478         op->o_ndn = li->li_db->be_rootndn;
1479
1480         rc = be_entry_get_rw( op, li->li_db->be_nsuffix, NULL, NULL, 0, &e );
1481
1482         if ( e ) {
1483                 be_entry_release_rw( op, e, 0 );
1484
1485         } else {
1486                 SlapReply rs = {REP_RESULT};
1487                 struct berval rdn, nrdn, attr;
1488                 char *ptr;
1489                 AttributeDescription *ad = NULL;
1490                 const char *text = NULL;
1491                 Entry *e_ctx;
1492
1493                 e = entry_alloc();
1494                 e->e_name = *li->li_db->be_suffix;
1495                 e->e_nname = *li->li_db->be_nsuffix;
1496
1497                 attr_merge_one( e, slap_schema.si_ad_objectClass,
1498                         &log_container->soc_cname, NULL );
1499
1500                 dnRdn( &e->e_name, &rdn );
1501                 dnRdn( &e->e_nname, &nrdn );
1502                 ptr = ber_bvchr( &rdn, '=' );
1503
1504                 assert( ptr != NULL );
1505
1506                 attr.bv_val = rdn.bv_val;
1507                 attr.bv_len = ptr - rdn.bv_val;
1508
1509                 slap_bv2ad( &attr, &ad, &text );
1510
1511                 rdn.bv_val = ptr+1;
1512                 rdn.bv_len -= attr.bv_len + 1;
1513                 ptr = ber_bvchr( &nrdn, '=' );
1514                 nrdn.bv_len -= ptr - nrdn.bv_val + 1;
1515                 nrdn.bv_val = ptr+1;
1516                 attr_merge_one( e, ad, &rdn, &nrdn );
1517
1518                 /* Get contextCSN from main DB */
1519                 op->o_bd = be;
1520                 op->o_bd->bd_info = on->on_info->oi_orig;
1521                 rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
1522                         slap_schema.si_ad_contextCSN, 0, &e_ctx );
1523
1524                 if ( e_ctx ) {
1525                         Attribute *a;
1526
1527                         a = attr_find( e_ctx->e_attrs, slap_schema.si_ad_contextCSN );
1528                         if ( a ) {
1529                                 attr_merge( e, slap_schema.si_ad_entryCSN, a->a_vals, NULL );
1530                                 attr_merge( e, a->a_desc, a->a_vals, NULL );
1531                         }
1532                         be_entry_release_rw( op, e_ctx, 0 );
1533                 }
1534                 op->o_bd->bd_info = (BackendInfo *)on;
1535                 op->o_bd = li->li_db;
1536
1537                 op->ora_e = e;
1538                 op->o_req_dn = e->e_name;
1539                 op->o_req_ndn = e->e_nname;
1540                 op->o_callback = &nullsc;
1541                 SLAP_DBFLAGS( op->o_bd ) |= SLAP_DBFLAG_NOLASTMOD;
1542                 rc = op->o_bd->be_add( op, &rs );
1543                 SLAP_DBFLAGS( op->o_bd ) ^= SLAP_DBFLAG_NOLASTMOD;
1544                 BER_BVZERO( &e->e_name );
1545                 BER_BVZERO( &e->e_nname );
1546                 entry_free( e );
1547         }
1548         ldap_pvt_thread_pool_context_reset( thrctx );
1549         return rc;
1550 }
1551
1552 int accesslog_initialize()
1553 {
1554         int i, rc;
1555
1556         accesslog.on_bi.bi_type = "accesslog";
1557         accesslog.on_bi.bi_db_init = accesslog_db_init;
1558         accesslog.on_bi.bi_db_destroy = accesslog_db_destroy;
1559         accesslog.on_bi.bi_db_open = accesslog_db_open;
1560
1561         accesslog.on_bi.bi_op_add = accesslog_op_mod;
1562         accesslog.on_bi.bi_op_bind = accesslog_op_bind;
1563         accesslog.on_bi.bi_op_delete = accesslog_op_mod;
1564         accesslog.on_bi.bi_op_modify = accesslog_op_mod;
1565         accesslog.on_bi.bi_op_modrdn = accesslog_op_mod;
1566         accesslog.on_bi.bi_op_unbind = accesslog_unbind;
1567         accesslog.on_bi.bi_op_abandon = accesslog_abandon;
1568         accesslog.on_response = accesslog_response;
1569
1570         accesslog.on_bi.bi_cf_ocs = log_cfocs;
1571
1572         nullsc.sc_response = slap_null_cb;
1573
1574         rc = config_register_schema( log_cfats, log_cfocs );
1575         if ( rc ) return rc;
1576
1577         /* log schema integration */
1578         for ( i=0; lattrs[i].at; i++ ) {
1579                 int code;
1580
1581                 code = register_at( lattrs[i].at, lattrs[i].ad, 0 );
1582                 if ( code ) {
1583                         Debug( LDAP_DEBUG_ANY,
1584                                 "accesslog_init: register_at failed\n", 0, 0, 0 );
1585                         return -1;
1586                 }
1587         }
1588         for ( i=0; locs[i].ot; i++ ) {
1589                 int code;
1590
1591                 code = register_oc( locs[i].ot, locs[i].oc, 0 );
1592                 if ( code ) {
1593                         Debug( LDAP_DEBUG_ANY,
1594                                 "accesslog_init: register_oc failed\n", 0, 0, 0 );
1595                         return -1;
1596                 }
1597         }
1598
1599         return overlay_register(&accesslog);
1600 }
1601
1602 #if SLAPD_OVER_ACCESSLOG == SLAPD_MOD_DYNAMIC
1603 int
1604 init_module( int argc, char *argv[] )
1605 {
1606         return accesslog_initialize();
1607 }
1608 #endif
1609
1610 #endif /* SLAPD_OVER_ACCESSLOG */