summaryrefslogtreecommitdiff
path: root/src/misc/s6-linux-init-logouthookd.c
blob: cc542bac37bfa2cd6f0a96364013306aba8d89ef (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
/* ISC license. */

#include <skalibs/sysdeps.h>

#ifndef SKALIBS_HASSOPEERCRED
#error "The SO_PEERCRED option to getsockopt() is required."
#endif

#include <skalibs/nonposix.h>

#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <utmpx.h>

#include <skalibs/allreadwrite.h>
#include <skalibs/strerr2.h>

#ifndef UT_NAMESIZE
#define UT_NAMESIZE 32
#endif

#ifndef UT_HOSTSIZE
#define UT_HOSTSIZE 256
#endif

int main (void)
{
  struct utmpx *utx ;
  struct ucred client ;
  socklen_t len = sizeof(client) ;
  ssize_t r ;
  char c ;

  close(1) ;
  if (getsockopt(0, SOL_SOCKET, SO_PEERCRED, &client, &len) == -1)
    strerr_diefu1sys(111, "getsockopt") ;

 /* Only take connections from root. */
  if (client.uid) return 1 ;

 /* Wait for the client to die. */
  r = fd_read(0, &c, 1) ;
  if (r < 0) strerr_diefu1sys(111, "read from stdin") ;
  if (r) strerr_dief1x(2, "client attempted to write") ;

 /* Clean up utmpx record for the client's pid, then exit. */
  for (;;)
  {
    errno = 0 ;
    utx = getutxent() ;
    if (!utx) break ;
    if (utx->ut_pid == client.pid) goto gotit ;
  }
  if (errno) strerr_diefu1sys(111, "getutxent") ;
  return 0 ;

 gotit:
  utx->ut_type = DEAD_PROCESS ;
  memset(utx->ut_user, 0, UT_NAMESIZE) ;
  memset(utx->ut_host, 0, UT_HOSTSIZE) ;
  utx->ut_tv.tv_sec = 0 ;
  utx->ut_tv.tv_usec = 0 ;
  setutxent() ;
  if (!pututxline(utx)) strerr_diefu1sys(111, "pututxline") ;
  return 0 ;
}