1/*  Copyright (C) 1996 N.M. Maclaren
2    Copyright (C) 1996 The University of Cambridge
3
4This includes code that really should have been part of ANSI/ISO C, but was
5left out for historical reasons (despite requests to define ftty), plus
6the get_lock() and log_message() functions.
7*/
8
9#include "header.h"
10
11#include <sys/types.h>
12#include <unistd.h>
13#include <syslog.h>
14#include <signal.h>
15
16#define UNIX
17#include "kludges.h"
18#undef UNIX
19
20
21void do_nothing (int seconds) {
22
23/* Wait for a fixed period, possibly uninterruptibly.  This should not wait
24for less than the specified period, if that can be avoided. */
25
26    sleep((unsigned int)(seconds+2));          /* +2 is enough for POSIX */
27}
28
29
30
31int ftty (FILE *file) {
32
33/* Return whether the file is attached to an interactive device. */
34
35    return isatty(fileno(file));
36}
37
38
39
40void set_lock (int lock) {
41
42/* Check that we have enough privileges to reset the time and that no other
43updating msntp process is running, but don't bother with fancy interlocking.
44This function is really only to permit the daemon mode to be restarted in a
45cron job and improve the diagnostics; it can be replaced by a 'return'
46statement if it causes implementation difficulties.  Note that there is little
47point in clearing the lock under Unix, but do so anyway. */
48
49    FILE *file;
50    long pid;
51
52    if (lockname == NULL || lockname[0] == '\0') return;
53    if (lock) {
54        errno = 0;
55        if ((file = fopen(lockname,"r")) != NULL &&
56                fscanf(file,"%ld",&pid) == 1 && kill(pid,0) == 0) {
57            if (verbose || isatty(STDIN_FILENO) || isatty(STDOUT_FILENO))
58                fatal(0,"another msntp process is currently running",NULL);
59            else
60                fatal(0,NULL,NULL);
61        }
62        if (file != NULL) fclose(file);
63        errno = 0;
64        if ((file = fopen(lockname,"w")) == NULL ||
65                fprintf(file,"%ld\n",(long)getpid()) <= 0 ||
66                ferror(file) || fclose(file) != 0)
67            fatal(1,"unable to write PID to %s",lockname);
68        adjust_time(0.0,1,0.0);
69    } else {
70        errno = 0;
71        if (remove(lockname) != 0)
72            fatal(1,"unable to remove the msntp lockname %s",lockname);
73    }
74}
75
76
77
78/*
79 * Log a message, crudely.
80 * This is used in only one place, but could be used more widely.
81 */
82
83void
84log_message (const char *message)
85{
86
87    syslog(
88#ifdef LOG_DAEMON
89	LOG_DAEMON |
90#endif
91	LOG_WARNING, "%s", message);
92}
93