]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/accesslog.c
Add logoldattr keyword for attributes that should always have their old
[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 )", &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 ( pd->used >= pd->slots ) {
508                 pd->slots += PURGE_INCREMENT;
509                 pd->dn = ch_realloc( pd->dn, pd->slots * sizeof( struct berval ));
510                 pd->ndn = ch_realloc( pd->ndn, pd->slots * sizeof( struct berval ));
511         }
512         ber_dupbv( &pd->dn[pd->used], &rs->sr_entry->e_name );
513         ber_dupbv( &pd->ndn[pd->used], &rs->sr_entry->e_nname );
514         pd->used++;
515         return 0;
516 }
517
518 /* Periodically search for old entries in the log database and delete them */
519 static void *
520 accesslog_purge( void *ctx, void *arg )
521 {
522         struct re_s *rtask = arg;
523         struct log_info *li = rtask->arg;
524
525         Connection conn = {0};
526         OperationBuffer opbuf;
527         Operation *op = (Operation *) &opbuf;
528         SlapReply rs = {REP_RESULT};
529         slap_callback cb = { NULL, log_old_lookup, NULL, NULL };
530         Filter f;
531         AttributeAssertion ava = {0};
532         purge_data pd = {0};
533         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE];
534         time_t old = slap_get_time();
535
536         connection_fake_init( &conn, op, ctx );
537
538         f.f_choice = LDAP_FILTER_LE;
539         f.f_ava = &ava;
540         f.f_next = NULL;
541
542         ava.aa_desc = ad_reqStart;
543         ava.aa_value.bv_val = timebuf;
544         ava.aa_value.bv_len = sizeof(timebuf);
545
546         old -= li->li_age;
547         slap_timestamp( &old, &ava.aa_value );
548
549         op->o_tag = LDAP_REQ_SEARCH;
550         op->o_bd = li->li_db;
551         op->o_dn = li->li_db->be_rootdn;
552         op->o_ndn = li->li_db->be_rootndn;
553         op->o_req_dn = li->li_db->be_suffix[0];
554         op->o_req_ndn = li->li_db->be_nsuffix[0];
555         op->o_callback = &cb;
556         op->ors_scope = LDAP_SCOPE_ONELEVEL;
557         op->ors_deref = LDAP_DEREF_NEVER;
558         op->ors_tlimit = SLAP_NO_LIMIT;
559         op->ors_slimit = SLAP_NO_LIMIT;
560         op->ors_filter = &f;
561         filter2bv_x( op, &f, &op->ors_filterstr );
562         op->ors_attrs = slap_anlist_no_attrs;
563         op->ors_attrsonly = 1;
564         
565         cb.sc_private = &pd;
566
567         op->o_bd->be_search( op, &rs );
568         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
569
570         if ( pd.used ) {
571                 int i;
572
573                 op->o_tag = LDAP_REQ_DELETE;
574                 op->o_callback = &nullsc;
575
576                 for (i=0; i<pd.used; i++) {
577                         op->o_req_dn = pd.dn[i];
578                         op->o_req_ndn = pd.ndn[i];
579                         op->o_bd->be_delete( op, &rs );
580                         ch_free( pd.ndn[i].bv_val );
581                         ch_free( pd.dn[i].bv_val );
582                 }
583                 ch_free( pd.ndn );
584                 ch_free( pd.dn );
585         }
586
587         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
588         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
589         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
590
591         return NULL;
592 }
593
594 static int
595 log_cf_gen(ConfigArgs *c)
596 {
597         slap_overinst *on = (slap_overinst *)c->bi;
598         struct log_info *li = on->on_bi.bi_private;
599         int rc = 0;
600         slap_mask_t tmask = 0;
601         char agebuf[2*STRLENOF("ddddd+hh:mm:ss  ")];
602         struct berval agebv, cyclebv;
603
604         switch( c->op ) {
605         case SLAP_CONFIG_EMIT:
606                 switch( c->type ) {
607                 case LOG_DB:
608                         value_add( &c->rvalue_vals, li->li_db->be_suffix );
609                         value_add( &c->rvalue_nvals, li->li_db->be_nsuffix );
610                         break;
611                 case LOG_OPS:
612                         rc = mask_to_verbs( logops, li->li_ops, &c->rvalue_vals );
613                         break;
614                 case LOG_PURGE:
615                         agebv.bv_val = agebuf;
616                         log_age_unparse( li->li_age, &agebv );
617                         agebv.bv_val[agebv.bv_len] = ' ';
618                         agebv.bv_len++;
619                         cyclebv.bv_val = agebv.bv_val + agebv.bv_len;
620                         log_age_unparse( li->li_cycle, &cyclebv );
621                         agebv.bv_len += cyclebv.bv_len;
622                         value_add_one( &c->rvalue_vals, &agebv );
623                         break;
624                 case LOG_SUCCESS:
625                         if ( li->li_success )
626                                 c->value_int = li->li_success;
627                         else
628                                 rc = 1;
629                         break;
630                 case LOG_OLD:
631                         if ( li->li_oldf ) {
632                                 filter2bv( li->li_oldf, &agebv );
633                                 value_add_one( &c->rvalue_vals, &agebv );
634                         }
635                         else
636                                 rc = 1;
637                         break;
638                 case LOG_OLDATTR:
639                         if ( li->li_oldattrs ) {
640                                 log_attr *la;
641
642                                 for ( la = li->li_oldattrs; la; la=la->next )
643                                         value_add_one( &c->rvalue_vals, &la->attr->ad_cname );
644                         }
645                         else
646                                 rc = 1;
647                         break;
648                 }
649                 break;
650         case LDAP_MOD_DELETE:
651                 switch( c->type ) {
652                 case LOG_DB:
653                         /* noop. this should always be a valid backend. */
654                         break;
655                 case LOG_OPS:
656                         if ( c->valx < 0 ) {
657                                 li->li_ops = 0;
658                         } else {
659                                 rc = verbs_to_mask( 1, &c->line, logops, &tmask );
660                                 if ( rc == 0 )
661                                         li->li_ops &= ~tmask;
662                         }
663                         break;
664                 case LOG_PURGE:
665                         if ( li->li_task ) {
666                                 struct re_s *re = li->li_task;
667                                 li->li_task = NULL;
668                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
669                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
670                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
671                         }
672                         li->li_age = 0;
673                         li->li_cycle = 0;
674                         break;
675                 case LOG_SUCCESS:
676                         li->li_success = 0;
677                         break;
678                 case LOG_OLD:
679                         if ( li->li_oldf ) {
680                                 filter_free( li->li_oldf );
681                                 li->li_oldf = NULL;
682                         }
683                         break;
684                 case LOG_OLDATTR:
685                         if ( c->valx < 0 ) {
686                                 log_attr *la, *ln;
687
688                                 for ( la = li->li_oldattrs; la; la = ln ) {
689                                         ln = la->next;
690                                         ch_free( la );
691                                 }
692                         } else {
693                                 log_attr *la, **lp;
694                                 int i;
695
696                                 for ( lp = &li->li_oldattrs, i=0; i < c->valx; i++ ) {
697                                         la = *lp;
698                                         lp = &la->next;
699                                 }
700                                 *lp = la->next;
701                                 ch_free( la );
702                         }
703                         break;
704                 }
705                 break;
706         default:
707                 switch( c->type ) {
708                 case LOG_DB:
709                         li->li_db = select_backend( &c->value_ndn, 0, 0 );
710                         if ( !li->li_db ) {
711                                 sprintf( c->msg, "<%s> no matching backend found for suffix",
712                                         c->argv[0] );
713                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
714                                         c->log, c->msg, c->value_dn.bv_val );
715                                 rc = 1;
716                         }
717                         ch_free( c->value_dn.bv_val );
718                         ch_free( c->value_ndn.bv_val );
719                         break;
720                 case LOG_OPS:
721                         rc = verbs_to_mask( c->argc, c->argv, logops, &tmask );
722                         if ( rc == 0 )
723                                 li->li_ops |= tmask;
724                         break;
725                 case LOG_PURGE:
726                         li->li_age = log_age_parse( c->argv[1] );
727                         if ( li->li_age == -1 ) {
728                                 rc = 1;
729                         } else {
730                                 li->li_cycle = log_age_parse( c->argv[2] );
731                                 if ( li->li_cycle == -1 ) {
732                                         rc = 1;
733                                 } else if ( slapMode & SLAP_SERVER_MODE ) {
734                                         struct re_s *re = li->li_task;
735                                         if ( re )
736                                                 re->interval.tv_sec = li->li_cycle;
737                                         else
738                                                 li->li_task = ldap_pvt_runqueue_insert( &slapd_rq,
739                                                         li->li_cycle, accesslog_purge, li,
740                                                         "accesslog_purge", li->li_db ?
741                                                                 li->li_db->be_suffix[0].bv_val :
742                                                                 c->be->be_suffix[0].bv_val );
743                                 }
744                         }
745                         break;
746                 case LOG_SUCCESS:
747                         li->li_success = c->value_int;
748                         break;
749                 case LOG_OLD:
750                         li->li_oldf = str2filter( c->argv[1] );
751                         if ( !li->li_oldf ) {
752                                 sprintf( c->msg, "bad filter!" );
753                                 rc = 1;
754                         }
755                         break;
756                 case LOG_OLDATTR: {
757                         int i;
758                         AttributeDescription *ad;
759                         const char *text;
760
761                         for ( i=1; i< c->argc; i++ ) {
762                                 ad = NULL;
763                                 if ( slap_str2ad( c->argv[i], &ad, &text ) == LDAP_SUCCESS ) {
764                                         log_attr *la = ch_malloc( sizeof( log_attr ));
765                                         la->attr = ad;
766                                         la->next = li->li_oldattrs;
767                                         li->li_oldattrs = la;
768                                 } else {
769                                         sprintf( c->msg, "%s: %s", c->argv[i], text );
770                                         rc = ARG_BAD_CONF;
771                                         break;
772                                 }
773                         }
774                         }
775                         break;
776                 }
777                 break;
778         }
779         return rc;
780 }
781
782 static Entry *accesslog_entry( Operation *op, int logop,
783         Operation *op2 ) {
784         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
785         log_info *li = on->on_bi.bi_private;
786
787         char rdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
788         char nrdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
789
790         struct berval rdn, nrdn, timestamp, ntimestamp, bv;
791         slap_verbmasks *lo = logops+logop+EN_OFFSET;
792
793         Entry *e = ch_calloc( 1, sizeof(Entry) );
794
795         strcpy( rdnbuf, RDNEQ );
796         rdn.bv_val = rdnbuf;
797         strcpy( nrdnbuf, RDNEQ );
798         nrdn.bv_val = nrdnbuf;
799
800         timestamp.bv_val = rdnbuf+STRLENOF(RDNEQ);
801         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
802         slap_timestamp( &op->o_time, &timestamp );
803         sprintf( timestamp.bv_val + timestamp.bv_len-1, ".%06dZ", op->o_tincr );
804         timestamp.bv_len += 7;
805
806         rdn.bv_len = STRLENOF(RDNEQ)+timestamp.bv_len;
807         ad_reqStart->ad_type->sat_equality->smr_normalize(
808                 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, ad_reqStart->ad_type->sat_syntax,
809                 ad_reqStart->ad_type->sat_equality, &timestamp, &ntimestamp,
810                 op->o_tmpmemctx );
811
812         strcpy( nrdn.bv_val + STRLENOF(RDNEQ), ntimestamp.bv_val );
813         nrdn.bv_len = STRLENOF(RDNEQ)+ntimestamp.bv_len;
814         build_new_dn( &e->e_name, li->li_db->be_suffix, &rdn, NULL );
815         build_new_dn( &e->e_nname, li->li_db->be_nsuffix, &nrdn, NULL );
816
817         attr_merge_one( e, slap_schema.si_ad_objectClass,
818                 &log_ocs[logop]->soc_cname, NULL );
819         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
820                 &log_ocs[logop]->soc_cname, NULL );
821         attr_merge_one( e, ad_reqStart, &timestamp, &ntimestamp );
822         op->o_tmpfree( ntimestamp.bv_val, op->o_tmpmemctx );
823
824         slap_op_time( &op2->o_time, &op2->o_tincr );
825
826         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
827         slap_timestamp( &op2->o_time, &timestamp );
828         sprintf( timestamp.bv_val + timestamp.bv_len-1, ".%06dZ", op2->o_tincr );
829         timestamp.bv_len += 7;
830
831         attr_merge_normalize_one( e, ad_reqEnd, &timestamp, op->o_tmpmemctx );
832
833         /* Exops have OID appended */
834         if ( logop == LOG_EN_EXTENDED ) {
835                 bv.bv_len = lo->word.bv_len + op->ore_reqoid.bv_len + 2;
836                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
837                 AC_MEMCPY( bv.bv_val, lo->word.bv_val, lo->word.bv_len );
838                 bv.bv_val[lo->word.bv_len] = '{';
839                 AC_MEMCPY( bv.bv_val+lo->word.bv_len+1, op->ore_reqoid.bv_val,
840                         op->ore_reqoid.bv_len );
841                 bv.bv_val[bv.bv_len-1] = '}';
842                 bv.bv_val[bv.bv_len] = '\0';
843                 attr_merge_one( e, ad_reqType, &bv, NULL );
844         } else {
845                 attr_merge_one( e, ad_reqType, &lo->word, NULL );
846         }
847
848         rdn.bv_len = sprintf( rdn.bv_val, "%lu", op->o_connid );
849         attr_merge_one( e, ad_reqSession, &rdn, NULL );
850
851         if ( BER_BVISNULL( &op->o_dn )) 
852                 attr_merge_one( e, ad_reqAuthzID, (struct berval *)&slap_empty_bv,
853                         (struct berval *)&slap_empty_bv );
854         else
855                 attr_merge_one( e, ad_reqAuthzID, &op->o_dn, &op->o_ndn );
856
857         /* FIXME: need to add reqControls and reqRespControls */
858
859         return e;
860 }
861
862 static struct berval scopes[] = {
863         BER_BVC("base"),
864         BER_BVC("one"),
865         BER_BVC("sub"),
866         BER_BVC("subord")
867 };
868
869 static struct berval derefs[] = {
870         BER_BVC("never"),
871         BER_BVC("searching"),
872         BER_BVC("finding"),
873         BER_BVC("always")
874 };
875
876 static struct berval simple = BER_BVC("SIMPLE");
877
878 static void accesslog_val2val(AttributeDescription *ad, struct berval *val,
879         char c_op, struct berval *dst) {
880         char *ptr;
881
882         dst->bv_len = ad->ad_cname.bv_len + val->bv_len + 2;
883         if ( c_op ) dst->bv_len++;
884
885         dst->bv_val = ch_malloc( dst->bv_len+1 );
886
887         ptr = lutil_strcopy( dst->bv_val, ad->ad_cname.bv_val );
888         *ptr++ = ':';
889         if ( c_op )
890                 *ptr++ = c_op;
891         *ptr++ = ' ';
892         AC_MEMCPY( ptr, val->bv_val, val->bv_len );
893         dst->bv_val[dst->bv_len] = '\0';
894 }
895
896 static int accesslog_response(Operation *op, SlapReply *rs) {
897         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
898         log_info *li = on->on_bi.bi_private;
899         Attribute *a, *last_attr;
900         Modifications *m;
901         struct berval *b;
902         int i;
903         int logop;
904         slap_verbmasks *lo;
905         Entry *e = NULL, *old = NULL;
906         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE+8];
907         struct berval bv;
908         char *ptr;
909         BerVarray vals;
910         Operation op2 = {0};
911         SlapReply rs2 = {REP_RESULT};
912
913         if ( rs->sr_type != REP_RESULT && rs->sr_type != REP_EXTENDED )
914                 return SLAP_CB_CONTINUE;
915
916         switch ( op->o_tag ) {
917         case LDAP_REQ_ADD:              logop = LOG_EN_ADD; break;
918         case LDAP_REQ_DELETE:   logop = LOG_EN_DELETE; break;
919         case LDAP_REQ_MODIFY:   logop = LOG_EN_MODIFY; break;
920         case LDAP_REQ_MODRDN:   logop = LOG_EN_MODRDN; break;
921         case LDAP_REQ_COMPARE:  logop = LOG_EN_COMPARE; break;
922         case LDAP_REQ_SEARCH:   logop = LOG_EN_SEARCH; break;
923         case LDAP_REQ_BIND:             logop = LOG_EN_BIND; break;
924         case LDAP_REQ_EXTENDED: logop = LOG_EN_EXTENDED; break;
925         default:        /* unknown operation type */
926                 logop = LOG_EN_UNKNOWN; break;
927         }       /* Unbind and Abandon never reach here */
928
929         lo = logops+logop+EN_OFFSET;
930         if ( !( li->li_ops & lo->mask ))
931                 return SLAP_CB_CONTINUE;
932
933         if ( lo->mask & LOG_OP_WRITES ) {
934                 ldap_pvt_thread_mutex_lock( &li->li_log_mutex );
935                 old = li->li_old;
936                 li->li_old = NULL;
937                 ldap_pvt_thread_rmutex_unlock( &li->li_op_rmutex );
938         }
939
940         if ( li->li_success && rs->sr_err != LDAP_SUCCESS )
941                 goto done;
942
943         e = accesslog_entry( op, logop, &op2 );
944
945         attr_merge_one( e, ad_reqDN, &op->o_req_dn, &op->o_req_ndn );
946
947         if ( rs->sr_text ) {
948                 ber_str2bv( rs->sr_text, 0, 0, &bv );
949                 attr_merge_one( e, ad_reqMessage, &bv, NULL );
950         }
951         bv.bv_len = sprintf( timebuf, "%d", rs->sr_err );
952         bv.bv_val = timebuf;
953
954         attr_merge_one( e, ad_reqResult, &bv, NULL );
955
956         last_attr = attr_find( e->e_attrs, ad_reqResult );
957
958         switch( logop ) {
959         case LOG_EN_ADD:
960         case LOG_EN_DELETE: {
961                 char c_op;
962                 Entry *e2;
963
964                 if ( logop == LOG_EN_ADD ) {
965                         e2 = op->ora_e;
966                         c_op = '+';
967                 } else {
968                         if ( !old )
969                                 break;
970                         e2 = old;
971                         c_op = 0;
972                 }
973                 /* count all the vals */
974                 i = 0;
975                 for ( a=e2->e_attrs; a; a=a->a_next ) {
976                         if ( a->a_vals ) {
977                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++) {
978                                         i++;
979                                 }
980                         }
981                 }
982                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
983                 i = 0;
984                 for ( a=e2->e_attrs; a; a=a->a_next ) {
985                         if ( a->a_vals ) {
986                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
987                                         accesslog_val2val( a->a_desc, b, c_op, &vals[i] );
988                                 }
989                         }
990                 }
991                 vals[i].bv_val = NULL;
992                 vals[i].bv_len = 0;
993                 a = attr_alloc( logop == LOG_EN_ADD ? ad_reqMod : ad_reqOld );
994                 a->a_vals = vals;
995                 a->a_nvals = vals;
996                 last_attr->a_next = a;
997                 break;
998         }
999
1000         case LOG_EN_MODIFY:
1001                 /* count all the mods */
1002                 i = 0;
1003                 for ( m=op->orm_modlist; m; m=m->sml_next ) {
1004                         if ( m->sml_values ) {
1005                                 for (b=m->sml_values; !BER_BVISNULL( b ); b++) {
1006                                         i++;
1007                                 }
1008                         } else if ( m->sml_op == LDAP_MOD_DELETE ) {
1009                                 i++;
1010                         }
1011                 }
1012                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1013                 i = 0;
1014
1015                 /* init flags on old entry */
1016                 if ( old ) {
1017                         for ( a=old->e_attrs; a; a=a->a_next ) {
1018                                 log_attr *la;
1019                                 a->a_flags = 0;
1020
1021                                 /* look for attrs that are always logged */
1022                                 for ( la=li->li_oldattrs; la; la=la->next )
1023                                         if ( a->a_desc == la->attr )
1024                                                 a->a_flags = 1;
1025                         }
1026                 }
1027
1028                 for ( m=op->orm_modlist; m; m=m->sml_next ) {
1029                         /* Mark this attribute as modified */
1030                         if ( old ) {
1031                                 a = attr_find( old->e_attrs, m->sml_desc );
1032                                 if ( a )
1033                                         a->a_flags = 1;
1034                         }
1035                         if ( m->sml_values ) {
1036                                 for (b=m->sml_values; !BER_BVISNULL( b ); b++,i++) {
1037                                         char c_op;
1038
1039                                         switch( m->sml_op ) {
1040                                         case LDAP_MOD_ADD: c_op = '+'; break;
1041                                         case LDAP_MOD_DELETE:   c_op = '-'; break;
1042                                         case LDAP_MOD_REPLACE:  c_op = '='; break;
1043                                         case LDAP_MOD_INCREMENT:        c_op = '#'; break;
1044
1045                                         /* unknown op. there shouldn't be any of these. we
1046                                          * don't know what to do with it, but we shouldn't just
1047                                          * ignore it.
1048                                          */
1049                                         default: c_op = '?'; break;
1050                                         }
1051                                         accesslog_val2val( m->sml_desc, b, c_op, &vals[i] );
1052                                 }
1053                         } else if ( m->sml_op == LDAP_MOD_DELETE ) {
1054                                 vals[i].bv_len = m->sml_desc->ad_cname.bv_len + 2;
1055                                 vals[i].bv_val = ch_malloc( vals[i].bv_len+1 );
1056                                 ptr = lutil_strcopy( vals[i].bv_val,
1057                                         m->sml_desc->ad_cname.bv_val );
1058                                 *ptr++ = ':';
1059                                 *ptr++ = '-';
1060                                 *ptr = '\0';
1061                                 i++;
1062                         }
1063                 }
1064                 vals[i].bv_val = NULL;
1065                 vals[i].bv_len = 0;
1066                 a = attr_alloc( ad_reqMod );
1067                 a->a_vals = vals;
1068                 a->a_nvals = vals;
1069                 last_attr->a_next = a;
1070
1071                 if ( old ) {
1072                         last_attr = a;
1073                         /* count all the vals */
1074                         i = 0;
1075                         for ( a=old->e_attrs; a; a=a->a_next ) {
1076                                 if ( a->a_vals && a->a_flags ) {
1077                                         for (b=a->a_vals; !BER_BVISNULL( b ); b++) {
1078                                         i++;
1079                                         }
1080                                 }
1081                         }
1082                         vals = ch_malloc( (i+1) * sizeof( struct berval ));
1083                         i = 0;
1084                         for ( a=old->e_attrs; a; a=a->a_next ) {
1085                                 if ( a->a_vals && a->a_flags ) {
1086                                         for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1087                                                 accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1088                                         }
1089                                 }
1090                         }
1091                         vals[i].bv_val = NULL;
1092                         vals[i].bv_len = 0;
1093                         a = attr_alloc( ad_reqOld );
1094                         a->a_vals = vals;
1095                         a->a_nvals = vals;
1096                         last_attr->a_next = a;
1097                 }
1098                 break;
1099
1100         case LOG_EN_MODRDN:
1101                 attr_merge_one( e, ad_reqNewRDN, &op->orr_newrdn, &op->orr_nnewrdn );
1102                 attr_merge_one( e, ad_reqDeleteOldRDN, op->orr_deleteoldrdn ?
1103                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1104                         NULL );
1105                 if ( op->orr_newSup ) {
1106                         attr_merge_one( e, ad_reqNewSuperior, op->orr_newSup, op->orr_nnewSup );
1107                 }
1108                 break;
1109
1110         case LOG_EN_COMPARE:
1111                 bv.bv_len = op->orc_ava->aa_desc->ad_cname.bv_len + 1 +
1112                         op->orc_ava->aa_value.bv_len;
1113                 bv.bv_val = op->o_tmpalloc( bv.bv_len+1, op->o_tmpmemctx );
1114                 ptr = lutil_strcopy( bv.bv_val, op->orc_ava->aa_desc->ad_cname.bv_val );
1115                 *ptr++ = '=';
1116                 AC_MEMCPY( ptr, op->orc_ava->aa_value.bv_val, op->orc_ava->aa_value.bv_len );
1117                 bv.bv_val[bv.bv_len] = '\0';
1118                 attr_merge_one( e, ad_reqAssertion, &bv, NULL );
1119                 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1120                 break;
1121
1122         case LOG_EN_SEARCH:
1123                 attr_merge_one( e, ad_reqScope, &scopes[op->ors_scope], NULL );
1124                 attr_merge_one( e, ad_reqDerefAliases, &derefs[op->ors_deref], NULL );
1125                 attr_merge_one( e, ad_reqAttrsOnly, op->ors_attrsonly ?
1126                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1127                         NULL );
1128                 if ( !BER_BVISEMPTY( &op->ors_filterstr ))
1129                         attr_merge_one( e, ad_reqFilter, &op->ors_filterstr, NULL );
1130                 if ( op->ors_attrs ) {
1131                         /* count them */
1132                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1133                                 ;
1134                         vals = op->o_tmpalloc( (i+1) * sizeof(struct berval),
1135                                 op->o_tmpmemctx );
1136                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1137                                 vals[i] = op->ors_attrs[i].an_name;
1138                         vals[i].bv_val = NULL;
1139                         vals[i].bv_len = 0;
1140                         attr_merge( e, ad_reqAttr, vals, NULL );
1141                         op->o_tmpfree( vals, op->o_tmpmemctx );
1142                 }
1143                 bv.bv_val = timebuf;
1144                 bv.bv_len = sprintf( bv.bv_val, "%d", rs->sr_nentries );
1145                 attr_merge_one( e, ad_reqEntries, &bv, NULL );
1146
1147                 bv.bv_len = sprintf( bv.bv_val, "%d", op->ors_tlimit );
1148                 attr_merge_one( e, ad_reqTimeLimit, &bv, NULL );
1149
1150                 bv.bv_len = sprintf( bv.bv_val, "%d", op->ors_slimit );
1151                 attr_merge_one( e, ad_reqSizeLimit, &bv, NULL );
1152                 break;
1153
1154         case LOG_EN_BIND:
1155                 bv.bv_val = timebuf;
1156                 bv.bv_len = sprintf( bv.bv_val, "%d", op->o_protocol );
1157                 attr_merge_one( e, ad_reqVersion, &bv, NULL );
1158                 if ( op->orb_method == LDAP_AUTH_SIMPLE ) {
1159                         attr_merge_one( e, ad_reqMethod, &simple, NULL );
1160                 } else {
1161                         bv.bv_len = STRLENOF("SASL()") + op->orb_tmp_mech.bv_len;
1162                         bv.bv_val = op->o_tmpalloc( bv.bv_len + 1, op->o_tmpmemctx );
1163                         ptr = lutil_strcopy( bv.bv_val, "SASL(" );
1164                         ptr = lutil_strcopy( ptr, op->orb_tmp_mech.bv_val );
1165                         *ptr++ = ')';
1166                         *ptr = '\0';
1167                         attr_merge_one( e, ad_reqMethod, &bv, NULL );
1168                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1169                 }
1170
1171                 break;
1172
1173         case LOG_EN_EXTENDED:
1174                 if ( op->ore_reqdata ) {
1175                         attr_merge_one( e, ad_reqData, op->ore_reqdata, NULL );
1176                 }
1177                 break;
1178
1179         case LOG_EN_UNKNOWN:
1180                 /* we don't know its parameters, don't add any */
1181                 break;
1182         }
1183
1184         op2.o_hdr = op->o_hdr;
1185         op2.o_tag = LDAP_REQ_ADD;
1186         op2.o_bd = li->li_db;
1187         op2.o_dn = li->li_db->be_rootdn;
1188         op2.o_ndn = li->li_db->be_rootndn;
1189         op2.o_req_dn = e->e_name;
1190         op2.o_req_ndn = e->e_nname;
1191         op2.ora_e = e;
1192         op2.o_callback = &nullsc;
1193
1194         if (( lo->mask & LOG_OP_WRITES ) && !BER_BVISEMPTY( &op->o_csn )) {
1195                 slap_queue_csn( &op2, &op->o_csn );
1196         }
1197
1198         op2.o_bd->be_add( &op2, &rs2 );
1199
1200 done:
1201         if ( lo->mask & LOG_OP_WRITES )
1202                 ldap_pvt_thread_mutex_unlock( &li->li_log_mutex );
1203         if ( e ) entry_free( e );
1204         if ( old ) entry_free( old );
1205         return SLAP_CB_CONTINUE;
1206 }
1207
1208 /* Since Bind success is sent by the frontend, it won't normally enter
1209  * the overlay response callback. Add another callback to make sure it
1210  * gets here.
1211  */
1212 static int
1213 accesslog_bind_resp( Operation *op, SlapReply *rs )
1214 {
1215         BackendDB *be, db;
1216         int rc;
1217         slap_callback *sc;
1218
1219         be = op->o_bd;
1220         db = *be;
1221         op->o_bd = &db;
1222         db.bd_info = op->o_callback->sc_private;
1223         rc = accesslog_response( op, rs );
1224         op->o_bd = be;
1225         sc = op->o_callback;
1226         op->o_callback = sc->sc_next;
1227         op->o_tmpfree( sc, op->o_tmpmemctx );
1228         return rc;
1229 }
1230
1231 static int
1232 accesslog_op_bind( Operation *op, SlapReply *rs )
1233 {
1234         slap_callback *sc;
1235
1236         sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1237         sc->sc_response = accesslog_bind_resp;
1238         sc->sc_private = op->o_bd->bd_info;
1239
1240         if ( op->o_callback ) {
1241                 sc->sc_next = op->o_callback->sc_next;
1242                 op->o_callback->sc_next = sc;
1243         } else {
1244                 op->o_callback = sc;
1245         }
1246         return SLAP_CB_CONTINUE;
1247 }
1248
1249 static int
1250 accesslog_op_mod( Operation *op, SlapReply *rs )
1251 {
1252         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1253         log_info *li = on->on_bi.bi_private;
1254
1255         if ( li->li_ops & LOG_OP_WRITES ) {
1256                 ldap_pvt_thread_rmutex_lock( &li->li_op_rmutex );
1257                 if ( li->li_oldf && ( op->o_tag == LDAP_REQ_DELETE ||
1258                         op->o_tag == LDAP_REQ_MODIFY )) {
1259                         int rc;
1260                         Entry *e;
1261
1262                         op->o_bd->bd_info = on->on_info->oi_orig;
1263                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1264                         if ( e ) {
1265                                 if ( test_filter( op, e, li->li_oldf ) == LDAP_COMPARE_TRUE )
1266                                         li->li_old = entry_dup( e );
1267                                 be_entry_release_rw( op, e, 0 );
1268                         }
1269                         op->o_bd->bd_info = (BackendInfo *)on;
1270                 }
1271         }
1272         return SLAP_CB_CONTINUE;
1273 }
1274
1275 /* unbinds are broadcast to all backends; we only log it if this
1276  * backend was used for the original bind.
1277  */
1278 static int
1279 accesslog_unbind( Operation *op, SlapReply *rs )
1280 {
1281         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1282         if ( op->o_conn->c_authz_backend == on->on_info->oi_origdb ) {
1283                 log_info *li = on->on_bi.bi_private;
1284                 Operation op2 = {0};
1285                 void *cids[SLAP_MAX_CIDS];
1286                 SlapReply rs2 = {REP_RESULT};
1287                 Entry *e;
1288
1289                 if ( !( li->li_ops & LOG_OP_UNBIND ))
1290                         return SLAP_CB_CONTINUE;
1291
1292                 e = accesslog_entry( op, LOG_EN_UNBIND, &op2 );
1293                 op2.o_hdr = op->o_hdr;
1294                 op2.o_tag = LDAP_REQ_ADD;
1295                 op2.o_bd = li->li_db;
1296                 op2.o_dn = li->li_db->be_rootdn;
1297                 op2.o_ndn = li->li_db->be_rootndn;
1298                 op2.o_req_dn = e->e_name;
1299                 op2.o_req_ndn = e->e_nname;
1300                 op2.ora_e = e;
1301                 op2.o_callback = &nullsc;
1302                 op2.o_controls = cids;
1303                 memset(cids, 0, sizeof( cids ));
1304
1305                 op2.o_bd->be_add( &op2, &rs2 );
1306                 entry_free( e );
1307         }
1308         return SLAP_CB_CONTINUE;
1309 }
1310
1311 static int
1312 accesslog_abandon( 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         Operation op2 = {0};
1317         void *cids[SLAP_MAX_CIDS];
1318         SlapReply rs2 = {REP_RESULT};
1319         Entry *e;
1320         char buf[64];
1321         struct berval bv;
1322
1323         if ( !op->o_time || !( li->li_ops & LOG_OP_ABANDON ))
1324                 return SLAP_CB_CONTINUE;
1325
1326         e = accesslog_entry( op, LOG_EN_ABANDON, &op2 );
1327         bv.bv_val = buf;
1328         bv.bv_len = sprintf( buf, "%d", op->orn_msgid );
1329         attr_merge_one( e, ad_reqId, &bv, NULL );
1330
1331         op2.o_hdr = op->o_hdr;
1332         op2.o_tag = LDAP_REQ_ADD;
1333         op2.o_bd = li->li_db;
1334         op2.o_dn = li->li_db->be_rootdn;
1335         op2.o_ndn = li->li_db->be_rootndn;
1336         op2.o_req_dn = e->e_name;
1337         op2.o_req_ndn = e->e_nname;
1338         op2.ora_e = e;
1339         op2.o_callback = &nullsc;
1340         op2.o_controls = cids;
1341         memset(cids, 0, sizeof( cids ));
1342
1343         op2.o_bd->be_add( &op2, &rs2 );
1344         entry_free( e );
1345
1346         return SLAP_CB_CONTINUE;
1347 }
1348
1349 static slap_overinst accesslog;
1350
1351 static int
1352 accesslog_db_init(
1353         BackendDB *be
1354 )
1355 {
1356         slap_overinst *on = (slap_overinst *)be->bd_info;
1357         log_info *li = ch_calloc(1, sizeof(log_info));
1358
1359         on->on_bi.bi_private = li;
1360         ldap_pvt_thread_rmutex_init( &li->li_op_rmutex );
1361         ldap_pvt_thread_mutex_init( &li->li_log_mutex );
1362         return 0;
1363 }
1364
1365 static int
1366 accesslog_db_destroy(
1367         BackendDB *be
1368 )
1369 {
1370         slap_overinst *on = (slap_overinst *)be->bd_info;
1371         log_info *li = on->on_bi.bi_private;
1372
1373         ldap_pvt_thread_mutex_destroy( &li->li_log_mutex );
1374         ldap_pvt_thread_rmutex_destroy( &li->li_op_rmutex );
1375         free( li );
1376         return LDAP_SUCCESS;
1377 }
1378
1379 static int
1380 accesslog_db_open(
1381         BackendDB *be
1382 )
1383 {
1384         slap_overinst *on = (slap_overinst *)be->bd_info;
1385         log_info *li = on->on_bi.bi_private;
1386
1387         Connection conn;
1388         OperationBuffer opbuf;
1389         Operation *op = (Operation *) &opbuf;
1390         Entry *e;
1391         int rc;
1392         void *thrctx;
1393
1394         if ( slapMode & SLAP_TOOL_MODE )
1395                 return 0;
1396
1397         thrctx = ldap_pvt_thread_pool_context();
1398         connection_fake_init( &conn, op, thrctx );
1399         op->o_bd = li->li_db;
1400         op->o_dn = li->li_db->be_rootdn;
1401         op->o_ndn = li->li_db->be_rootndn;
1402
1403         rc = be_entry_get_rw( op, li->li_db->be_nsuffix, NULL, NULL, 0, &e );
1404
1405         if ( e ) {
1406                 be_entry_release_rw( op, e, 0 );
1407         } else {
1408                 SlapReply rs = {REP_RESULT};
1409                 struct berval rdn, nrdn, attr;
1410                 char *ptr;
1411                 AttributeDescription *ad = NULL;
1412                 const char *text = NULL;
1413                 Entry *e_ctx;
1414
1415                 e = ch_calloc( 1, sizeof( Entry ));
1416                 e->e_name = *li->li_db->be_suffix;
1417                 e->e_nname = *li->li_db->be_nsuffix;
1418
1419                 attr_merge_one( e, slap_schema.si_ad_objectClass,
1420                         &log_container->soc_cname, NULL );
1421
1422                 dnRdn( &e->e_name, &rdn );
1423                 dnRdn( &e->e_nname, &nrdn );
1424                 ptr = ber_bvchr( &rdn, '=' );
1425
1426                 assert( ptr != NULL );
1427
1428                 attr.bv_val = rdn.bv_val;
1429                 attr.bv_len = ptr - rdn.bv_val;
1430
1431                 slap_bv2ad( &attr, &ad, &text );
1432
1433                 rdn.bv_val = ptr+1;
1434                 rdn.bv_len -= attr.bv_len + 1;
1435                 ptr = ber_bvchr( &nrdn, '=' );
1436                 nrdn.bv_len -= ptr - nrdn.bv_val + 1;
1437                 nrdn.bv_val = ptr+1;
1438                 attr_merge_one( e, ad, &rdn, &nrdn );
1439
1440                 /* Get contextCSN from main DB */
1441                 op->o_bd = be;
1442                 op->o_bd->bd_info = on->on_info->oi_orig;
1443                 rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
1444                         slap_schema.si_ad_contextCSN, 0, &e_ctx );
1445
1446                 if ( e_ctx ) {
1447                         Attribute *a;
1448
1449                         a = attr_find( e_ctx->e_attrs, slap_schema.si_ad_contextCSN );
1450                         if ( a ) {
1451                                 attr_merge( e, slap_schema.si_ad_entryCSN, a->a_vals, NULL );
1452                                 attr_merge( e, a->a_desc, a->a_vals, NULL );
1453                         }
1454                         be_entry_release_rw( op, e_ctx, 0 );
1455                 }
1456                 op->o_bd->bd_info = (BackendInfo *)on;
1457                 op->o_bd = li->li_db;
1458
1459                 op->ora_e = e;
1460                 op->o_req_dn = e->e_name;
1461                 op->o_req_ndn = e->e_nname;
1462                 op->o_callback = &nullsc;
1463                 SLAP_DBFLAGS( op->o_bd ) |= SLAP_DBFLAG_NOLASTMOD;
1464                 rc = op->o_bd->be_add( op, &rs );
1465                 SLAP_DBFLAGS( op->o_bd ) ^= SLAP_DBFLAG_NOLASTMOD;
1466                 attrs_free( e->e_attrs );
1467                 ch_free( e );
1468         }
1469         ldap_pvt_thread_pool_context_reset( thrctx );
1470         return rc;
1471 }
1472
1473 int accesslog_initialize()
1474 {
1475         int i, rc;
1476
1477         accesslog.on_bi.bi_type = "accesslog";
1478         accesslog.on_bi.bi_db_init = accesslog_db_init;
1479         accesslog.on_bi.bi_db_destroy = accesslog_db_destroy;
1480         accesslog.on_bi.bi_db_open = accesslog_db_open;
1481
1482         accesslog.on_bi.bi_op_add = accesslog_op_mod;
1483         accesslog.on_bi.bi_op_bind = accesslog_op_bind;
1484         accesslog.on_bi.bi_op_delete = accesslog_op_mod;
1485         accesslog.on_bi.bi_op_modify = accesslog_op_mod;
1486         accesslog.on_bi.bi_op_modrdn = accesslog_op_mod;
1487         accesslog.on_bi.bi_op_unbind = accesslog_unbind;
1488         accesslog.on_bi.bi_op_abandon = accesslog_abandon;
1489         accesslog.on_response = accesslog_response;
1490
1491         accesslog.on_bi.bi_cf_ocs = log_cfocs;
1492
1493         nullsc.sc_response = slap_null_cb;
1494
1495         rc = config_register_schema( log_cfats, log_cfocs );
1496         if ( rc ) return rc;
1497
1498         /* log schema integration */
1499         for ( i=0; lattrs[i].at; i++ ) {
1500                 LDAPAttributeType *lat;
1501                 AttributeType *at;
1502                 int code;
1503                 const char *err;
1504
1505                 lat = ldap_str2attributetype( lattrs[i].at, &code, &err,
1506                         LDAP_SCHEMA_ALLOW_ALL );
1507                 if ( !lat ) {
1508                         Debug( LDAP_DEBUG_ANY, "accesslog_init: "
1509                                 "ldap_str2attributetype failed on %d: %s, %s\n",
1510                                 i, ldap_scherr2str(code), err );
1511                         return -1;
1512                 }
1513                 code = at_add( lat, 0, &at, &err );
1514                 ldap_memfree( lat );
1515                 if ( code ) {
1516                         Debug( LDAP_DEBUG_ANY, "log_back_initialize: "
1517                                 "at_add failed on %d: %s\n",
1518                                 i, scherr2str(code), 0 );
1519                         return -1;
1520                 }
1521                 if ( slap_bv2ad( &at->sat_cname, lattrs[i].ad, &err )) {
1522                         Debug( LDAP_DEBUG_ANY, "accesslog_init: "
1523                                 "slap_bv2ad failed on %d: %s\n",
1524                                 i, err, 0 );
1525                         return -1;
1526                 }
1527         }
1528         for ( i=0; locs[i].ot; i++ ) {
1529                 LDAPObjectClass *loc;
1530                 ObjectClass *oc;
1531                 int code;
1532                 const char *err;
1533
1534                 loc = ldap_str2objectclass( locs[i].ot, &code, &err,
1535                         LDAP_SCHEMA_ALLOW_ALL );
1536                 if ( !loc ) {
1537                         Debug( LDAP_DEBUG_ANY, "accesslog_init: "
1538                                 "ldap_str2objectclass failed on %d: %s, %s\n",
1539                                 i, ldap_scherr2str(code), err );
1540                         return -1;
1541                 }
1542                 
1543                 code = oc_add( loc, 0, &oc, &err );
1544                 ldap_memfree( loc );
1545                 if ( code ) {
1546                         Debug( LDAP_DEBUG_ANY, "accesslog_init: "
1547                                 "oc_add failed on %d: %s\n",
1548                                 i, scherr2str(code), 0 );
1549                         return -1;
1550                 }
1551                 if ( locs[i].oc )
1552                         *locs[i].oc = oc;
1553         }
1554
1555         return overlay_register(&accesslog);
1556 }
1557
1558 #if SLAPD_OVER_ACCESSLOG == SLAPD_MOD_DYNAMIC
1559 int
1560 init_module( int argc, char *argv[] )
1561 {
1562         return accesslog_initialize();
1563 }
1564 #endif
1565
1566 #endif /* SLAPD_OVER_ACCESSLOG */