aboutsummaryrefslogtreecommitdiff
path: root/server.go
blob: e34e3f289f21cd551f52f5d0ebbdfdcd34640825 (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main

import (
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"os/user"
	"strings"
)

const TableName = "membership"

type Server struct {
	HostName   string
	Groups     []string
	GroupsFile string
}

func ServeUnixSocket(listenner net.Listener, srv *Server) error {
	for {
		// Accept an incoming connection.
		conn, err := listenner.Accept()
		if errors.Is(err, net.ErrClosed) {
			break
		} else if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())

			continue
		}

		go func(conn net.Conn) {
			defer conn.Close()

			err = srv.HandleConn(conn, conn)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
			}
		}(conn)

	}

	return nil
}

func (s *Server) readGroupList() ([]string, error) {
	f, err := os.Open(s.GroupsFile)
	if err != nil {
		return nil, err
	}

	buf, err := io.ReadAll(f)
	if err != nil {
		return nil, err
	}

	groups := strings.Split(string(buf), "\n")

	return groups, nil
}

func (s *Server) HandleConn(w io.Writer, r io.Reader) error {
	for {
		var req Request

		_, err := readNetString(r, &req)
		if errors.Is(err, io.EOF) {
			break
		}

		if req.Name != TableName {
			if _, err = writeNetString(w, &ReplyPerm{Reason: "unexpected name"}); err != nil {
				return err
			}

			return nil
		}

		strs := strings.SplitN(req.Key, "@", 2)
		if len(strs) != 2 {
			return fmt.Errorf("unexpected email address format")
		}
		userName := strs[0]
		hostName := strs[1]

		if hostName != s.HostName {
			if _, err := writeNetString(w, &ReplyNotFound{}); err != nil {
				return err
			}

			return nil
		}

		u, err := user.Lookup(userName)
		if _, ok := err.(user.UnknownUserError); ok {
			_, err := writeNetString(w, &ReplyNotFound{})
			return err
		} else if err != nil {
			return err
		}

		groups, err := lookupGroupNames(u)
		if err != nil {
			return err
		}

		isListed := make(map[string]bool)

		for _, v := range s.Groups {
			isListed[v] = true
		}

		groupsFile, err := s.readGroupList()
		if err != nil {
			return fmt.Errorf("reading white list: %w", err)
		}

		for _, v := range groupsFile {
			isListed[v] = true
		}

		found := false

		for _, name := range groups {
			found = isListed[name]
			if found {
				_, err = writeNetString(w, &ReplyOK{Data: "OK"})
				return err
			}
		}

		_, err = writeNetString(w, &ReplyNotFound{})
		if err != nil {
			return err
		}
	}

	return nil
}