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