]> git.sur5r.net Git - openldap/blob - servers/slapd/lock.c
Happy New Year
[openldap] / servers / slapd / lock.c
1 /* lock.c - routines to open and apply an advisory lock to a file */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2018 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms are permitted
20  * provided that this notice is preserved and that due credit is given
21  * to the University of Michigan at Ann Arbor. The name of the University
22  * may not be used to endorse or promote products derived from this
23  * software without specific prior written permission. This software
24  * is provided ``as is'' without express or implied warranty.
25  */
26
27 #include "portable.h"
28
29 #include <stdio.h>
30
31 #include <ac/string.h>
32 #include <ac/socket.h>
33 #include <ac/time.h>
34 #include <ac/unistd.h>
35
36 #ifdef HAVE_SYS_FILE_H
37 #include <sys/file.h>
38 #endif
39
40 #include "slap.h"
41 #include <lutil.h>
42
43 FILE *
44 lock_fopen( const char *fname, const char *type, FILE **lfp )
45 {
46         FILE    *fp;
47         char    buf[MAXPATHLEN];
48
49         /* open the lock file */
50         snprintf( buf, sizeof buf, "%s.lock", fname );
51
52         if ( (*lfp = fopen( buf, "w" )) == NULL ) {
53                 Debug( LDAP_DEBUG_ANY, "could not open \"%s\"\n", buf, 0, 0 );
54
55                 return( NULL );
56         }
57
58         /* acquire the lock */
59         ldap_lockf( fileno(*lfp) );
60
61         /* open the log file */
62         if ( (fp = fopen( fname, type )) == NULL ) {
63                 Debug( LDAP_DEBUG_ANY, "could not open \"%s\"\n", fname, 0, 0 );
64
65                 ldap_unlockf( fileno(*lfp) );
66                 fclose( *lfp );
67                 *lfp = NULL;
68                 return( NULL );
69         }
70
71         return( fp );
72 }
73
74 int
75 lock_fclose( FILE *fp, FILE *lfp )
76 {
77         int rc = fclose( fp );
78         /* unlock */
79         ldap_unlockf( fileno(lfp) );
80         fclose( lfp );
81
82         return( rc );
83 }