X-Git-Url: https://ruderich.org/simon/gitweb/?p=nsscash%2Fnsscash.git;a=blobdiff_plain;f=passwd.go;h=c9f4409c2bbb013f99631d251389f2e8d2e85de9;hp=90fed68a6b9f1d959f6ab9b03e4ebf89a081ec49;hb=06dfc130f0f152ef11c3113f7237e822b3e45b5b;hpb=1d028880cfb17a7c8a9e3b1f54cf1e980baca63d diff --git a/passwd.go b/passwd.go index 90fed68..c9f4409 100644 --- a/passwd.go +++ b/passwd.go @@ -23,6 +23,7 @@ import ( "encoding/binary" "fmt" "io" + "math" "sort" "strconv" "strings" @@ -44,13 +45,19 @@ type Passwd struct { } // ParsePasswds parses a file in the format of /etc/passwd and returns all -// entries as Passwd structs. +// entries as slice of Passwd structs. func ParsePasswds(r io.Reader) ([]Passwd, error) { var res []Passwd - s := bufio.NewScanner(r) - for s.Scan() { - t := s.Text() + s := bufio.NewReader(r) + for { + t, err := s.ReadString('\n') + if err != nil { + if err == io.EOF { + break + } + return nil, err + } x := strings.Split(t, ":") if len(x) != 7 { @@ -73,18 +80,14 @@ func ParsePasswds(r io.Reader) ([]Passwd, error) { Gid: gid, Gecos: x[4], Dir: x[5], - Shell: x[6], + // ReadString() contains the delimiter + Shell: strings.TrimSuffix(x[6], "\n"), }) } - err := s.Err() - if err != nil { - return nil, err - } - return res, nil } -func SerializePasswd(p Passwd) []byte { +func SerializePasswd(p Passwd) ([]byte, error) { // Concatenate all (NUL-terminated) strings and store the offsets var data bytes.Buffer data.Write([]byte(p.Name)) @@ -101,6 +104,11 @@ func SerializePasswd(p Passwd) []byte { offShell := uint16(data.Len()) data.Write([]byte(p.Shell)) data.WriteByte(0) + // Ensure the offsets can fit the length of this entry + if data.Len() > math.MaxUint16 { + return nil, fmt.Errorf("passwd too large to serialize: %v, %v", + data.Len(), p) + } size := uint16(data.Len()) var res bytes.Buffer // serialized result @@ -136,7 +144,7 @@ func SerializePasswd(p Passwd) []byte { // struct are 8 byte aligned alignBufferTo(&res, 8) - return res.Bytes() + return res.Bytes(), nil } func SerializePasswds(w io.Writer, pws []Passwd) error { @@ -146,7 +154,11 @@ func SerializePasswds(w io.Writer, pws []Passwd) error { for _, p := range pws { // TODO: warn about duplicate entries offsets[p] = uint64(data.Len()) - data.Write(SerializePasswd(p)) + x, err := SerializePasswd(p) + if err != nil { + return err + } + data.Write(x) } // Copy to prevent sorting from modifying the argument