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