aboutsummaryrefslogtreecommitdiffhomepage
path: root/xcb/export.go
blob: 35af9aa56017d4d0d1186a4aba4ac463624347d5 (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
// Package xcb implements X11 ChangeHosts via libxcb.
package xcb

//#include <stdlib.h>
//#include <xcb/xcb.h>
//#cgo linux LDFLAGS: -lxcb
import "C"
import (
	"errors"
	"unsafe"
)

const (
	HostModeInsert = C.XCB_HOST_MODE_INSERT
	HostModeDelete = C.XCB_HOST_MODE_DELETE

	FamilyInternet          = C.XCB_FAMILY_INTERNET
	FamilyDecnet            = C.XCB_FAMILY_DECNET
	FamilyChaos             = C.XCB_FAMILY_CHAOS
	FamilyServerInterpreted = C.XCB_FAMILY_SERVER_INTERPRETED
	FamilyInternet6         = C.XCB_FAMILY_INTERNET_6
)

type ConnectionError struct {
	err error
}

func (e *ConnectionError) Error() string {
	return e.err.Error()
}

func (e *ConnectionError) Unwrap() error {
	return e.err
}

var (
	ErrChangeHosts = errors.New("xcb_change_hosts() failed")
)

func ChangeHosts(mode, family C.uint8_t, address string) error {
	c := C.xcb_connect(nil, nil)
	defer C.xcb_disconnect(c)

	if err := xcbHandleConnectionError(c); err != nil {
		return &ConnectionError{err}
	}

	addr := C.CString(address)
	cookie := C.xcb_change_hosts_checked(c, mode, family, C.ushort(len(address)), (*C.uchar)(unsafe.Pointer(addr)))
	C.free(unsafe.Pointer(addr))

	if err := xcbHandleConnectionError(c); err != nil {
		return &ConnectionError{err}
	}

	e := C.xcb_request_check(c, cookie)
	if e != nil {
		defer C.free(unsafe.Pointer(e))
		return ErrChangeHosts
	}

	return nil
}