// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Socket control messages

package unix

import 

// UnixCredentials encodes credentials into a socket control message
// for sending to another process. This can be used for
// authentication.
func ( *Ucred) []byte {
	 := make([]byte, CmsgSpace(SizeofUcred))
	 := (*Cmsghdr)(unsafe.Pointer(&[0]))
	.Level = SOL_SOCKET
	.Type = SCM_CREDENTIALS
	.SetLen(CmsgLen(SizeofUcred))
	*(*Ucred)(.data(0)) = *
	return 
}

// ParseUnixCredentials decodes a socket control message that contains
// credentials in a Ucred structure. To receive such a message, the
// SO_PASSCRED option must be enabled on the socket.
func ( *SocketControlMessage) (*Ucred, error) {
	if .Header.Level != SOL_SOCKET {
		return nil, EINVAL
	}
	if .Header.Type != SCM_CREDENTIALS {
		return nil, EINVAL
	}
	 := *(*Ucred)(unsafe.Pointer(&.Data[0]))
	return &, nil
}

// PktInfo4 encodes Inet4Pktinfo into a socket control message of type IP_PKTINFO.
func ( *Inet4Pktinfo) []byte {
	 := make([]byte, CmsgSpace(SizeofInet4Pktinfo))
	 := (*Cmsghdr)(unsafe.Pointer(&[0]))
	.Level = SOL_IP
	.Type = IP_PKTINFO
	.SetLen(CmsgLen(SizeofInet4Pktinfo))
	*(*Inet4Pktinfo)(.data(0)) = *
	return 
}

// PktInfo6 encodes Inet6Pktinfo into a socket control message of type IPV6_PKTINFO.
func ( *Inet6Pktinfo) []byte {
	 := make([]byte, CmsgSpace(SizeofInet6Pktinfo))
	 := (*Cmsghdr)(unsafe.Pointer(&[0]))
	.Level = SOL_IPV6
	.Type = IPV6_PKTINFO
	.SetLen(CmsgLen(SizeofInet6Pktinfo))
	*(*Inet6Pktinfo)(.data(0)) = *
	return 
}

// ParseOrigDstAddr decodes a socket control message containing the original
// destination address. To receive such a message the IP_RECVORIGDSTADDR or
// IPV6_RECVORIGDSTADDR option must be enabled on the socket.
func ( *SocketControlMessage) (Sockaddr, error) {
	switch {
	case .Header.Level == SOL_IP && .Header.Type == IP_ORIGDSTADDR:
		 := (*RawSockaddrInet4)(unsafe.Pointer(&.Data[0]))
		 := new(SockaddrInet4)
		 := (*[2]byte)(unsafe.Pointer(&.Port))
		.Port = int([0])<<8 + int([1])
		.Addr = .Addr
		return , nil

	case .Header.Level == SOL_IPV6 && .Header.Type == IPV6_ORIGDSTADDR:
		 := (*RawSockaddrInet6)(unsafe.Pointer(&.Data[0]))
		 := new(SockaddrInet6)
		 := (*[2]byte)(unsafe.Pointer(&.Port))
		.Port = int([0])<<8 + int([1])
		.ZoneId = .Scope_id
		.Addr = .Addr
		return , nil

	default:
		return nil, EINVAL
	}
}