#include "mt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <wait.h>
#include <fcntl.h>
#include <thread.h>
#include <unistd.h>
#include <errno.h>
#include <ucontext.h>
#include <syslog.h>
#include <rpcsvc/daemon_utils.h>
static int open_daemon_lock(const char *, int);
int
_check_daemon_lock(const char *name)
{
int fd, err;
struct flock lock;
if ((fd = open_daemon_lock(name, O_RDONLY)) == -1) {
if (errno == ENOENT)
return (0);
return (-1);
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = (off_t)0;
lock.l_len = (off_t)0;
err = fcntl(fd, F_GETLK, &lock);
(void) close(fd);
if (err == -1)
return (-1);
return ((lock.l_type == F_UNLCK) ? 0 : 1);
}
static int
open_daemon_lock(const char *name, int mode)
{
char lock_file[MAXPATHLEN], buf[MAXPATHLEN];
int fd;
char *p;
(void) strncpy(buf, name, MAXPATHLEN);
p = strrchr(buf, ':');
if (p != NULL)
*p = '\0';
p = strrchr(buf, '/');
if (p == NULL)
p = buf;
else {
*p = '-';
p = strrchr(buf, '/');
if (p == NULL)
p = buf;
else
p++;
}
(void) snprintf(lock_file, MAXPATHLEN, "/etc/svc/volatile/%s.lock", p);
if ((fd = open(lock_file, mode, 0644)) == -1)
return (-1);
if (mode & O_CREAT)
(void) fchmod(fd, 0644);
return (fd);
}
pid_t
_enter_daemon_lock(const char *name)
{
int fd;
pid_t pid;
char line[BUFSIZ];
struct flock lock;
pid = getpid();
(void) snprintf(line, sizeof (line), "%ld\n", pid);
if ((fd = open_daemon_lock(name, O_RDWR|O_CREAT)) == -1)
return ((pid_t)-1);
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = (off_t)0;
lock.l_len = (off_t)0;
if (fcntl(fd, F_SETLK, &lock) == -1) {
if (fcntl(fd, F_GETLK, &lock) == -1) {
(void) close(fd);
return ((pid_t)-1);
}
(void) close(fd);
return (lock.l_pid);
}
if (write(fd, line, strlen(line)) == -1) {
(void) close(fd);
return ((pid_t)-1);
}
return ((pid_t)0);
}
int
_create_daemon_lock(const char *name, uid_t uid, gid_t gid)
{
int fd = open_daemon_lock(name, O_CREAT);
int ret;
if (fd < 0)
return (-1);
ret = fchown(fd, uid, gid);
(void) close(fd);
return (ret);
}