File: gecos.go

package info (click to toggle)
golang-pault-go-gecos 1.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 64 kB
  • sloc: makefile: 5
file content (59 lines) | stat: -rw-r--r-- 944 bytes parent folder | download | duplicates (2)
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
package gecos

/*
#include <pwd.h>
#include <malloc.h>
*/
import "C"

import (
	"fmt"
	"os/user"
	"strconv"
	"strings"
)

var (
	NoGECOSEntry = fmt.Errorf("No GECOS Entry for this user")
)

type GECOS struct {
	Name        string
	Room        string
	OfficePhone string
	HomePhone   string
	Other       string
}

func getpwuid(user int) (*GECOS, error) {
	gecos := C.getpwuid(C.__uid_t(user))

	gecosString := C.GoString(gecos.pw_gecos)

	els := strings.SplitN(gecosString, ",", 5)

	if len(els) == 1 {
		return nil, NoGECOSEntry
	}
	if len(els) < 4 {
		return nil, fmt.Errorf("Expected 4 or 5 elements, got %d", len(els))
	}
	ret := GECOS{
		Name:        els[0],
		Room:        els[1],
		OfficePhone: els[2],
		HomePhone:   els[3],
	}
	if len(els) >= 5 {
		ret.Other = els[4]
	}
	return &ret, nil
}

func Lookup(user *user.User) (*GECOS, error) {
	id, err := strconv.Atoi(user.Uid)
	if err != nil {
		return nil, err
	}
	return getpwuid(id)
}