]> ruderich.org/simon Gitweb - nsscash/nsscash.git/blob - group.go
nsscash: improve comments
[nsscash/nsscash.git] / group.go
1 // Parse /etc/group files and serialize them
2
3 // Copyright (C) 2019  Simon Ruderich
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU Affero General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU Affero General Public License for more details.
14 //
15 // You should have received a copy of the GNU Affero General Public License
16 // along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
18 package main
19
20 import (
21         "bufio"
22         "bytes"
23         "encoding/binary"
24         "fmt"
25         "io"
26         "sort"
27         "strconv"
28         "strings"
29
30         "github.com/pkg/errors"
31 )
32
33 // Version written in SerializeGroups()
34 const GroupVersion = 1
35
36 type Group struct {
37         Name    string
38         Passwd  string
39         Gid     uint64
40         Members []string
41 }
42
43 // Go does not support slices in map keys; therefore, use this separate struct
44 type GroupKey struct {
45         Name    string
46         Passwd  string
47         Gid     uint64
48         Members string // "," separated
49 }
50
51 func toKey(g Group) GroupKey {
52         return GroupKey{
53                 Name:    g.Name,
54                 Passwd:  g.Passwd,
55                 Gid:     g.Gid,
56                 Members: strings.Join(g.Members, ","),
57         }
58 }
59
60 // ParseGroups parses a file in the format of /etc/group and returns all
61 // entries as slice of Group structs.
62 func ParseGroups(r io.Reader) ([]Group, error) {
63         var res []Group
64
65         s := bufio.NewScanner(r)
66         for s.Scan() {
67                 t := s.Text()
68
69                 x := strings.Split(t, ":")
70                 if len(x) != 4 {
71                         return nil, fmt.Errorf("invalid line %q", t)
72                 }
73
74                 gid, err := strconv.ParseUint(x[2], 10, 64)
75                 if err != nil {
76                         return nil, errors.Wrapf(err, "invalid gid in line %q", t)
77                 }
78
79                 var members []string
80                 // No members must result in empty slice, not slice with the
81                 // empty string
82                 if x[3] != "" {
83                         members = strings.Split(x[3], ",")
84                 }
85                 res = append(res, Group{
86                         Name:    x[0],
87                         Passwd:  x[1],
88                         Gid:     gid,
89                         Members: members,
90                 })
91         }
92         err := s.Err()
93         if err != nil {
94                 return nil, err
95         }
96
97         return res, nil
98 }
99
100 func SerializeGroup(g Group) []byte {
101         le := binary.LittleEndian
102
103         // Concatenate all (NUL-terminated) strings and store the offsets
104         var mems bytes.Buffer
105         var mems_off []uint16
106         for _, m := range g.Members {
107                 mems_off = append(mems_off, uint16(mems.Len()))
108                 mems.Write([]byte(m))
109                 mems.WriteByte(0)
110         }
111         var data bytes.Buffer
112         data.Write([]byte(g.Name))
113         data.WriteByte(0)
114         offPasswd := uint16(data.Len())
115         data.Write([]byte(g.Passwd))
116         data.WriteByte(0)
117         alignBufferTo(&data, 2) // align the following uint16
118         offMemOff := uint16(data.Len())
119         // Offsets for group members
120         offMem := offMemOff + 2*uint16(len(mems_off))
121         for _, o := range mems_off {
122                 tmp := make([]byte, 2)
123                 le.PutUint16(tmp, offMem+o)
124                 data.Write(tmp)
125         }
126         // And the group members concatenated as above
127         data.Write(mems.Bytes())
128         size := uint16(data.Len())
129
130         var res bytes.Buffer // serialized result
131
132         id := make([]byte, 8)
133         // gid
134         le.PutUint64(id, g.Gid)
135         res.Write(id)
136
137         off := make([]byte, 2)
138         // off_passwd
139         le.PutUint16(off, offPasswd)
140         res.Write(off)
141         // off_mem_off
142         le.PutUint16(off, offMemOff)
143         res.Write(off)
144         // mem_count
145         le.PutUint16(off, uint16(len(g.Members)))
146         res.Write(off)
147         // data_size
148         le.PutUint16(off, size)
149         res.Write(off)
150
151         res.Write(data.Bytes())
152         // We must pad each entry so that all uint64 at the beginning of the
153         // struct are 8 byte aligned
154         alignBufferTo(&res, 8)
155
156         return res.Bytes()
157 }
158
159 func SerializeGroups(w io.Writer, grs []Group) error {
160         // Serialize groups and store offsets
161         var data bytes.Buffer
162         offsets := make(map[GroupKey]uint64)
163         for _, g := range grs {
164                 // TODO: warn about duplicate entries
165                 offsets[toKey(g)] = uint64(data.Len())
166                 data.Write(SerializeGroup(g))
167         }
168
169         // Copy to prevent sorting from modifying the argument
170         sorted := make([]Group, len(grs))
171         copy(sorted, grs)
172
173         le := binary.LittleEndian
174         tmp := make([]byte, 8)
175
176         // Create index "sorted" in input order, used when iterating over all
177         // passwd entries (getgrent_r); keeping the original order makes
178         // debugging easier
179         var indexOrig bytes.Buffer
180         for _, g := range grs {
181                 le.PutUint64(tmp, offsets[toKey(g)])
182                 indexOrig.Write(tmp)
183         }
184
185         // Create index sorted after id
186         var indexId bytes.Buffer
187         sort.Slice(sorted, func(i, j int) bool {
188                 return sorted[i].Gid < sorted[j].Gid
189         })
190         for _, g := range sorted {
191                 le.PutUint64(tmp, offsets[toKey(g)])
192                 indexId.Write(tmp)
193         }
194
195         // Create index sorted after name
196         var indexName bytes.Buffer
197         sort.Slice(sorted, func(i, j int) bool {
198                 return sorted[i].Name < sorted[j].Name
199         })
200         for _, g := range sorted {
201                 le.PutUint64(tmp, offsets[toKey(g)])
202                 indexName.Write(tmp)
203         }
204
205         // Sanity check
206         if len(grs)*8 != indexOrig.Len() ||
207                 indexOrig.Len() != indexId.Len() ||
208                 indexId.Len() != indexName.Len() {
209                 return fmt.Errorf("indexes have inconsistent length")
210         }
211
212         // Write result
213
214         // magic
215         w.Write([]byte("NSS-CASH"))
216         // version
217         le.PutUint64(tmp, GroupVersion)
218         w.Write(tmp)
219         // count
220         le.PutUint64(tmp, uint64(len(grs)))
221         w.Write(tmp)
222         // off_orig_index
223         offset := uint64(0)
224         le.PutUint64(tmp, offset)
225         w.Write(tmp)
226         // off_id_index
227         offset += uint64(indexOrig.Len())
228         le.PutUint64(tmp, offset)
229         w.Write(tmp)
230         // off_name_index
231         offset += uint64(indexId.Len())
232         le.PutUint64(tmp, offset)
233         w.Write(tmp)
234         // off_data
235         offset += uint64(indexName.Len())
236         le.PutUint64(tmp, offset)
237         w.Write(tmp)
238
239         _, err := indexOrig.WriteTo(w)
240         if err != nil {
241                 return err
242         }
243         _, err = indexId.WriteTo(w)
244         if err != nil {
245                 return err
246         }
247         _, err = indexName.WriteTo(w)
248         if err != nil {
249                 return err
250         }
251         _, err = data.WriteTo(w)
252         if err != nil {
253                 return err
254         }
255
256         return nil
257 }