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