sockcmsg_linux.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Socket control messages
  5. package unix
  6. import "unsafe"
  7. // UnixCredentials encodes credentials into a socket control message
  8. // for sending to another process. This can be used for
  9. // authentication.
  10. func UnixCredentials(ucred *Ucred) []byte {
  11. b := make([]byte, CmsgSpace(SizeofUcred))
  12. h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
  13. h.Level = SOL_SOCKET
  14. h.Type = SCM_CREDENTIALS
  15. h.SetLen(CmsgLen(SizeofUcred))
  16. *((*Ucred)(cmsgData(h))) = *ucred
  17. return b
  18. }
  19. // ParseUnixCredentials decodes a socket control message that contains
  20. // credentials in a Ucred structure. To receive such a message, the
  21. // SO_PASSCRED option must be enabled on the socket.
  22. func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) {
  23. if m.Header.Level != SOL_SOCKET {
  24. return nil, EINVAL
  25. }
  26. if m.Header.Type != SCM_CREDENTIALS {
  27. return nil, EINVAL
  28. }
  29. ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
  30. return &ucred, nil
  31. }