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