]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/accesslog.c
2a04e84c3978efd1ec0d28d9da05674751fefafc
[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-2007 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         struct berval li_db_suffix;
62         slap_mask_t li_ops;
63         int li_age;
64         int li_cycle;
65         struct re_s *li_task;
66         Filter *li_oldf;
67         Entry *li_old;
68         log_attr *li_oldattrs;
69         int li_success;
70         int li_unlock;
71         ldap_pvt_thread_rmutex_t li_op_rmutex;
72         ldap_pvt_thread_mutex_t li_log_mutex;
73 } log_info;
74
75 static ConfigDriver log_cf_gen;
76
77 enum {
78         LOG_DB = 1,
79         LOG_OPS,
80         LOG_PURGE,
81         LOG_SUCCESS,
82         LOG_OLD,
83         LOG_OLDATTR
84 };
85
86 static ConfigTable log_cfats[] = {
87         { "logdb", "suffix", 2, 2, 0, ARG_DN|ARG_MAGIC|LOG_DB,
88                 log_cf_gen, "( OLcfgOvAt:4.1 NAME 'olcAccessLogDB' "
89                         "DESC 'Suffix of database for log content' "
90                         "SUP distinguishedName SINGLE-VALUE )", NULL, NULL },
91         { "logops", "op|writes|reads|session|all", 2, 0, 0,
92                 ARG_MAGIC|LOG_OPS,
93                 log_cf_gen, "( OLcfgOvAt:4.2 NAME 'olcAccessLogOps' "
94                         "DESC 'Operation types to log' "
95                         "EQUALITY caseIgnoreMatch "
96                         "SYNTAX OMsDirectoryString )", NULL, NULL },
97         { "logpurge", "age> <interval", 3, 3, 0, ARG_MAGIC|LOG_PURGE,
98                 log_cf_gen, "( OLcfgOvAt:4.3 NAME 'olcAccessLogPurge' "
99                         "DESC 'Log cleanup parameters' "
100                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
101         { "logsuccess", NULL, 2, 2, 0, ARG_MAGIC|ARG_ON_OFF|LOG_SUCCESS,
102                 log_cf_gen, "( OLcfgOvAt:4.4 NAME 'olcAccessLogSuccess' "
103                         "DESC 'Log successful ops only' "
104                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
105         { "logold", "filter", 2, 2, 0, ARG_MAGIC|LOG_OLD,
106                 log_cf_gen, "( OLcfgOvAt:4.5 NAME 'olcAccessLogOld' "
107                         "DESC 'Log old values when modifying entries matching the filter' "
108                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
109         { "logoldattr", "attrs", 2, 0, 0, ARG_MAGIC|LOG_OLDATTR,
110                 log_cf_gen, "( OLcfgOvAt:4.6 NAME 'olcAccessLogOldAttr' "
111                         "DESC 'Log old values of these attributes even if unmodified' "
112                         "EQUALITY caseIgnoreMatch "
113                         "SYNTAX OMsDirectoryString )", NULL, NULL },
114         { NULL }
115 };
116
117 static ConfigOCs log_cfocs[] = {
118         { "( OLcfgOvOc:4.1 "
119                 "NAME 'olcAccessLogConfig' "
120                 "DESC 'Access log configuration' "
121                 "SUP olcOverlayConfig "
122                 "MUST olcAccessLogDB "
123                 "MAY ( olcAccessLogOps $ olcAccessLogPurge $ olcAccessLogSuccess $ "
124                         "olcAccessLogOld $ olcAccessLogOldAttr ) )",
125                         Cft_Overlay, log_cfats },
126         { NULL }
127 };
128
129 static slap_verbmasks logops[] = {
130         { BER_BVC("all"),               LOG_OP_ALL },
131         { BER_BVC("writes"),    LOG_OP_WRITES },
132         { BER_BVC("session"),   LOG_OP_SESSION },
133         { BER_BVC("reads"),             LOG_OP_READS },
134         { BER_BVC("add"),               LOG_OP_ADD },
135         { BER_BVC("delete"),    LOG_OP_DELETE },
136         { BER_BVC("modify"),    LOG_OP_MODIFY },
137         { BER_BVC("modrdn"),    LOG_OP_MODRDN },
138         { BER_BVC("compare"),   LOG_OP_COMPARE },
139         { BER_BVC("search"),    LOG_OP_SEARCH },
140         { BER_BVC("bind"),              LOG_OP_BIND },
141         { BER_BVC("unbind"),    LOG_OP_UNBIND },
142         { BER_BVC("abandon"),   LOG_OP_ABANDON },
143         { BER_BVC("extended"),  LOG_OP_EXTENDED },
144         { BER_BVC("unknown"),   LOG_OP_UNKNOWN },
145         { BER_BVNULL, 0 }
146 };
147
148 /* Start with "add" in logops */
149 #define EN_OFFSET       4
150
151 enum {
152         LOG_EN_ADD = 0,
153         LOG_EN_DELETE,
154         LOG_EN_MODIFY,
155         LOG_EN_MODRDN,
156         LOG_EN_COMPARE,
157         LOG_EN_SEARCH,
158         LOG_EN_BIND,
159         LOG_EN_UNBIND,
160         LOG_EN_ABANDON,
161         LOG_EN_EXTENDED,
162         LOG_EN_UNKNOWN,
163         LOG_EN__COUNT
164 };
165
166 static ObjectClass *log_ocs[LOG_EN__COUNT], *log_container,
167         *log_oc_read, *log_oc_write;
168
169 #define LOG_SCHEMA_ROOT "1.3.6.1.4.1.4203.666.11.5"
170
171 #define LOG_SCHEMA_AT LOG_SCHEMA_ROOT ".1"
172 #define LOG_SCHEMA_OC LOG_SCHEMA_ROOT ".2"
173 #define LOG_SCHEMA_SYN LOG_SCHEMA_ROOT ".3"
174
175 static AttributeDescription *ad_reqDN, *ad_reqStart, *ad_reqEnd, *ad_reqType,
176         *ad_reqSession, *ad_reqResult, *ad_reqAuthzID, *ad_reqControls,
177         *ad_reqRespControls, *ad_reqMethod, *ad_reqAssertion, *ad_reqNewRDN,
178         *ad_reqNewSuperior, *ad_reqDeleteOldRDN, *ad_reqMod,
179         *ad_reqScope, *ad_reqFilter, *ad_reqAttr, *ad_reqEntries,
180         *ad_reqSizeLimit, *ad_reqTimeLimit, *ad_reqAttrsOnly, *ad_reqData,
181         *ad_reqId, *ad_reqMessage, *ad_reqVersion, *ad_reqDerefAliases,
182         *ad_reqReferral, *ad_reqOld, *ad_auditContext;
183
184 static int
185 logSchemaControlValidate(
186         Syntax          *syntax,
187         struct berval   *val );
188
189 char    *mrControl[] = {
190         "objectIdentifierFirstComponentMatch",
191         NULL
192 };
193
194 static struct {
195         char                    *oid;
196         slap_syntax_defs_rec    syn;
197         char                    **mrs;
198 } lsyntaxes[] = {
199         { LOG_SCHEMA_SYN ".1" ,
200                 { "( " LOG_SCHEMA_SYN ".1 DESC 'Control' )",
201                         SLAP_SYNTAX_HIDE,
202                         NULL,
203                         logSchemaControlValidate,
204                         NULL },
205                 mrControl },
206         { NULL }
207 };
208
209 static struct {
210         char *at;
211         AttributeDescription **ad;
212 } lattrs[] = {
213         { "( " LOG_SCHEMA_AT ".1 NAME 'reqDN' "
214                 "DESC 'Target DN of request' "
215                 "EQUALITY distinguishedNameMatch "
216                 "SYNTAX OMsDN "
217                 "SINGLE-VALUE )", &ad_reqDN },
218         { "( " LOG_SCHEMA_AT ".2 NAME 'reqStart' "
219                 "DESC 'Start time of request' "
220                 "EQUALITY generalizedTimeMatch "
221                 "ORDERING generalizedTimeOrderingMatch "
222                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
223                 "SINGLE-VALUE )", &ad_reqStart },
224         { "( " LOG_SCHEMA_AT ".3 NAME 'reqEnd' "
225                 "DESC 'End time of request' "
226                 "EQUALITY generalizedTimeMatch "
227                 "ORDERING generalizedTimeOrderingMatch "
228                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
229                 "SINGLE-VALUE )", &ad_reqEnd },
230         { "( " LOG_SCHEMA_AT ".4 NAME 'reqType' "
231                 "DESC 'Type of request' "
232                 "EQUALITY caseIgnoreMatch "
233                 "SYNTAX OMsDirectoryString "
234                 "SINGLE-VALUE )", &ad_reqType },
235         { "( " LOG_SCHEMA_AT ".5 NAME 'reqSession' "
236                 "DESC 'Session ID of request' "
237                 "EQUALITY caseIgnoreMatch "
238                 "SYNTAX OMsDirectoryString "
239                 "SINGLE-VALUE )", &ad_reqSession },
240         { "( " LOG_SCHEMA_AT ".6 NAME 'reqAuthzID' "
241                 "DESC 'Authorization ID of requestor' "
242                 "EQUALITY distinguishedNameMatch "
243                 "SYNTAX OMsDN "
244                 "SINGLE-VALUE )", &ad_reqAuthzID },
245         { "( " LOG_SCHEMA_AT ".7 NAME 'reqResult' "
246                 "DESC 'Result code of request' "
247                 "EQUALITY integerMatch "
248                 "ORDERING integerOrderingMatch "
249                 "SYNTAX OMsInteger "
250                 "SINGLE-VALUE )", &ad_reqResult },
251         { "( " LOG_SCHEMA_AT ".8 NAME 'reqMessage' "
252                 "DESC 'Error text of request' "
253                 "EQUALITY caseIgnoreMatch "
254                 "SUBSTR caseIgnoreSubstringsMatch "
255                 "SYNTAX OMsDirectoryString "
256                 "SINGLE-VALUE )", &ad_reqMessage },
257         { "( " LOG_SCHEMA_AT ".9 NAME 'reqReferral' "
258                 "DESC 'Referrals returned for request' "
259                 "SUP labeledURI )", &ad_reqReferral },
260         { "( " LOG_SCHEMA_AT ".10 NAME 'reqControls' "
261                 "DESC 'Request controls' "
262                 "EQUALITY objectIdentifierFirstComponentMatch "
263                 "SYNTAX " LOG_SCHEMA_SYN ".1 "
264                 "X-ORDERED 'VALUES' )", &ad_reqControls },
265         { "( " LOG_SCHEMA_AT ".11 NAME 'reqRespControls' "
266                 "DESC 'Response controls of request' "
267                 "EQUALITY objectIdentifierFirstComponentMatch "
268                 "SYNTAX " LOG_SCHEMA_SYN ".1 "
269                 "X-ORDERED 'VALUES' )", &ad_reqRespControls },
270         { "( " LOG_SCHEMA_AT ".12 NAME 'reqId' "
271                 "DESC 'ID of Request to Abandon' "
272                 "EQUALITY integerMatch "
273                 "ORDERING integerOrderingMatch "
274                 "SYNTAX OMsInteger "
275                 "SINGLE-VALUE )", &ad_reqId },
276         { "( " LOG_SCHEMA_AT ".13 NAME 'reqVersion' "
277                 "DESC 'Protocol version of Bind request' "
278                 "EQUALITY integerMatch "
279                 "ORDERING integerOrderingMatch "
280                 "SYNTAX OMsInteger "
281                 "SINGLE-VALUE )", &ad_reqVersion },
282         { "( " LOG_SCHEMA_AT ".14 NAME 'reqMethod' "
283                 "DESC 'Bind method of request' "
284                 "EQUALITY caseIgnoreMatch "
285                 "SYNTAX OMsDirectoryString "
286                 "SINGLE-VALUE )", &ad_reqMethod },
287         { "( " LOG_SCHEMA_AT ".15 NAME 'reqAssertion' "
288                 "DESC 'Compare Assertion of request' "
289                 "SYNTAX OMsDirectoryString "
290                 "SINGLE-VALUE )", &ad_reqAssertion },
291         { "( " LOG_SCHEMA_AT ".16 NAME 'reqMod' "
292                 "DESC 'Modifications of request' "
293                 "EQUALITY octetStringMatch "
294                 "SUBSTR octetStringSubstringsMatch "
295                 "SYNTAX OMsOctetString )", &ad_reqMod },
296         { "( " LOG_SCHEMA_AT ".17 NAME 'reqOld' "
297                 "DESC 'Old values of entry before request completed' "
298                 "EQUALITY octetStringMatch "
299                 "SUBSTR octetStringSubstringsMatch "
300                 "SYNTAX OMsOctetString )", &ad_reqOld },
301         { "( " LOG_SCHEMA_AT ".18 NAME 'reqNewRDN' "
302                 "DESC 'New RDN of request' "
303                 "EQUALITY distinguishedNameMatch "
304                 "SYNTAX OMsDN "
305                 "SINGLE-VALUE )", &ad_reqNewRDN },
306         { "( " LOG_SCHEMA_AT ".19 NAME 'reqDeleteOldRDN' "
307                 "DESC 'Delete old RDN' "
308                 "EQUALITY booleanMatch "
309                 "SYNTAX OMsBoolean "
310                 "SINGLE-VALUE )", &ad_reqDeleteOldRDN },
311         { "( " LOG_SCHEMA_AT ".20 NAME 'reqNewSuperior' "
312                 "DESC 'New superior DN of request' "
313                 "EQUALITY distinguishedNameMatch "
314                 "SYNTAX OMsDN "
315                 "SINGLE-VALUE )", &ad_reqNewSuperior },
316         { "( " LOG_SCHEMA_AT ".21 NAME 'reqScope' "
317                 "DESC 'Scope of request' "
318                 "EQUALITY caseIgnoreMatch "
319                 "SYNTAX OMsDirectoryString "
320                 "SINGLE-VALUE )", &ad_reqScope },
321         { "( " LOG_SCHEMA_AT ".22 NAME 'reqDerefAliases' "
322                 "DESC 'Disposition of Aliases in request' "
323                 "EQUALITY caseIgnoreMatch "
324                 "SYNTAX OMsDirectoryString "
325                 "SINGLE-VALUE )", &ad_reqDerefAliases },
326         { "( " LOG_SCHEMA_AT ".23 NAME 'reqAttrsOnly' "
327                 "DESC 'Attributes and values of request' "
328                 "EQUALITY booleanMatch "
329                 "SYNTAX OMsBoolean "
330                 "SINGLE-VALUE )", &ad_reqAttrsOnly },
331         { "( " LOG_SCHEMA_AT ".24 NAME 'reqFilter' "
332                 "DESC 'Filter of request' "
333                 "EQUALITY caseIgnoreMatch "
334                 "SUBSTR caseIgnoreSubstringsMatch "
335                 "SYNTAX OMsDirectoryString "
336                 "SINGLE-VALUE )", &ad_reqFilter },
337         { "( " LOG_SCHEMA_AT ".25 NAME 'reqAttr' "
338                 "DESC 'Attributes of request' "
339                 "EQUALITY caseIgnoreMatch "
340                 "SYNTAX OMsDirectoryString )", &ad_reqAttr },
341         { "( " LOG_SCHEMA_AT ".26 NAME 'reqSizeLimit' "
342                 "DESC 'Size limit of request' "
343                 "EQUALITY integerMatch "
344                 "ORDERING integerOrderingMatch "
345                 "SYNTAX OMsInteger "
346                 "SINGLE-VALUE )", &ad_reqSizeLimit },
347         { "( " LOG_SCHEMA_AT ".27 NAME 'reqTimeLimit' "
348                 "DESC 'Time limit of request' "
349                 "EQUALITY integerMatch "
350                 "ORDERING integerOrderingMatch "
351                 "SYNTAX OMsInteger "
352                 "SINGLE-VALUE )", &ad_reqTimeLimit },
353         { "( " LOG_SCHEMA_AT ".28 NAME 'reqEntries' "
354                 "DESC 'Number of entries returned' "
355                 "EQUALITY integerMatch "
356                 "ORDERING integerOrderingMatch "
357                 "SYNTAX OMsInteger "
358                 "SINGLE-VALUE )", &ad_reqEntries },
359         { "( " LOG_SCHEMA_AT ".29 NAME 'reqData' "
360                 "DESC 'Data of extended request' "
361                 "EQUALITY octetStringMatch "
362                 "SUBSTR octetStringSubstringsMatch "
363                 "SYNTAX OMsOctetString "
364                 "SINGLE-VALUE )", &ad_reqData },
365
366         /*
367          * from <draft-chu-ldap-logschema-01.txt>:
368          *
369
370    ( LOG_SCHEMA_AT .30 NAME 'auditContext'
371    DESC 'DN of auditContainer'
372    EQUALITY distinguishedNameMatch
373    SYNTAX 1.3.6.1.4.1.1466.115.121.1.12
374    SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation )
375
376          * - removed EQUALITY matchingRule
377          * - changed directoryOperation in dSAOperation
378          */
379         { "( " LOG_SCHEMA_AT ".30 NAME 'auditContext' "
380                 "DESC 'DN of auditContainer' "
381                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 "
382                 "SINGLE-VALUE "
383                 "NO-USER-MODIFICATION "
384                 "USAGE dSAOperation )", &ad_auditContext },
385         { NULL, NULL }
386 };
387
388 static struct {
389         char *ot;
390         ObjectClass **oc;
391 } locs[] = {
392         { "( " LOG_SCHEMA_OC ".0 NAME 'auditContainer' "
393                 "DESC 'AuditLog container' "
394                 "SUP top STRUCTURAL "
395                 "MAY ( cn $ reqStart $ reqEnd ) )", &log_container },
396         { "( " LOG_SCHEMA_OC ".1 NAME 'auditObject' "
397                 "DESC 'OpenLDAP request auditing' "
398                 "SUP top STRUCTURAL "
399                 "MUST ( reqStart $ reqType $ reqSession ) "
400                 "MAY ( reqDN $ reqAuthzID $ reqControls $ reqRespControls $ reqEnd $ "
401                         "reqResult $ reqMessage $ reqReferral ) )",
402                                 &log_ocs[LOG_EN_UNBIND] },
403         { "( " LOG_SCHEMA_OC ".2 NAME 'auditReadObject' "
404                 "DESC 'OpenLDAP read request record' "
405                 "SUP auditObject STRUCTURAL )", &log_oc_read },
406         { "( " LOG_SCHEMA_OC ".3 NAME 'auditWriteObject' "
407                 "DESC 'OpenLDAP write request record' "
408                 "SUP auditObject STRUCTURAL )", &log_oc_write },
409         { "( " LOG_SCHEMA_OC ".4 NAME 'auditAbandon' "
410                 "DESC 'Abandon operation' "
411                 "SUP auditObject STRUCTURAL "
412                 "MUST reqId )", &log_ocs[LOG_EN_ABANDON] },
413         { "( " LOG_SCHEMA_OC ".5 NAME 'auditAdd' "
414                 "DESC 'Add operation' "
415                 "SUP auditWriteObject STRUCTURAL "
416                 "MUST reqMod )", &log_ocs[LOG_EN_ADD] },
417         { "( " LOG_SCHEMA_OC ".6 NAME 'auditBind' "
418                 "DESC 'Bind operation' "
419                 "SUP auditObject STRUCTURAL "
420                 "MUST ( reqVersion $ reqMethod ) )", &log_ocs[LOG_EN_BIND] },
421         { "( " LOG_SCHEMA_OC ".7 NAME 'auditCompare' "
422                 "DESC 'Compare operation' "
423                 "SUP auditReadObject STRUCTURAL "
424                 "MUST reqAssertion )", &log_ocs[LOG_EN_COMPARE] },
425         { "( " LOG_SCHEMA_OC ".8 NAME 'auditDelete' "
426                 "DESC 'Delete operation' "
427                 "SUP auditWriteObject STRUCTURAL "
428                 "MAY reqOld )", &log_ocs[LOG_EN_DELETE] },
429         { "( " LOG_SCHEMA_OC ".9 NAME 'auditModify' "
430                 "DESC 'Modify operation' "
431                 "SUP auditWriteObject STRUCTURAL "
432                 "MAY reqOld MUST reqMod )", &log_ocs[LOG_EN_MODIFY] },
433         { "( " LOG_SCHEMA_OC ".10 NAME 'auditModRDN' "
434                 "DESC 'ModRDN operation' "
435                 "SUP auditWriteObject STRUCTURAL "
436                 "MUST ( reqNewRDN $ reqDeleteOldRDN ) "
437                 "MAY ( reqNewSuperior $ reqMod $ reqOld ) )", &log_ocs[LOG_EN_MODRDN] },
438         { "( " LOG_SCHEMA_OC ".11 NAME 'auditSearch' "
439                 "DESC 'Search operation' "
440                 "SUP auditReadObject STRUCTURAL "
441                 "MUST ( reqScope $ reqDerefAliases $ reqAttrsonly ) "
442                 "MAY ( reqFilter $ reqAttr $ reqEntries $ reqSizeLimit $ "
443                         "reqTimeLimit ) )", &log_ocs[LOG_EN_SEARCH] },
444         { "( " LOG_SCHEMA_OC ".12 NAME 'auditExtended' "
445                 "DESC 'Extended operation' "
446                 "SUP auditObject STRUCTURAL "
447                 "MAY reqData )", &log_ocs[LOG_EN_EXTENDED] },
448         { NULL, NULL }
449 };
450
451 #define RDNEQ   "reqStart="
452
453 /* Our time intervals are of the form [ddd+]hh:mm[:ss]
454  * If a field is present, it must be two digits. (Except for
455  * days, which can be arbitrary width.)
456  */
457 static int
458 log_age_parse(char *agestr)
459 {
460         int t1, t2;
461         int gotdays = 0;
462         char *endptr;
463
464         t1 = strtol( agestr, &endptr, 10 );
465         /* Is there a days delimiter? */
466         if ( *endptr == '+' ) {
467                 /* 32 bit time only covers about 68 years */
468                 if ( t1 < 0 || t1 > 25000 )
469                         return -1;
470                 t1 *= 24;
471                 gotdays = 1;
472                 agestr = endptr + 1;
473         } else {
474                 if ( agestr[2] != ':' ) {
475                         /* No valid delimiter found, fail */
476                         return -1;
477                 }
478                 t1 *= 60;
479                 agestr += 3;
480         }
481
482         t2 = atoi( agestr );
483         t1 += t2;
484
485         if ( agestr[2] ) {
486                 /* if there's a delimiter, it can only be a colon */
487                 if ( agestr[2] != ':' )
488                         return -1;
489         } else {
490                 /* If we're at the end of the string, and we started with days,
491                  * fail because we expected to find minutes too.
492                  */
493                 return gotdays ? -1 : t1 * 60;
494         }
495
496         agestr += 3;
497         t2 = atoi( agestr );
498
499         /* last field can only be seconds */
500         if ( agestr[2] && ( agestr[2] != ':' || !gotdays ))
501                 return -1;
502         t1 *= 60;
503         t1 += t2;
504
505         if ( agestr[2] ) {
506                 agestr += 3;
507                 if ( agestr[2] )
508                         return -1;
509                 t1 *= 60;
510                 t1 += atoi( agestr );
511         } else if ( gotdays ) {
512                 /* only got days+hh:mm */
513                 t1 *= 60;
514         }
515         return t1;
516 }
517
518 static void
519 log_age_unparse( int age, struct berval *agebv, size_t size )
520 {
521         int dd, hh, mm, ss, len;
522         char *ptr;
523
524         assert( size > 0 );
525
526         ss = age % 60;
527         age /= 60;
528         mm = age % 60;
529         age /= 60;
530         hh = age % 24;
531         age /= 24;
532         dd = age;
533
534         ptr = agebv->bv_val;
535
536         if ( dd ) {
537                 len = snprintf( ptr, size, "%d+", dd );
538                 assert( len >= 0 && len < size );
539                 size -= len;
540                 ptr += len;
541         }
542         len = snprintf( ptr, size, "%02d:%02d", hh, mm );
543         assert( len >= 0 && len < size );
544         size -= len;
545         ptr += len;
546         if ( ss ) {
547                 len = snprintf( ptr, size, ":%02d", ss );
548                 assert( len >= 0 && len < size );
549                 size -= len;
550                 ptr += len;
551         }
552
553         agebv->bv_len = ptr - agebv->bv_val;
554 }
555
556 static slap_callback nullsc = { NULL, NULL, NULL, NULL };
557
558 #define PURGE_INCREMENT 100
559
560 typedef struct purge_data {
561         int slots;
562         int used;
563         BerVarray dn;
564         BerVarray ndn;
565         struct berval csn;      /* an arbitrary old CSN */
566 } purge_data;
567
568 static int
569 log_old_lookup( Operation *op, SlapReply *rs )
570 {
571         purge_data *pd = op->o_callback->sc_private;
572
573         if ( rs->sr_type != REP_SEARCH) return 0;
574
575         if ( slapd_shutdown ) return 0;
576
577         /* Remember old CSN */
578         if ( pd->csn.bv_val[0] == '\0' ) {
579                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
580                         slap_schema.si_ad_entryCSN );
581                 if ( a ) {
582                         int len = a->a_vals[0].bv_len;
583                         if ( len > pd->csn.bv_len )
584                                 len = pd->csn.bv_len;
585                         AC_MEMCPY( pd->csn.bv_val, a->a_vals[0].bv_val, len );
586                         pd->csn.bv_len = len;
587                 }
588         }
589         if ( pd->used >= pd->slots ) {
590                 pd->slots += PURGE_INCREMENT;
591                 pd->dn = ch_realloc( pd->dn, pd->slots * sizeof( struct berval ));
592                 pd->ndn = ch_realloc( pd->ndn, pd->slots * sizeof( struct berval ));
593         }
594         ber_dupbv( &pd->dn[pd->used], &rs->sr_entry->e_name );
595         ber_dupbv( &pd->ndn[pd->used], &rs->sr_entry->e_nname );
596         pd->used++;
597         return 0;
598 }
599
600 /* Periodically search for old entries in the log database and delete them */
601 static void *
602 accesslog_purge( void *ctx, void *arg )
603 {
604         struct re_s *rtask = arg;
605         struct log_info *li = rtask->arg;
606
607         Connection conn = {0};
608         OperationBuffer opbuf;
609         Operation *op;
610         SlapReply rs = {REP_RESULT};
611         slap_callback cb = { NULL, log_old_lookup, NULL, NULL };
612         Filter f;
613         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
614         purge_data pd = {0};
615         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE];
616         char csnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
617         time_t old = slap_get_time();
618
619         connection_fake_init( &conn, &opbuf, ctx );
620         op = &opbuf.ob_op;
621
622         f.f_choice = LDAP_FILTER_LE;
623         f.f_ava = &ava;
624         f.f_next = NULL;
625
626         ava.aa_desc = ad_reqStart;
627         ava.aa_value.bv_val = timebuf;
628         ava.aa_value.bv_len = sizeof(timebuf);
629
630         old -= li->li_age;
631         slap_timestamp( &old, &ava.aa_value );
632
633         op->o_tag = LDAP_REQ_SEARCH;
634         op->o_bd = li->li_db;
635         op->o_dn = li->li_db->be_rootdn;
636         op->o_ndn = li->li_db->be_rootndn;
637         op->o_req_dn = li->li_db->be_suffix[0];
638         op->o_req_ndn = li->li_db->be_nsuffix[0];
639         op->o_callback = &cb;
640         op->ors_scope = LDAP_SCOPE_ONELEVEL;
641         op->ors_deref = LDAP_DEREF_NEVER;
642         op->ors_tlimit = SLAP_NO_LIMIT;
643         op->ors_slimit = SLAP_NO_LIMIT;
644         op->ors_filter = &f;
645         filter2bv_x( op, &f, &op->ors_filterstr );
646         op->ors_attrs = slap_anlist_no_attrs;
647         op->ors_attrsonly = 1;
648         
649         pd.csn.bv_len = sizeof( csnbuf );
650         pd.csn.bv_val = csnbuf;
651         csnbuf[0] = '\0';
652         cb.sc_private = &pd;
653
654         op->o_bd->be_search( op, &rs );
655         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
656
657         if ( pd.used ) {
658                 int i;
659
660                 op->o_tag = LDAP_REQ_DELETE;
661                 op->o_callback = &nullsc;
662                 op->o_csn = pd.csn;
663
664                 for (i=0; i<pd.used; i++) {
665                         op->o_req_dn = pd.dn[i];
666                         op->o_req_ndn = pd.ndn[i];
667                         if ( !slapd_shutdown )
668                                 op->o_bd->be_delete( op, &rs );
669                         ch_free( pd.ndn[i].bv_val );
670                         ch_free( pd.dn[i].bv_val );
671                 }
672                 ch_free( pd.ndn );
673                 ch_free( pd.dn );
674         }
675
676         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
677         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
678         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
679
680         return NULL;
681 }
682
683 static int
684 log_cf_gen(ConfigArgs *c)
685 {
686         slap_overinst *on = (slap_overinst *)c->bi;
687         struct log_info *li = on->on_bi.bi_private;
688         int rc = 0;
689         slap_mask_t tmask = 0;
690         char agebuf[2*STRLENOF("ddddd+hh:mm:ss  ")];
691         struct berval agebv, cyclebv;
692
693         switch( c->op ) {
694         case SLAP_CONFIG_EMIT:
695                 switch( c->type ) {
696                 case LOG_DB:
697                         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
698                                 value_add_one( &c->rvalue_vals, &li->li_db_suffix );
699                                 value_add_one( &c->rvalue_nvals, &li->li_db_suffix );
700                         } else if ( li->li_db ) {
701                                 value_add_one( &c->rvalue_vals, li->li_db->be_suffix );
702                                 value_add_one( &c->rvalue_nvals, li->li_db->be_nsuffix );
703                         } else {
704                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
705                                         "accesslog: \"logdb <suffix>\" must be specified" );
706                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
707                                         c->log, c->cr_msg, c->value_dn.bv_val );
708                                 rc = 1;
709                                 break;
710                         }
711                         break;
712                 case LOG_OPS:
713                         rc = mask_to_verbs( logops, li->li_ops, &c->rvalue_vals );
714                         break;
715                 case LOG_PURGE:
716                         if ( !li->li_age ) {
717                                 rc = 1;
718                                 break;
719                         }
720                         agebv.bv_val = agebuf;
721                         log_age_unparse( li->li_age, &agebv, sizeof( agebuf ) );
722                         agebv.bv_val[agebv.bv_len] = ' ';
723                         agebv.bv_len++;
724                         cyclebv.bv_val = agebv.bv_val + agebv.bv_len;
725                         log_age_unparse( li->li_cycle, &cyclebv, sizeof( agebuf ) - agebv.bv_len );
726                         agebv.bv_len += cyclebv.bv_len;
727                         value_add_one( &c->rvalue_vals, &agebv );
728                         break;
729                 case LOG_SUCCESS:
730                         if ( li->li_success )
731                                 c->value_int = li->li_success;
732                         else
733                                 rc = 1;
734                         break;
735                 case LOG_OLD:
736                         if ( li->li_oldf ) {
737                                 filter2bv( li->li_oldf, &agebv );
738                                 ber_bvarray_add( &c->rvalue_vals, &agebv );
739                         }
740                         else
741                                 rc = 1;
742                         break;
743                 case LOG_OLDATTR:
744                         if ( li->li_oldattrs ) {
745                                 log_attr *la;
746
747                                 for ( la = li->li_oldattrs; la; la=la->next )
748                                         value_add_one( &c->rvalue_vals, &la->attr->ad_cname );
749                         }
750                         else
751                                 rc = 1;
752                         break;
753                 }
754                 break;
755         case LDAP_MOD_DELETE:
756                 switch( c->type ) {
757                 case LOG_DB:
758                         /* noop. this should always be a valid backend. */
759                         break;
760                 case LOG_OPS:
761                         if ( c->valx < 0 ) {
762                                 li->li_ops = 0;
763                         } else {
764                                 rc = verbs_to_mask( 1, &c->line, logops, &tmask );
765                                 if ( rc == 0 )
766                                         li->li_ops &= ~tmask;
767                         }
768                         break;
769                 case LOG_PURGE:
770                         if ( li->li_task ) {
771                                 struct re_s *re = li->li_task;
772                                 li->li_task = NULL;
773                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
774                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
775                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
776                         }
777                         li->li_age = 0;
778                         li->li_cycle = 0;
779                         break;
780                 case LOG_SUCCESS:
781                         li->li_success = 0;
782                         break;
783                 case LOG_OLD:
784                         if ( li->li_oldf ) {
785                                 filter_free( li->li_oldf );
786                                 li->li_oldf = NULL;
787                         }
788                         break;
789                 case LOG_OLDATTR:
790                         if ( c->valx < 0 ) {
791                                 log_attr *la, *ln;
792
793                                 for ( la = li->li_oldattrs; la; la = ln ) {
794                                         ln = la->next;
795                                         ch_free( la );
796                                 }
797                         } else {
798                                 log_attr *la = NULL, **lp;
799                                 int i;
800
801                                 for ( lp = &li->li_oldattrs, i=0; i < c->valx; i++ ) {
802                                         la = *lp;
803                                         lp = &la->next;
804                                 }
805                                 *lp = la->next;
806                                 ch_free( la );
807                         }
808                         break;
809                 }
810                 break;
811         default:
812                 switch( c->type ) {
813                 case LOG_DB:
814                         if ( CONFIG_ONLINE_ADD( c )) {
815                                 li->li_db = select_backend( &c->value_ndn, 0 );
816                                 if ( !li->li_db ) {
817                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
818                                                 "<%s> no matching backend found for suffix",
819                                                 c->argv[0] );
820                                         Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
821                                                 c->log, c->cr_msg, c->value_dn.bv_val );
822                                         rc = 1;
823                                 }
824                                 ch_free( c->value_ndn.bv_val );
825                         } else {
826                                 li->li_db_suffix = c->value_ndn;
827                         }
828                         ch_free( c->value_dn.bv_val );
829                         break;
830                 case LOG_OPS:
831                         rc = verbs_to_mask( c->argc, c->argv, logops, &tmask );
832                         if ( rc == 0 )
833                                 li->li_ops |= tmask;
834                         break;
835                 case LOG_PURGE:
836                         li->li_age = log_age_parse( c->argv[1] );
837                         if ( li->li_age < 1 ) {
838                                 rc = 1;
839                         } else {
840                                 li->li_cycle = log_age_parse( c->argv[2] );
841                                 if ( li->li_cycle < 1 ) {
842                                         rc = 1;
843                                 } else if ( slapMode & SLAP_SERVER_MODE ) {
844                                         struct re_s *re = li->li_task;
845                                         if ( re )
846                                                 re->interval.tv_sec = li->li_cycle;
847                                         else
848                                                 li->li_task = ldap_pvt_runqueue_insert( &slapd_rq,
849                                                         li->li_cycle, accesslog_purge, li,
850                                                         "accesslog_purge", li->li_db ?
851                                                                 li->li_db->be_suffix[0].bv_val :
852                                                                 c->be->be_suffix[0].bv_val );
853                                 }
854                         }
855                         break;
856                 case LOG_SUCCESS:
857                         li->li_success = c->value_int;
858                         break;
859                 case LOG_OLD:
860                         li->li_oldf = str2filter( c->argv[1] );
861                         if ( !li->li_oldf ) {
862                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "bad filter!" );
863                                 rc = 1;
864                         }
865                         break;
866                 case LOG_OLDATTR: {
867                         int i;
868                         AttributeDescription *ad;
869                         const char *text;
870
871                         for ( i=1; i< c->argc; i++ ) {
872                                 ad = NULL;
873                                 if ( slap_str2ad( c->argv[i], &ad, &text ) == LDAP_SUCCESS ) {
874                                         log_attr *la = ch_malloc( sizeof( log_attr ));
875                                         la->attr = ad;
876                                         la->next = li->li_oldattrs;
877                                         li->li_oldattrs = la;
878                                 } else {
879                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s <%s>: %s",
880                                                 c->argv[0], c->argv[i], text );
881                                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
882                                                 "%s: %s\n", c->log, c->cr_msg, 0 );
883                                         rc = ARG_BAD_CONF;
884                                         break;
885                                 }
886                         }
887                         }
888                         break;
889                 }
890                 break;
891         }
892         return rc;
893 }
894
895 static int
896 logSchemaControlValidate(
897         Syntax          *syntax,
898         struct berval   *valp )
899 {
900         struct berval   val, bv;
901         int             i;
902         int             rc = LDAP_SUCCESS;
903
904         assert( valp != NULL );
905
906         val = *valp;
907
908         /* check minimal size */
909         if ( val.bv_len < STRLENOF( "{*}" ) ) {
910                 return LDAP_INVALID_SYNTAX;
911         }
912
913         val.bv_len--;
914
915         /* check SEQUENCE boundaries */
916         if ( val.bv_val[ 0 ] != '{' /*}*/ ||
917                 val.bv_val[ val.bv_len ] != /*{*/ '}' )
918         {
919                 return LDAP_INVALID_SYNTAX;
920         }
921
922         /* extract and check OID */
923         for ( i = 1; i < val.bv_len; i++ ) {
924                 if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
925                         break;
926                 }
927         }
928
929         bv.bv_val = &val.bv_val[ i ];
930
931         for ( i++; i < val.bv_len; i++ ) {
932                 if ( ASCII_SPACE( val.bv_val[ i ] ) )
933                 {
934                         break;
935                 }
936         }
937
938         bv.bv_len = &val.bv_val[ i ] - bv.bv_val;
939
940         rc = numericoidValidate( NULL, &bv );
941         if ( rc != LDAP_SUCCESS ) {
942                 return rc;
943         }
944
945         if ( i == val.bv_len ) {
946                 return LDAP_SUCCESS;
947         }
948
949         if ( val.bv_val[ i ] != ' ' ) {
950                 return LDAP_INVALID_SYNTAX;
951         }
952
953         for ( i++; i < val.bv_len; i++ ) {
954                 if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
955                         break;
956                 }
957         }
958
959         if ( i == val.bv_len ) {
960                 return LDAP_SUCCESS;
961         }
962
963         /* extract and check criticality */
964         if ( strncasecmp( &val.bv_val[ i ], "criticality ", STRLENOF( "criticality " ) ) == 0 )
965         {
966                 i += STRLENOF( "criticality " );
967                 for ( ; i < val.bv_len; i++ ) {
968                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
969                                 break;
970                         }
971                 }
972
973                 if ( i == val.bv_len ) {
974                         return LDAP_INVALID_SYNTAX;
975                 }
976
977                 bv.bv_val = &val.bv_val[ i ];
978
979                 for ( ; i < val.bv_len; i++ ) {
980                         if ( ASCII_SPACE( val.bv_val[ i ] ) ) {
981                                 break;
982                         }
983                 }
984
985                 bv.bv_len = &val.bv_val[ i ] - bv.bv_val;
986
987                 if ( !bvmatch( &bv, &slap_true_bv ) && !bvmatch( &bv, &slap_false_bv ) ) 
988                 {
989                         return LDAP_INVALID_SYNTAX;
990                 }
991
992                 if ( i == val.bv_len ) {
993                         return LDAP_SUCCESS;
994                 }
995
996                 if ( val.bv_val[ i ] != ' ' ) {
997                         return LDAP_INVALID_SYNTAX;
998                 }
999
1000                 for ( i++; i < val.bv_len; i++ ) {
1001                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1002                                 break;
1003                         }
1004                 }
1005
1006                 if ( i == val.bv_len ) {
1007                         return LDAP_SUCCESS;
1008                 }
1009         }
1010
1011         /* extract and check controlValue */
1012         if ( strncasecmp( &val.bv_val[ i ], "controlValue ", STRLENOF( "controlValue " ) ) == 0 )
1013         {
1014                 i += STRLENOF( "controlValue " );
1015                 for ( ; i < val.bv_len; i++ ) {
1016                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1017                                 break;
1018                         }
1019                 }
1020
1021                 if ( i == val.bv_len ) {
1022                         return LDAP_INVALID_SYNTAX;
1023                 }
1024
1025                 if ( val.bv_val[ i ] != '"' ) {
1026                         return LDAP_INVALID_SYNTAX;
1027                 }
1028
1029                 for ( ; i < val.bv_len; i++ ) {
1030                         if ( val.bv_val[ i ] == '"' ) {
1031                                 break;
1032                         }
1033
1034                         if ( !ASCII_HEX( val.bv_val[ i ] ) ) {
1035                                 return LDAP_INVALID_SYNTAX;
1036                         }
1037                 }
1038
1039                 if ( val.bv_val[ i ] != '"' ) {
1040                         return LDAP_INVALID_SYNTAX;
1041                 }
1042
1043                 for ( ; i < val.bv_len; i++ ) {
1044                         if ( !ASCII_SPACE( val.bv_val[ i ] ) ) {
1045                                 break;
1046                         }
1047                 }
1048
1049                 if ( i == val.bv_len ) {
1050                         return LDAP_SUCCESS;
1051                 }
1052         }
1053
1054         return LDAP_INVALID_SYNTAX;
1055 }
1056
1057 static int
1058 accesslog_ctrls(
1059         LDAPControl **ctrls,
1060         BerVarray *valsp,
1061         BerVarray *nvalsp,
1062         void *memctx )
1063 {
1064         long            i, rc = 0;
1065
1066         assert( valsp != NULL );
1067         assert( ctrls != NULL );
1068
1069         *valsp = NULL;
1070         *nvalsp = NULL;
1071
1072         for ( i = 0; ctrls[ i ] != NULL; i++ ) {
1073                 struct berval   idx,
1074                                 oid,
1075                                 noid,
1076                                 bv;
1077                 char            *ptr,
1078                                 buf[ 32 ];
1079
1080                 if ( ctrls[ i ]->ldctl_oid == NULL ) {
1081                         return LDAP_PROTOCOL_ERROR;
1082                 }
1083
1084                 idx.bv_len = snprintf( buf, sizeof( buf ), "{%ld}", i );
1085                 idx.bv_val = buf;
1086
1087                 ber_str2bv( ctrls[ i ]->ldctl_oid, 0, 0, &oid );
1088                 noid.bv_len = idx.bv_len + oid.bv_len;
1089                 ptr = noid.bv_val = ber_memalloc_x( noid.bv_len + 1, memctx );
1090                 ptr = lutil_strcopy( ptr, idx.bv_val );
1091                 ptr = lutil_strcopy( ptr, oid.bv_val );
1092
1093                 bv.bv_len = idx.bv_len + STRLENOF( "{}" ) + oid.bv_len;
1094
1095                 if ( ctrls[ i ]->ldctl_iscritical ) {
1096                         bv.bv_len += STRLENOF( " criticality TRUE" );
1097                 }
1098
1099                 if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
1100                         bv.bv_len += STRLENOF( " controlValue \"\"" )
1101                                 + 2 * ctrls[ i ]->ldctl_value.bv_len;
1102                 }
1103
1104                 ptr = bv.bv_val = ber_memalloc_x( bv.bv_len + 1, memctx );
1105                 if ( ptr == NULL ) {
1106                         ber_bvarray_free( *valsp );
1107                         *valsp = NULL;
1108                         ber_bvarray_free( *nvalsp );
1109                         *nvalsp = NULL;
1110                         return LDAP_OTHER;
1111                 }
1112
1113                 ptr = lutil_strcopy( ptr, idx.bv_val );
1114
1115                 *ptr++ = '{' /*}*/ ;
1116                 ptr = lutil_strcopy( ptr, oid.bv_val );
1117
1118                 if ( ctrls[ i ]->ldctl_iscritical ) {
1119                         ptr = lutil_strcopy( ptr, " criticality TRUE" );
1120                 }
1121                 
1122                 if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
1123                         int     j;
1124
1125                         ptr = lutil_strcopy( ptr, " controlValue \"" );
1126                         for ( j = 0; j < ctrls[ i ]->ldctl_value.bv_len; j++ )
1127                         {
1128                                 unsigned char   o;
1129
1130                                 o = ( ( ctrls[ i ]->ldctl_value.bv_val[ j ] >> 4 ) & 0xF );
1131                                 if ( o < 10 ) {
1132                                         *ptr++ = '0' + o;
1133
1134                                 } else {
1135                                         *ptr++ = 'A' + o;
1136                                 }
1137
1138                                 o = ( ctrls[ i ]->ldctl_value.bv_val[ j ] & 0xF );
1139                                 if ( o < 10 ) {
1140                                         *ptr++ = '0' + o;
1141
1142                                 } else {
1143                                         *ptr++ = 'A' + o;
1144                                 }
1145                         }
1146
1147                         *ptr++ = '"';
1148                 }
1149
1150                 *ptr++ = '}';
1151                 *ptr = '\0';
1152
1153                 ber_bvarray_add_x( valsp, &bv, memctx );
1154                 ber_bvarray_add_x( nvalsp, &noid, memctx );
1155         }
1156
1157         return rc;
1158         
1159 }
1160
1161 static Entry *accesslog_entry( Operation *op, SlapReply *rs, int logop,
1162         Operation *op2 ) {
1163         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1164         log_info *li = on->on_bi.bi_private;
1165
1166         char rdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
1167         char nrdnbuf[STRLENOF(RDNEQ)+LDAP_LUTIL_GENTIME_BUFSIZE+8];
1168
1169         struct berval rdn, nrdn, timestamp, ntimestamp, bv;
1170         slap_verbmasks *lo = logops+logop+EN_OFFSET;
1171
1172         Entry *e = entry_alloc();
1173
1174         strcpy( rdnbuf, RDNEQ );
1175         rdn.bv_val = rdnbuf;
1176         strcpy( nrdnbuf, RDNEQ );
1177         nrdn.bv_val = nrdnbuf;
1178
1179         timestamp.bv_val = rdnbuf+STRLENOF(RDNEQ);
1180         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
1181         slap_timestamp( &op->o_time, &timestamp );
1182         snprintf( timestamp.bv_val + timestamp.bv_len-1, sizeof(".123456Z"), ".%06dZ", op->o_tincr );
1183         timestamp.bv_len += STRLENOF(".123456");
1184
1185         rdn.bv_len = STRLENOF(RDNEQ)+timestamp.bv_len;
1186         ad_reqStart->ad_type->sat_equality->smr_normalize(
1187                 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, ad_reqStart->ad_type->sat_syntax,
1188                 ad_reqStart->ad_type->sat_equality, &timestamp, &ntimestamp,
1189                 op->o_tmpmemctx );
1190
1191         strcpy( nrdn.bv_val + STRLENOF(RDNEQ), ntimestamp.bv_val );
1192         nrdn.bv_len = STRLENOF(RDNEQ)+ntimestamp.bv_len;
1193         build_new_dn( &e->e_name, li->li_db->be_suffix, &rdn, NULL );
1194         build_new_dn( &e->e_nname, li->li_db->be_nsuffix, &nrdn, NULL );
1195
1196         attr_merge_one( e, slap_schema.si_ad_objectClass,
1197                 &log_ocs[logop]->soc_cname, NULL );
1198         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
1199                 &log_ocs[logop]->soc_cname, NULL );
1200         attr_merge_one( e, ad_reqStart, &timestamp, &ntimestamp );
1201         op->o_tmpfree( ntimestamp.bv_val, op->o_tmpmemctx );
1202
1203         slap_op_time( &op2->o_time, &op2->o_tincr );
1204
1205         timestamp.bv_len = sizeof(rdnbuf) - STRLENOF(RDNEQ);
1206         slap_timestamp( &op2->o_time, &timestamp );
1207         snprintf( timestamp.bv_val + timestamp.bv_len-1, sizeof(".123456Z"), ".%06dZ", op2->o_tincr );
1208         timestamp.bv_len += STRLENOF(".123456");
1209
1210         attr_merge_normalize_one( e, ad_reqEnd, &timestamp, op->o_tmpmemctx );
1211
1212         /* Exops have OID appended */
1213         if ( logop == LOG_EN_EXTENDED ) {
1214                 bv.bv_len = lo->word.bv_len + op->ore_reqoid.bv_len + 2;
1215                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
1216                 AC_MEMCPY( bv.bv_val, lo->word.bv_val, lo->word.bv_len );
1217                 bv.bv_val[lo->word.bv_len] = '{';
1218                 AC_MEMCPY( bv.bv_val+lo->word.bv_len+1, op->ore_reqoid.bv_val,
1219                         op->ore_reqoid.bv_len );
1220                 bv.bv_val[bv.bv_len-1] = '}';
1221                 bv.bv_val[bv.bv_len] = '\0';
1222                 attr_merge_one( e, ad_reqType, &bv, NULL );
1223         } else {
1224                 attr_merge_one( e, ad_reqType, &lo->word, NULL );
1225         }
1226
1227         rdn.bv_len = snprintf( rdn.bv_val, sizeof( rdnbuf ), "%lu", op->o_connid );
1228         if ( rdn.bv_len >= 0 || rdn.bv_len < sizeof( rdnbuf ) ) {
1229                 attr_merge_one( e, ad_reqSession, &rdn, NULL );
1230         } /* else? */
1231
1232         if ( BER_BVISNULL( &op->o_dn ) ) {
1233                 attr_merge_one( e, ad_reqAuthzID, (struct berval *)&slap_empty_bv,
1234                         (struct berval *)&slap_empty_bv );
1235         } else {
1236                 attr_merge_one( e, ad_reqAuthzID, &op->o_dn, &op->o_ndn );
1237         }
1238
1239         /* FIXME: need to add reqControls and reqRespControls */
1240         if ( op->o_ctrls ) {
1241                 BerVarray       vals = NULL,
1242                                 nvals = NULL;
1243
1244                 if ( accesslog_ctrls( op->o_ctrls, &vals, &nvals,
1245                         op->o_tmpmemctx ) == LDAP_SUCCESS && vals )
1246                 {
1247                         attr_merge( e, ad_reqControls, vals, nvals );
1248                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1249                         ber_bvarray_free_x( nvals, op->o_tmpmemctx );
1250                 }
1251         }
1252
1253         if ( rs->sr_ctrls ) {
1254                 BerVarray       vals = NULL,
1255                                 nvals = NULL;
1256
1257                 if ( accesslog_ctrls( rs->sr_ctrls, &vals, &nvals,
1258                         op->o_tmpmemctx ) == LDAP_SUCCESS && vals )
1259                 {
1260                         attr_merge( e, ad_reqRespControls, vals, nvals );
1261                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1262                         ber_bvarray_free_x( nvals, op->o_tmpmemctx );
1263                 }
1264
1265         }
1266
1267         return e;
1268 }
1269
1270 static struct berval scopes[] = {
1271         BER_BVC("base"),
1272         BER_BVC("one"),
1273         BER_BVC("sub"),
1274         BER_BVC("subord")
1275 };
1276
1277 static struct berval derefs[] = {
1278         BER_BVC("never"),
1279         BER_BVC("searching"),
1280         BER_BVC("finding"),
1281         BER_BVC("always")
1282 };
1283
1284 static struct berval simple = BER_BVC("SIMPLE");
1285
1286 static void accesslog_val2val(AttributeDescription *ad, struct berval *val,
1287         char c_op, struct berval *dst) {
1288         char *ptr;
1289
1290         dst->bv_len = ad->ad_cname.bv_len + val->bv_len + 2;
1291         if ( c_op ) dst->bv_len++;
1292
1293         dst->bv_val = ch_malloc( dst->bv_len+1 );
1294
1295         ptr = lutil_strcopy( dst->bv_val, ad->ad_cname.bv_val );
1296         *ptr++ = ':';
1297         if ( c_op )
1298                 *ptr++ = c_op;
1299         *ptr++ = ' ';
1300         AC_MEMCPY( ptr, val->bv_val, val->bv_len );
1301         dst->bv_val[dst->bv_len] = '\0';
1302 }
1303
1304 static int accesslog_response(Operation *op, SlapReply *rs) {
1305         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1306         log_info *li = on->on_bi.bi_private;
1307         Attribute *a, *last_attr;
1308         Modifications *m;
1309         struct berval *b;
1310         int i;
1311         int logop;
1312         slap_verbmasks *lo;
1313         Entry *e = NULL, *old = NULL;
1314         char timebuf[LDAP_LUTIL_GENTIME_BUFSIZE+8];
1315         struct berval bv;
1316         char *ptr;
1317         BerVarray vals;
1318         Operation op2 = {0};
1319         SlapReply rs2 = {REP_RESULT};
1320
1321         if ( rs->sr_type != REP_RESULT && rs->sr_type != REP_EXTENDED )
1322                 return SLAP_CB_CONTINUE;
1323
1324         switch ( op->o_tag ) {
1325         case LDAP_REQ_ADD:              logop = LOG_EN_ADD; break;
1326         case LDAP_REQ_DELETE:   logop = LOG_EN_DELETE; break;
1327         case LDAP_REQ_MODIFY:   logop = LOG_EN_MODIFY; break;
1328         case LDAP_REQ_MODRDN:   logop = LOG_EN_MODRDN; break;
1329         case LDAP_REQ_COMPARE:  logop = LOG_EN_COMPARE; break;
1330         case LDAP_REQ_SEARCH:   logop = LOG_EN_SEARCH; break;
1331         case LDAP_REQ_BIND:             logop = LOG_EN_BIND; break;
1332         case LDAP_REQ_EXTENDED: logop = LOG_EN_EXTENDED; break;
1333         default:        /* unknown operation type */
1334                 logop = LOG_EN_UNKNOWN; break;
1335         }       /* Unbind and Abandon never reach here */
1336
1337         lo = logops+logop+EN_OFFSET;
1338         if ( !( li->li_ops & lo->mask ))
1339                 return SLAP_CB_CONTINUE;
1340
1341         if ( lo->mask & LOG_OP_WRITES ) {
1342                 ldap_pvt_thread_mutex_lock( &li->li_log_mutex );
1343                 old = li->li_old;
1344                 li->li_old = NULL;
1345                 li->li_unlock = 0;
1346                 ldap_pvt_thread_rmutex_unlock( &li->li_op_rmutex, op->o_tid );
1347         }
1348
1349         if ( li->li_success && rs->sr_err != LDAP_SUCCESS )
1350                 goto done;
1351
1352         e = accesslog_entry( op, rs, logop, &op2 );
1353
1354         attr_merge_one( e, ad_reqDN, &op->o_req_dn, &op->o_req_ndn );
1355
1356         if ( rs->sr_text ) {
1357                 ber_str2bv( rs->sr_text, 0, 0, &bv );
1358                 attr_merge_one( e, ad_reqMessage, &bv, NULL );
1359         }
1360         bv.bv_len = snprintf( timebuf, sizeof( timebuf ), "%d", rs->sr_err );
1361         if ( bv.bv_len >= 0 && bv.bv_len < sizeof( timebuf ) ) {
1362                 bv.bv_val = timebuf;
1363                 attr_merge_one( e, ad_reqResult, &bv, NULL );
1364         }
1365
1366         last_attr = attr_find( e->e_attrs, ad_reqResult );
1367
1368         switch( logop ) {
1369         case LOG_EN_ADD:
1370         case LOG_EN_DELETE: {
1371                 char c_op;
1372                 Entry *e2;
1373
1374                 if ( logop == LOG_EN_ADD ) {
1375                         e2 = op->ora_e;
1376                         c_op = '+';
1377                 } else {
1378                         if ( !old )
1379                                 break;
1380                         e2 = old;
1381                         c_op = 0;
1382                 }
1383                 /* count all the vals */
1384                 i = 0;
1385                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1386                         i += a->a_numvals;
1387                 }
1388                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1389                 i = 0;
1390                 for ( a=e2->e_attrs; a; a=a->a_next ) {
1391                         if ( a->a_vals ) {
1392                                 for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1393                                         accesslog_val2val( a->a_desc, b, c_op, &vals[i] );
1394                                 }
1395                         }
1396                 }
1397                 vals[i].bv_val = NULL;
1398                 vals[i].bv_len = 0;
1399                 a = attr_alloc( logop == LOG_EN_ADD ? ad_reqMod : ad_reqOld );
1400                 a->a_numvals = i;
1401                 a->a_vals = vals;
1402                 a->a_nvals = vals;
1403                 last_attr->a_next = a;
1404                 break;
1405         }
1406
1407         case LOG_EN_MODRDN:
1408         case LOG_EN_MODIFY:
1409                 /* count all the mods */
1410                 i = 0;
1411                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1412                         if ( m->sml_values ) {
1413                                 i += m->sml_numvals;
1414                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1415                                 m->sml_op == LDAP_MOD_REPLACE )
1416                         {
1417                                 i++;
1418                         }
1419                 }
1420                 vals = ch_malloc( (i+1) * sizeof( struct berval ));
1421                 i = 0;
1422
1423                 /* init flags on old entry */
1424                 if ( old ) {
1425                         for ( a = old->e_attrs; a; a = a->a_next ) {
1426                                 log_attr *la;
1427                                 a->a_flags = 0;
1428
1429                                 /* look for attrs that are always logged */
1430                                 for ( la = li->li_oldattrs; la; la = la->next ) {
1431                                         if ( a->a_desc == la->attr ) {
1432                                                 a->a_flags = 1;
1433                                         }
1434                                 }
1435                         }
1436                 }
1437
1438                 for ( m = op->orm_modlist; m; m = m->sml_next ) {
1439                         /* Mark this attribute as modified */
1440                         if ( old ) {
1441                                 a = attr_find( old->e_attrs, m->sml_desc );
1442                                 if ( a ) {
1443                                         a->a_flags = 1;
1444                                 }
1445                         }
1446
1447                         /* don't log the RDN mods; they're explicitly logged later */
1448                         if ( logop == LOG_EN_MODRDN &&
1449                                 ( m->sml_op == SLAP_MOD_SOFTADD ||
1450                                   m->sml_op == LDAP_MOD_DELETE ) )
1451                         {
1452                                 continue;
1453                         }
1454
1455                         if ( m->sml_values ) {
1456                                 for ( b = m->sml_values; !BER_BVISNULL( b ); b++, i++ ) {
1457                                         char c_op;
1458
1459                                         switch ( m->sml_op ) {
1460                                         case LDAP_MOD_ADD: c_op = '+'; break;
1461                                         case LDAP_MOD_DELETE:   c_op = '-'; break;
1462                                         case LDAP_MOD_REPLACE:  c_op = '='; break;
1463                                         case LDAP_MOD_INCREMENT:        c_op = '#'; break;
1464
1465                                         /* unknown op. there shouldn't be any of these. we
1466                                          * don't know what to do with it, but we shouldn't just
1467                                          * ignore it.
1468                                          */
1469                                         default: c_op = '?'; break;
1470                                         }
1471                                         accesslog_val2val( m->sml_desc, b, c_op, &vals[i] );
1472                                 }
1473                         } else if ( m->sml_op == LDAP_MOD_DELETE ||
1474                                 m->sml_op == LDAP_MOD_REPLACE )
1475                         {
1476                                 vals[i].bv_len = m->sml_desc->ad_cname.bv_len + 2;
1477                                 vals[i].bv_val = ch_malloc( vals[i].bv_len + 1 );
1478                                 ptr = lutil_strcopy( vals[i].bv_val,
1479                                         m->sml_desc->ad_cname.bv_val );
1480                                 *ptr++ = ':';
1481                                 if ( m->sml_op == LDAP_MOD_DELETE ) {
1482                                         *ptr++ = '-';
1483                                 } else {
1484                                         *ptr++ = '=';
1485                                 }
1486                                 *ptr = '\0';
1487                                 i++;
1488                         }
1489                 }
1490
1491                 if ( i > 0 ) {
1492                         BER_BVZERO( &vals[i] );
1493                         a = attr_alloc( ad_reqMod );
1494                         a->a_numvals = i;
1495                         a->a_vals = vals;
1496                         a->a_nvals = vals;
1497                         last_attr->a_next = a;
1498                         last_attr = a;
1499
1500                 } else {
1501                         ch_free( vals );
1502                 }
1503
1504                 if ( old ) {
1505                         /* count all the vals */
1506                         i = 0;
1507                         for ( a = old->e_attrs; a != NULL; a = a->a_next ) {
1508                                 if ( a->a_vals && a->a_flags ) {
1509                                         i += a->a_numvals;
1510                                 }
1511                         }
1512                         vals = ch_malloc( (i + 1) * sizeof( struct berval ) );
1513                         i = 0;
1514                         for ( a=old->e_attrs; a; a=a->a_next ) {
1515                                 if ( a->a_vals && a->a_flags ) {
1516                                         for (b=a->a_vals; !BER_BVISNULL( b ); b++,i++) {
1517                                                 accesslog_val2val( a->a_desc, b, 0, &vals[i] );
1518                                         }
1519                                 }
1520                         }
1521                         vals[i].bv_val = NULL;
1522                         vals[i].bv_len = 0;
1523                         a = attr_alloc( ad_reqOld );
1524                         a->a_numvals = i;
1525                         a->a_vals = vals;
1526                         a->a_nvals = vals;
1527                         last_attr->a_next = a;
1528                 }
1529                 if ( logop == LOG_EN_MODIFY ) {
1530                         break;
1531                 }
1532
1533                 /* Now log the actual modRDN info */
1534                 attr_merge_one( e, ad_reqNewRDN, &op->orr_newrdn, &op->orr_nnewrdn );
1535                 attr_merge_one( e, ad_reqDeleteOldRDN, op->orr_deleteoldrdn ?
1536                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1537                         NULL );
1538                 if ( op->orr_newSup ) {
1539                         attr_merge_one( e, ad_reqNewSuperior, op->orr_newSup, op->orr_nnewSup );
1540                 }
1541                 break;
1542
1543         case LOG_EN_COMPARE:
1544                 bv.bv_len = op->orc_ava->aa_desc->ad_cname.bv_len + 1 +
1545                         op->orc_ava->aa_value.bv_len;
1546                 bv.bv_val = op->o_tmpalloc( bv.bv_len+1, op->o_tmpmemctx );
1547                 ptr = lutil_strcopy( bv.bv_val, op->orc_ava->aa_desc->ad_cname.bv_val );
1548                 *ptr++ = '=';
1549                 AC_MEMCPY( ptr, op->orc_ava->aa_value.bv_val, op->orc_ava->aa_value.bv_len );
1550                 bv.bv_val[bv.bv_len] = '\0';
1551                 attr_merge_one( e, ad_reqAssertion, &bv, NULL );
1552                 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1553                 break;
1554
1555         case LOG_EN_SEARCH:
1556                 attr_merge_one( e, ad_reqScope, &scopes[op->ors_scope], NULL );
1557                 attr_merge_one( e, ad_reqDerefAliases, &derefs[op->ors_deref], NULL );
1558                 attr_merge_one( e, ad_reqAttrsOnly, op->ors_attrsonly ?
1559                         (struct berval *)&slap_true_bv : (struct berval *)&slap_false_bv,
1560                         NULL );
1561                 if ( !BER_BVISEMPTY( &op->ors_filterstr ))
1562                         attr_merge_one( e, ad_reqFilter, &op->ors_filterstr, NULL );
1563                 if ( op->ors_attrs ) {
1564                         /* count them */
1565                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1566                                 ;
1567                         vals = op->o_tmpalloc( (i+1) * sizeof(struct berval),
1568                                 op->o_tmpmemctx );
1569                         for (i=0; !BER_BVISNULL(&op->ors_attrs[i].an_name );i++)
1570                                 vals[i] = op->ors_attrs[i].an_name;
1571                         vals[i].bv_val = NULL;
1572                         vals[i].bv_len = 0;
1573                         attr_merge( e, ad_reqAttr, vals, NULL );
1574                         op->o_tmpfree( vals, op->o_tmpmemctx );
1575                 }
1576                 bv.bv_val = timebuf;
1577                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", rs->sr_nentries );
1578                 if ( bv.bv_len >= 0 && bv.bv_len < sizeof( timebuf ) ) {
1579                         attr_merge_one( e, ad_reqEntries, &bv, NULL );
1580                 } /* else? */
1581
1582                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->ors_tlimit );
1583                 if ( bv.bv_len >= 0 && bv.bv_len < sizeof( timebuf ) ) {
1584                         attr_merge_one( e, ad_reqTimeLimit, &bv, NULL );
1585                 } /* else? */
1586
1587                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->ors_slimit );
1588                 if ( bv.bv_len >= 0 && bv.bv_len < sizeof( timebuf ) ) {
1589                         attr_merge_one( e, ad_reqSizeLimit, &bv, NULL );
1590                 } /* else? */
1591                 break;
1592
1593         case LOG_EN_BIND:
1594                 bv.bv_val = timebuf;
1595                 bv.bv_len = snprintf( bv.bv_val, sizeof( timebuf ), "%d", op->o_protocol );
1596                 if ( bv.bv_len >= 0 && bv.bv_len < sizeof( timebuf ) ) {
1597                         attr_merge_one( e, ad_reqVersion, &bv, NULL );
1598                 } /* else? */
1599                 if ( op->orb_method == LDAP_AUTH_SIMPLE ) {
1600                         attr_merge_one( e, ad_reqMethod, &simple, NULL );
1601                 } else {
1602                         bv.bv_len = STRLENOF("SASL()") + op->orb_mech.bv_len;
1603                         bv.bv_val = op->o_tmpalloc( bv.bv_len + 1, op->o_tmpmemctx );
1604                         ptr = lutil_strcopy( bv.bv_val, "SASL(" );
1605                         ptr = lutil_strcopy( ptr, op->orb_mech.bv_val );
1606                         *ptr++ = ')';
1607                         *ptr = '\0';
1608                         attr_merge_one( e, ad_reqMethod, &bv, NULL );
1609                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
1610                 }
1611
1612                 break;
1613
1614         case LOG_EN_EXTENDED:
1615                 if ( op->ore_reqdata ) {
1616                         attr_merge_one( e, ad_reqData, op->ore_reqdata, NULL );
1617                 }
1618                 break;
1619
1620         case LOG_EN_UNKNOWN:
1621                 /* we don't know its parameters, don't add any */
1622                 break;
1623         }
1624
1625         op2.o_hdr = op->o_hdr;
1626         op2.o_tag = LDAP_REQ_ADD;
1627         op2.o_bd = li->li_db;
1628         op2.o_dn = li->li_db->be_rootdn;
1629         op2.o_ndn = li->li_db->be_rootndn;
1630         op2.o_req_dn = e->e_name;
1631         op2.o_req_ndn = e->e_nname;
1632         op2.ora_e = e;
1633         op2.o_callback = &nullsc;
1634
1635         if (( lo->mask & LOG_OP_WRITES ) && !BER_BVISEMPTY( &op->o_csn )) {
1636                 slap_queue_csn( &op2, &op->o_csn );
1637         }
1638
1639         op2.o_bd->be_add( &op2, &rs2 );
1640         if ( e == op2.ora_e ) entry_free( e );
1641         e = NULL;
1642
1643 done:
1644         if ( lo->mask & LOG_OP_WRITES )
1645                 ldap_pvt_thread_mutex_unlock( &li->li_log_mutex );
1646         if ( old ) entry_free( old );
1647         return SLAP_CB_CONTINUE;
1648 }
1649
1650 /* Since Bind success is sent by the frontend, it won't normally enter
1651  * the overlay response callback. Add another callback to make sure it
1652  * gets here.
1653  */
1654 static int
1655 accesslog_bind_resp( Operation *op, SlapReply *rs )
1656 {
1657         BackendDB *be, db;
1658         int rc;
1659         slap_callback *sc;
1660
1661         be = op->o_bd;
1662         db = *be;
1663         op->o_bd = &db;
1664         db.bd_info = op->o_callback->sc_private;
1665         rc = accesslog_response( op, rs );
1666         op->o_bd = be;
1667         sc = op->o_callback;
1668         op->o_callback = sc->sc_next;
1669         op->o_tmpfree( sc, op->o_tmpmemctx );
1670         return rc;
1671 }
1672
1673 static int
1674 accesslog_op_bind( Operation *op, SlapReply *rs )
1675 {
1676         slap_callback *sc;
1677
1678         sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1679         sc->sc_response = accesslog_bind_resp;
1680         sc->sc_private = op->o_bd->bd_info;
1681
1682         if ( op->o_callback ) {
1683                 sc->sc_next = op->o_callback->sc_next;
1684                 op->o_callback->sc_next = sc;
1685         } else {
1686                 op->o_callback = sc;
1687         }
1688         return SLAP_CB_CONTINUE;
1689 }
1690
1691 static int
1692 accesslog_mod_cleanup( Operation *op, SlapReply *rs )
1693 {
1694         slap_callback *sc = op->o_callback;
1695         slap_overinst *on = sc->sc_private;
1696         log_info *li = on->on_bi.bi_private;
1697         op->o_callback = sc->sc_next;
1698
1699         op->o_tmpfree( sc, op->o_tmpmemctx );
1700
1701         if ( li->li_unlock ) {
1702                 BackendInfo *bi = op->o_bd->bd_info;
1703                 op->o_bd->bd_info = (BackendInfo *)on;
1704                 accesslog_response( op, rs );
1705                 op->o_bd->bd_info = bi;
1706         }
1707         return 0;
1708 }
1709
1710 static int
1711 accesslog_op_mod( Operation *op, SlapReply *rs )
1712 {
1713         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1714         log_info *li = on->on_bi.bi_private;
1715
1716         if ( li->li_ops & LOG_OP_WRITES ) {
1717                 slap_callback *cb = op->o_tmpalloc( sizeof( slap_callback ), op->o_tmpmemctx );
1718                 cb->sc_cleanup = accesslog_mod_cleanup;
1719                 cb->sc_response = NULL;
1720                 cb->sc_private = on;
1721                 cb->sc_next = op->o_callback;
1722                 op->o_callback = cb;
1723
1724                 ldap_pvt_thread_rmutex_lock( &li->li_op_rmutex, op->o_tid );
1725                 li->li_unlock = 1;
1726                 if ( li->li_oldf && ( op->o_tag == LDAP_REQ_DELETE ||
1727                         op->o_tag == LDAP_REQ_MODIFY ||
1728                         ( op->o_tag == LDAP_REQ_MODRDN && li->li_oldattrs ))) {
1729                         int rc;
1730                         Entry *e;
1731
1732                         op->o_bd->bd_info = on->on_info->oi_orig;
1733                         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1734                         if ( e ) {
1735                                 if ( test_filter( op, e, li->li_oldf ) == LDAP_COMPARE_TRUE )
1736                                         li->li_old = entry_dup( e );
1737                                 be_entry_release_rw( op, e, 0 );
1738                         }
1739                         op->o_bd->bd_info = (BackendInfo *)on;
1740                 }
1741         }
1742         return SLAP_CB_CONTINUE;
1743 }
1744
1745 /* unbinds are broadcast to all backends; we only log it if this
1746  * backend was used for the original bind.
1747  */
1748 static int
1749 accesslog_unbind( Operation *op, SlapReply *rs )
1750 {
1751         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1752         if ( op->o_conn->c_authz_backend == on->on_info->oi_origdb ) {
1753                 log_info *li = on->on_bi.bi_private;
1754                 Operation op2 = {0};
1755                 void *cids[SLAP_MAX_CIDS];
1756                 SlapReply rs2 = {REP_RESULT};
1757                 Entry *e;
1758
1759                 if ( !( li->li_ops & LOG_OP_UNBIND ))
1760                         return SLAP_CB_CONTINUE;
1761
1762                 e = accesslog_entry( op, rs, LOG_EN_UNBIND, &op2 );
1763                 op2.o_hdr = op->o_hdr;
1764                 op2.o_tag = LDAP_REQ_ADD;
1765                 op2.o_bd = li->li_db;
1766                 op2.o_dn = li->li_db->be_rootdn;
1767                 op2.o_ndn = li->li_db->be_rootndn;
1768                 op2.o_req_dn = e->e_name;
1769                 op2.o_req_ndn = e->e_nname;
1770                 op2.ora_e = e;
1771                 op2.o_callback = &nullsc;
1772                 op2.o_controls = cids;
1773                 memset(cids, 0, sizeof( cids ));
1774
1775                 op2.o_bd->be_add( &op2, &rs2 );
1776                 if ( e == op2.ora_e )
1777                         entry_free( e );
1778         }
1779         return SLAP_CB_CONTINUE;
1780 }
1781
1782 static int
1783 accesslog_abandon( Operation *op, SlapReply *rs )
1784 {
1785         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1786         log_info *li = on->on_bi.bi_private;
1787         Operation op2 = {0};
1788         void *cids[SLAP_MAX_CIDS];
1789         SlapReply rs2 = {REP_RESULT};
1790         Entry *e;
1791         char buf[64];
1792         struct berval bv;
1793
1794         if ( !op->o_time || !( li->li_ops & LOG_OP_ABANDON ))
1795                 return SLAP_CB_CONTINUE;
1796
1797         e = accesslog_entry( op, rs, LOG_EN_ABANDON, &op2 );
1798         bv.bv_val = buf;
1799         bv.bv_len = snprintf( buf, sizeof( buf ), "%d", op->orn_msgid );
1800         if ( bv.bv_len >= 0 && bv.bv_len < sizeof( buf ) ) {
1801                 attr_merge_one( e, ad_reqId, &bv, NULL );
1802         } /* else? */
1803
1804         op2.o_hdr = op->o_hdr;
1805         op2.o_tag = LDAP_REQ_ADD;
1806         op2.o_bd = li->li_db;
1807         op2.o_dn = li->li_db->be_rootdn;
1808         op2.o_ndn = li->li_db->be_rootndn;
1809         op2.o_req_dn = e->e_name;
1810         op2.o_req_ndn = e->e_nname;
1811         op2.ora_e = e;
1812         op2.o_callback = &nullsc;
1813         op2.o_controls = cids;
1814         memset(cids, 0, sizeof( cids ));
1815
1816         op2.o_bd->be_add( &op2, &rs2 );
1817         if ( e == op2.ora_e )
1818                 entry_free( e );
1819
1820         return SLAP_CB_CONTINUE;
1821 }
1822
1823 static int
1824 accesslog_operational( Operation *op, SlapReply *rs )
1825 {
1826         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1827         log_info *li = on->on_bi.bi_private;
1828
1829         if ( op->o_sync != SLAP_CONTROL_NONE )
1830                 return SLAP_CB_CONTINUE;
1831
1832         if ( rs->sr_entry != NULL
1833                 && dn_match( &op->o_bd->be_nsuffix[0], &rs->sr_entry->e_nname ) )
1834         {
1835                 Attribute       **ap;
1836
1837                 for ( ap = &rs->sr_operational_attrs; *ap; ap = &(*ap)->a_next )
1838                         /* just count */ ;
1839
1840                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
1841                                 ad_inlist( ad_auditContext, rs->sr_attrs ) )
1842                 {
1843                         *ap = attr_alloc( ad_auditContext );
1844                         attr_valadd( *ap,
1845                                 &li->li_db->be_suffix[0],
1846                                 &li->li_db->be_nsuffix[0], 1 );
1847                 }
1848         }
1849
1850         return SLAP_CB_CONTINUE;
1851 }
1852
1853 static slap_overinst accesslog;
1854
1855 static int
1856 accesslog_db_init(
1857         BackendDB *be,
1858         ConfigReply *cr
1859 )
1860 {
1861         slap_overinst *on = (slap_overinst *)be->bd_info;
1862         log_info *li = ch_calloc(1, sizeof(log_info));
1863
1864         on->on_bi.bi_private = li;
1865         ldap_pvt_thread_rmutex_init( &li->li_op_rmutex );
1866         ldap_pvt_thread_mutex_init( &li->li_log_mutex );
1867         return 0;
1868 }
1869
1870 static int
1871 accesslog_db_destroy(
1872         BackendDB *be,
1873         ConfigReply *cr
1874 )
1875 {
1876         slap_overinst *on = (slap_overinst *)be->bd_info;
1877         log_info *li = on->on_bi.bi_private;
1878         log_attr *la;
1879
1880         if ( li->li_oldf )
1881                 filter_free( li->li_oldf );
1882         for ( la=li->li_oldattrs; la; la=li->li_oldattrs ) {
1883                 li->li_oldattrs = la->next;
1884                 ch_free( la );
1885         }
1886         ldap_pvt_thread_mutex_destroy( &li->li_log_mutex );
1887         ldap_pvt_thread_rmutex_destroy( &li->li_op_rmutex );
1888         free( li );
1889         return LDAP_SUCCESS;
1890 }
1891
1892 /* Create the logdb's root entry if it's missing */
1893 static void *
1894 accesslog_db_root(
1895         void *ctx,
1896         void *arg )
1897 {
1898         struct re_s *rtask = arg;
1899         slap_overinst *on = rtask->arg;
1900         log_info *li = on->on_bi.bi_private;
1901
1902         Connection conn = {0};
1903         OperationBuffer opbuf;
1904         Operation *op;
1905
1906         Entry *e;
1907         int rc;
1908
1909         connection_fake_init( &conn, &opbuf, ctx );
1910         op = &opbuf.ob_op;
1911         op->o_bd = li->li_db;
1912         op->o_dn = li->li_db->be_rootdn;
1913         op->o_ndn = li->li_db->be_rootndn;
1914         rc = be_entry_get_rw( op, li->li_db->be_nsuffix, NULL, NULL, 0, &e );
1915
1916         if ( e ) {
1917                 be_entry_release_rw( op, e, 0 );
1918
1919         } else {
1920                 SlapReply rs = {REP_RESULT};
1921                 struct berval rdn, nrdn, attr;
1922                 char *ptr;
1923                 AttributeDescription *ad = NULL;
1924                 const char *text = NULL;
1925                 Entry *e_ctx;
1926
1927                 e = entry_alloc();
1928                 ber_dupbv( &e->e_name, li->li_db->be_suffix );
1929                 ber_dupbv( &e->e_nname, li->li_db->be_nsuffix );
1930
1931                 attr_merge_one( e, slap_schema.si_ad_objectClass,
1932                         &log_container->soc_cname, NULL );
1933
1934                 dnRdn( &e->e_name, &rdn );
1935                 dnRdn( &e->e_nname, &nrdn );
1936                 ptr = ber_bvchr( &rdn, '=' );
1937
1938                 assert( ptr != NULL );
1939
1940                 attr.bv_val = rdn.bv_val;
1941                 attr.bv_len = ptr - rdn.bv_val;
1942
1943                 slap_bv2ad( &attr, &ad, &text );
1944
1945                 rdn.bv_val = ptr+1;
1946                 rdn.bv_len -= attr.bv_len + 1;
1947                 ptr = ber_bvchr( &nrdn, '=' );
1948                 nrdn.bv_len -= ptr - nrdn.bv_val + 1;
1949                 nrdn.bv_val = ptr+1;
1950                 attr_merge_one( e, ad, &rdn, &nrdn );
1951
1952                 /* Get contextCSN from main DB */
1953                 op->o_bd = on->on_info->oi_origdb;
1954                 rc = be_entry_get_rw( op, op->o_bd->be_nsuffix, NULL,
1955                         slap_schema.si_ad_contextCSN, 0, &e_ctx );
1956
1957                 if ( e_ctx ) {
1958                         Attribute *a;
1959
1960                         a = attr_find( e_ctx->e_attrs, slap_schema.si_ad_contextCSN );
1961                         if ( a ) {
1962                                 /* FIXME: contextCSN could have multiple values!
1963                                  * should select the one with the server's SID */
1964                                 attr_merge_one( e, slap_schema.si_ad_entryCSN,
1965                                         &a->a_vals[0], &a->a_nvals[0] );
1966                                 attr_merge( e, a->a_desc, a->a_vals, a->a_nvals );
1967                         }
1968                         be_entry_release_rw( op, e_ctx, 0 );
1969                 }
1970                 op->o_bd = li->li_db;
1971
1972                 op->ora_e = e;
1973                 op->o_req_dn = e->e_name;
1974                 op->o_req_ndn = e->e_nname;
1975                 op->o_callback = &nullsc;
1976                 SLAP_DBFLAGS( op->o_bd ) |= SLAP_DBFLAG_NOLASTMOD;
1977                 rc = op->o_bd->be_add( op, &rs );
1978                 SLAP_DBFLAGS( op->o_bd ) ^= SLAP_DBFLAG_NOLASTMOD;
1979                 if ( e == op->ora_e )
1980                         entry_free( e );
1981         }
1982         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1983         ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1984         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1985         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1986
1987         return NULL;
1988 }
1989
1990 static int
1991 accesslog_db_open(
1992         BackendDB *be,
1993         ConfigReply *cr
1994 )
1995 {
1996         slap_overinst *on = (slap_overinst *)be->bd_info;
1997         log_info *li = on->on_bi.bi_private;
1998
1999
2000         if ( !BER_BVISEMPTY( &li->li_db_suffix )) {
2001                 li->li_db = select_backend( &li->li_db_suffix, 0 );
2002                 ch_free( li->li_db_suffix.bv_val );
2003                 BER_BVZERO( &li->li_db_suffix );
2004         }
2005         if ( li->li_db == NULL ) {
2006                 Debug( LDAP_DEBUG_ANY,
2007                         "accesslog: \"logdb <suffix>\" missing or invalid.\n",
2008                         0, 0, 0 );
2009                 return 1;
2010         }
2011
2012         if ( slapMode & SLAP_TOOL_MODE )
2013                 return 0;
2014
2015         if ( BER_BVISEMPTY( &li->li_db->be_rootndn )) {
2016                 ber_dupbv( &li->li_db->be_rootdn, li->li_db->be_suffix );
2017                 ber_dupbv( &li->li_db->be_rootndn, li->li_db->be_nsuffix );
2018         }
2019
2020         ldap_pvt_runqueue_insert( &slapd_rq, 3600, accesslog_db_root, on,
2021                 "accesslog_db_root", li->li_db->be_suffix[0].bv_val );
2022
2023         return 0;
2024 }
2025
2026 int accesslog_initialize()
2027 {
2028         int i, rc;
2029
2030         accesslog.on_bi.bi_type = "accesslog";
2031         accesslog.on_bi.bi_db_init = accesslog_db_init;
2032         accesslog.on_bi.bi_db_destroy = accesslog_db_destroy;
2033         accesslog.on_bi.bi_db_open = accesslog_db_open;
2034
2035         accesslog.on_bi.bi_op_add = accesslog_op_mod;
2036         accesslog.on_bi.bi_op_bind = accesslog_op_bind;
2037         accesslog.on_bi.bi_op_delete = accesslog_op_mod;
2038         accesslog.on_bi.bi_op_modify = accesslog_op_mod;
2039         accesslog.on_bi.bi_op_modrdn = accesslog_op_mod;
2040         accesslog.on_bi.bi_op_unbind = accesslog_unbind;
2041         accesslog.on_bi.bi_op_abandon = accesslog_abandon;
2042         accesslog.on_bi.bi_operational = accesslog_operational;
2043         accesslog.on_response = accesslog_response;
2044
2045         accesslog.on_bi.bi_cf_ocs = log_cfocs;
2046
2047         nullsc.sc_response = slap_null_cb;
2048
2049         rc = config_register_schema( log_cfats, log_cfocs );
2050         if ( rc ) return rc;
2051
2052         /* log schema integration */
2053         for ( i=0; lsyntaxes[i].oid; i++ ) {
2054                 int code;
2055
2056                 code = register_syntax( &lsyntaxes[ i ].syn );
2057                 if ( code != 0 ) {
2058                         Debug( LDAP_DEBUG_ANY,
2059                                 "accesslog_init: register_syntax failed\n",
2060                                 0, 0, 0 );
2061                         return code;
2062                 }
2063
2064                 if ( lsyntaxes[i].mrs != NULL ) {
2065                         code = mr_make_syntax_compat_with_mrs(
2066                                 lsyntaxes[i].oid, lsyntaxes[i].mrs );
2067                         if ( code < 0 ) {
2068                                 Debug( LDAP_DEBUG_ANY,
2069                                         "accesslog_init: "
2070                                         "mr_make_syntax_compat_with_mrs "
2071                                         "failed\n",
2072                                         0, 0, 0 );
2073                                 return code;
2074                         }
2075                 }
2076         }
2077
2078         for ( i=0; lattrs[i].at; i++ ) {
2079                 int code;
2080
2081                 code = register_at( lattrs[i].at, lattrs[i].ad, 0 );
2082                 if ( code ) {
2083                         Debug( LDAP_DEBUG_ANY,
2084                                 "accesslog_init: register_at failed\n",
2085                                 0, 0, 0 );
2086                         return -1;
2087                 }
2088 #ifndef LDAP_DEVEL
2089                 (*lattrs[i].ad)->ad_type->sat_flags |= SLAP_AT_HIDE;
2090 #endif
2091         }
2092
2093         for ( i=0; locs[i].ot; i++ ) {
2094                 int code;
2095
2096                 code = register_oc( locs[i].ot, locs[i].oc, 0 );
2097                 if ( code ) {
2098                         Debug( LDAP_DEBUG_ANY,
2099                                 "accesslog_init: register_oc failed\n",
2100                                 0, 0, 0 );
2101                         return -1;
2102                 }
2103 #ifndef LDAP_DEVEL
2104                 (*locs[i].oc)->soc_flags |= SLAP_OC_HIDE;
2105 #endif
2106         }
2107
2108         return overlay_register(&accesslog);
2109 }
2110
2111 #if SLAPD_OVER_ACCESSLOG == SLAPD_MOD_DYNAMIC
2112 int
2113 init_module( int argc, char *argv[] )
2114 {
2115         return accesslog_initialize();
2116 }
2117 #endif
2118
2119 #endif /* SLAPD_OVER_ACCESSLOG */