summaryrefslogtreecommitdiffstats
path: root/btimed.c
blob: 0a3b6093a3575a4aa1c88c463def80f025b2bac9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "btime_int.h"

static unsigned int get_btime(void);

int
main(int argc, char **argv)
{
	int sd;
	char inmsg[BTIME_MSGLEN];
	char outmsg[BTIME_MSGLEN];
	struct sockaddr_in cli_addr;
	int cli_addr_len;
	ssize_t nbytes;

	openlog("btimed", LOG_PID, LOG_USER);

	/* Running out of (x)inetd the socket was duped onto stdin. */
	sd = fileno(stdin);

	/* We want to exit after 30 seconds of inactivity */
	alarm(30);

	/* Generate the standard btime message */
	memset(outmsg, 0, BTIME_MSGLEN);
	sprintf(outmsg, "%u\n", get_btime());

	for (;;) {
		memset(&cli_addr, 0, sizeof cli_addr);
		cli_addr_len = sizeof cli_addr;
		nbytes = recvfrom(sd, &inmsg, BTIME_MSGLEN, MSG_WAITALL, 
		         (struct sockaddr *)&cli_addr, &cli_addr_len);

		sendto(sd, &outmsg, BTIME_MSGLEN, MSG_DONTWAIT, 
		       (struct sockaddr *)&cli_addr, cli_addr_len);
		/* We want to exit after 30 seconds of inactivity */
		alarm(30);
	}

	return 0;
}


/*
 *---------------------------------------------------------------------------
 *
 * get_btime --
 *
 *	Return machine's boot time.
 *
 * Returns:
 *	0 on failure
 * 	non-zero on success.
 *
 *---------------------------------------------------------------------------
 */

static unsigned int 
get_btime(void)
{
	FILE *statf;
	char line[1024];
	unsigned int btime = 0;

	if ((statf = fopen("/proc/stat", "r")) == NULL) {
		syslog(LOG_ERR, "/proc/stat open failure: %s\n", 
		        strerror(errno));
		exit(1);
	}

	while (fgets(line, 1024, statf) != NULL) {
		if (strstr(line, "btime") != NULL) {
			sscanf(line, "%*s%u", &btime); 
		}
			
	}

	fclose(statf);

	return btime;
}