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