xref: /freebsd/contrib/sendmail/libsmutil/lockfile.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
1 /*
2  * Copyright (c) 1998-2000 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #ifndef lint
15 static char id[] = "@(#)$Id: lockfile.c,v 8.3.16.11 2000/11/16 02:54:28 geir Exp $";
16 #endif /* ! lint */
17 
18 #include <sendmail.h>
19 
20 /*
21 **  LOCKFILE -- lock a file using flock or (shudder) fcntl locking
22 **
23 **	Parameters:
24 **		fd -- the file descriptor of the file.
25 **		filename -- the file name (for error messages). [unused]
26 **		ext -- the filename extension. [unused]
27 **		type -- type of the lock.  Bits can be:
28 **			LOCK_EX -- exclusive lock.
29 **			LOCK_NB -- non-blocking.
30 **			LOCK_UN -- unlock.
31 **
32 **	Returns:
33 **		TRUE if the lock was acquired.
34 **		FALSE otherwise.
35 */
36 
37 bool
38 lockfile(fd, filename, ext, type)
39 	int fd;
40 	char *filename;
41 	char *ext;
42 	int type;
43 {
44 #if !HASFLOCK
45 	int action;
46 	struct flock lfd;
47 	extern int errno;
48 
49 	memset(&lfd, '\0', sizeof lfd);
50 	if (bitset(LOCK_UN, type))
51 		lfd.l_type = F_UNLCK;
52 	else if (bitset(LOCK_EX, type))
53 		lfd.l_type = F_WRLCK;
54 	else
55 		lfd.l_type = F_RDLCK;
56 	if (bitset(LOCK_NB, type))
57 		action = F_SETLK;
58 	else
59 		action = F_SETLKW;
60 
61 	if (fcntl(fd, action, &lfd) >= 0)
62 		return TRUE;
63 
64 	/*
65 	**  On SunOS, if you are testing using -oQ/tmp/mqueue or
66 	**  -oA/tmp/aliases or anything like that, and /tmp is mounted
67 	**  as type "tmp" (that is, served from swap space), the
68 	**  previous fcntl will fail with "Invalid argument" errors.
69 	**  Since this is fairly common during testing, we will assume
70 	**  that this indicates that the lock is successfully grabbed.
71 	*/
72 
73 	if (errno == EINVAL)
74 		return TRUE;
75 
76 #else /* !HASFLOCK */
77 
78 	if (flock(fd, type) >= 0)
79 		return TRUE;
80 
81 #endif /* !HASFLOCK */
82 
83 	return FALSE;
84 }
85