#include <config.h>
#include <sys/types.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#ifdef HAVE_STDBOOL_H
# include <stdbool.h>
#else
# include "compat/stdbool.h"
#endif
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include "sudo_compat.h"
#include "sudo_util.h"
#include "sudo_debug.h"
#ifdef HAVE_LOCKF
bool
sudo_lock_file_v1(int fd, int type)
{
return sudo_lock_region_v1(fd, type, 0);
}
bool
sudo_lock_region_v1(int fd, int type, off_t len)
{
int op;
debug_decl(sudo_lock_region, SUDO_DEBUG_UTIL)
switch (type) {
case SUDO_LOCK:
op = F_LOCK;
break;
case SUDO_TLOCK:
op = F_TLOCK;
break;
case SUDO_UNLOCK:
op = F_ULOCK;
break;
default:
errno = EINVAL;
debug_return_bool(false);
}
debug_return_bool(lockf(fd, op, len) == 0);
}
#else
bool
sudo_lock_file_v1(int fd, int type)
{
return sudo_lock_region_v1(fd, type, 0);
}
bool
sudo_lock_region_v1(int fd, int type, off_t len)
{
struct flock lock;
int func;
debug_decl(sudo_lock_file, SUDO_DEBUG_UTIL)
switch (type) {
case SUDO_LOCK:
lock.l_type = F_WRLCK;
func = F_SETLKW;
break;
case SUDO_TLOCK:
lock.l_type = F_WRLCK;
func = F_SETLK;
break;
case SUDO_UNLOCK:
lock.l_type = F_UNLCK;
func = F_SETLK;
break;
default:
errno = EINVAL;
debug_return_bool(false);
}
lock.l_start = 0;
lock.l_len = len;
lock.l_pid = 0;
lock.l_whence = len ? SEEK_CUR : SEEK_SET;
debug_return_bool(fcntl(fd, func, &lock) == 0);
}
#endif