1/* dumpleases.c - Dump the leases granted by udhcpd.
2 *
3 * Copyright 2013 Sandeep Sharma <sandeep.jack2756@gmail.com>
4 * Copyright 2013 Kyungwan Han <asura321@gmail.com>
5 *
6
7USE_DUMPLEASES(NEWTOY(dumpleases, ">0arf:[!ar]", TOYFLAG_USR|TOYFLAG_BIN))
8
9config DUMPLEASES
10  bool "dumpleases"
11  default n
12  help
13    usage: dumpleases [-r|-a] [-f LEASEFILE]
14
15    Display DHCP leases granted by udhcpd
16    -f FILE,  Lease file
17    -r        Show remaining time
18    -a        Show expiration time
19*/
20
21#define FOR_dumpleases
22#include "toys.h"
23
24GLOBALS(
25    char *file;
26)
27
28//lease structure
29struct lease {
30  uint32_t expires;
31  uint32_t lease_nip;
32  uint8_t lease_mac[6];
33  char hostname[20];
34  uint8_t pad[2]; //Padding
35};
36
37void dumpleases_main(void)
38{
39  struct in_addr addr;
40  struct lease lease_struct;
41  int64_t written_time , current_time, exp;
42  int i, fd;
43
44  if(!(toys.optflags & FLAG_f)) TT.file = "/var/lib/misc/dhcpd.leases"; //DEF_LEASE_FILE
45  fd = xopenro(TT.file);
46  xprintf("Mac Address       IP Address      Host Name           Expires %s\n", (toys.optflags & FLAG_a) ? "at" : "in");
47  xread(fd, &written_time, sizeof(written_time));
48  current_time = time(NULL);
49  written_time = SWAP_BE64(written_time);
50  if(current_time < written_time) written_time = current_time;
51
52  while(sizeof(lease_struct) ==
53      (readall(fd, &lease_struct, sizeof(lease_struct)))) {
54    for (i = 0; i < 6; i++) printf(":%02x"+ !i, lease_struct.lease_mac[i]);
55
56    addr.s_addr = lease_struct.lease_nip;
57    lease_struct.hostname[19] = '\0';
58    xprintf(" %-16s%-20s", inet_ntoa(addr), lease_struct.hostname );
59    exp = ntohl(lease_struct.expires) + written_time;
60    if (exp <= current_time) {
61      xputs("expired");
62      continue;
63    }
64    if (!(toys.optflags & FLAG_a)) {
65      unsigned dt, hr, m;
66      unsigned expires = exp - current_time;
67      dt = expires / (24*60*60); expires %= (24*60*60);
68      hr = expires / (60*60); expires %= (60*60);
69      m = expires / 60; expires %= 60;
70      if (dt) xprintf("%u days ", dt);
71      xprintf("%02u:%02u:%02u\n", hr, m, (unsigned)expires);
72    } else {
73      fputs(ctime((const time_t*)&exp), stdout);
74    }
75  }
76  xclose(fd);
77}
78