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