/*
 *  libmodem library, a modem control facility.
 *
 *  mdmlock.c - modem lock files
 *
 *  Copyright (C) 1994, 1995  Riccardo Facchetti
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  You can contact the author at this e-mail address:
 *
 *  riccardo@cdc8g5.cdc.polimi.it
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#include <dial/modems.h>

#define BUFS    128

char *__mdmlock = "mdmlock.c (C) Riccardo Facchetti, version " LIBMODEM_VER;

static char buffer[BUFS];
static char buffer1[BUFS];

int mdm_lock(struct modems *device) {
    int fd;
    int lpid;

/*
 * build the lockfile pathname
 */
    sprintf(buffer, "%s/LCK..%s", LOCKDIR, device->line);

/*
 * check if line is alredy locked
 */
reopen_lock:
    if ((fd = open(buffer, O_CREAT|O_WRONLY|O_EXCL)) == -1) {
/*
 * the lock exist. Get the pid and check if the process lpid exist.
 * If not, remove the stale lock
 */
        fd = open (buffer, O_RDONLY);
        read(fd, buffer1, BUFS);
        close(fd);
        sscanf(buffer1, "%10d", &lpid);

        if (kill(lpid, SIGUSR1) == 0)
            return FAILURE;
        unlink(buffer);
        goto reopen_lock;
    }

    fchmod(fd, 0644);
/*
 * lock the line
 */
    sprintf(buffer, "%10d\n", getpid());
    write(fd, buffer, strlen(buffer));
    close(fd);
    return SUCCESS;
}

int mdm_unlock(struct modems *device) {

/*
 * build the lockfile pathname
 */
    sprintf(buffer, "%s/LCK..%s", LOCKDIR, device->line);
    
    if (unlink(buffer) == -1)
        return FAILURE;
    return SUCCESS;
}

int mdm_chklock(struct modems *device) {
    int fd;
    int lpid;

/*
 * build the lockfile pathname
 */
    sprintf(buffer, "%s/LCK..%s", LOCKDIR, device->line);
    
    if (access(buffer, F_OK) == -1)
        return FAILURE;

/*
 * the lock exist. Get the pid and check if the process lpid exist.
 * If not, remove the stale lock
 */
    fd = open (buffer, O_RDONLY);
    read(fd, buffer1, BUFS);
    close(fd);
    sscanf(buffer1, "%10d", &lpid);

    if (kill(lpid, SIGUSR1) == 0)
        return SUCCESS;

    unlink(buffer);

    return FAILURE;
}
