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