package main

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"runtime"
	"sync/atomic"
	"time"
	"unicode/utf8"
	"unsafe"

	"golang.org/x/sys/unix"
)

const headerSize = 4096
const maxPayload = 16403
const maxDetail = 65535

type session struct {
	fd int
	memory []byte
	submission uint64
	completion uint64
}

type completion struct {
	id uint64
	code byte
	payload []byte
}

func recordSize(length uint64) uint64 { return (16 + length + 15) &^ 15 }
func validCapacity(value uint64) bool { return value >= 16 && value&(value-1) == 0 }
func positions(head, tail, capacity uint64) error {
	if (head|tail)&15 != 0 || head > tail || tail-head > capacity {
		return errors.New("invalid ring positions")
	}
	return nil
}
func (s *session) word64(offset int) *uint64 { return (*uint64)(unsafe.Pointer(&s.memory[offset])) }
func (s *session) word32(offset int) *uint32 { return (*uint32)(unsafe.Pointer(&s.memory[offset])) }

func connectAgent(path string) (_ *session, err error) {
	fd, err := unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
	if err != nil { return nil, err }
	ok := false
	defer func() { if !ok { unix.Close(fd) } }()
	if err := unix.Connect(fd, &unix.SockaddrUnix{Name: path}); err != nil { return nil, err }
	deadline := time.Now().Add(2 * time.Second)
	limit := unix.NsecToTimeval((2 * time.Second).Nanoseconds())
	if err := unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_SNDTIMEO, &limit); err != nil {
		return nil, err
	}
	hello := []byte("ZCI1")
	for len(hello) != 0 {
		n, err := unix.SendmsgN(fd, hello, nil, nil, unix.MSG_NOSIGNAL)
		if err == unix.EINTR { continue }
		if err != nil { return nil, err }
		if n == 0 { return nil, errors.New("agent closed during handshake") }
		hello = hello[n:]
	}
	reply := make([]byte, 9)
	received, memfd := 0, -1
	defer func() { if memfd >= 0 { unix.Close(memfd) } }()
	for received < len(reply) {
		left := time.Until(deadline)
		if left <= 0 { return nil, errors.New("IPC handshake timed out") }
		limit = unix.NsecToTimeval(left.Nanoseconds())
		if err := unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &limit); err != nil {
			return nil, err
		}
		control := make([]byte, unix.CmsgSpace(4))
		n, controlLength, flags, _, err := unix.Recvmsg(fd, reply[received:], control, unix.MSG_CMSG_CLOEXEC)
		if err == unix.EINTR { continue }
		if err != nil { return nil, err }
		if n == 0 { return nil, errors.New("agent closed during handshake") }
		messages, err := unix.ParseSocketControlMessage(control[:controlLength])
		if err != nil { return nil, err }
		for _, message := range messages {
			if message.Header.Level != unix.SOL_SOCKET || message.Header.Type != unix.SCM_RIGHTS { continue }
			rights, err := unix.ParseUnixRights(&message)
			if err != nil { return nil, err }
			if len(rights) != 1 || memfd >= 0 {
				for _, extra := range rights { unix.Close(extra) }
				return nil, errors.New("unexpected descriptors in handshake")
			}
			memfd = rights[0]
		}
		if flags&(unix.MSG_CTRUNC|unix.MSG_TRUNC) != 0 { return nil, errors.New("truncated handshake") }
		received += n
	}
	if reply[0] != 0 { return nil, fmt.Errorf("session refused with code %d", reply[0]) }
	if memfd < 0 { return nil, errors.New("handshake carried no shared memory") }
	submission := uint64(binary.LittleEndian.Uint32(reply[1:5]))
	completionCapacity := uint64(binary.LittleEndian.Uint32(reply[5:9]))
	if !validCapacity(submission) || !validCapacity(completionCapacity) {
		return nil, errors.New("invalid capacity")
	}
	length := uint64(headerSize) + submission + completionCapacity
	var stat unix.Stat_t
	if err := unix.Fstat(memfd, &stat); err != nil { return nil, err }
	if stat.Size < 0 || uint64(stat.Size) < length { return nil, errors.New("shared memory is too small") }
	memory, err := unix.Mmap(memfd, 0, int(length), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED)
	if err != nil { return nil, err }
	defer func() { if !ok { unix.Munmap(memory) } }()
	if string(memory[:4]) != "ZCR1" || binary.LittleEndian.Uint32(memory[4:8]) != 1 ||
		uint64(binary.LittleEndian.Uint32(memory[8:12])) != submission ||
		uint64(binary.LittleEndian.Uint32(memory[12:16])) != completionCapacity {
		return nil, errors.New("unexpected shared memory header")
	}
	if err := unix.SetNonblock(fd, true); err != nil { return nil, err }
	ok = true
	return &session{fd, memory, submission, completionCapacity}, nil
}

func (s *session) submit(id uint64, payload []byte) error {
	// Go's atomics are sequentially consistent, stronger than acquire/release.
	tail := atomic.LoadUint64(s.word64(64))
	head := atomic.LoadUint64(s.word64(128))
	if err := positions(head, tail, s.submission); err != nil { return err }
	size := recordSize(uint64(len(payload)))
	offset := tail & (s.submission-1)
	remaining, pad := s.submission-offset, uint64(0)
	if size > remaining { pad = remaining }
	if pad+size > s.submission-(tail-head) { return errors.New("submission ring is full") }
	if tail > ^uint64(0)-(pad+size) { return errors.New("submission counter overflow") }
	if pad != 0 {
		record := s.memory[headerSize+offset:headerSize+offset+16]
		clear(record)
		binary.LittleEndian.PutUint32(record, uint32(pad-16))
		offset = 0
	}
	record := s.memory[headerSize+offset:headerSize+offset+size]
	clear(record)
	binary.LittleEndian.PutUint32(record, uint32(len(payload)))
	record[4], record[5] = 1, 1 // Transaction, request a completion, no preflight.
	binary.LittleEndian.PutUint64(record[8:16], id)
	copy(record[16:], payload)
	atomic.StoreUint64(s.word64(64), tail+pad+size)
	// The SC exchange supplies the store/load fence and clears the doorbell flag.
	if atomic.SwapUint32(s.word32(320), 0) == 1 {
		_, _ = unix.SendmsgN(s.fd, []byte{0}, nil, nil, unix.MSG_NOSIGNAL|unix.MSG_DONTWAIT)
	}
	return nil
}

func (s *session) readCompletion() (*completion, error) {
	for {
		head := atomic.LoadUint64(s.word64(256))
		tail := atomic.LoadUint64(s.word64(192))
		if err := positions(head, tail, s.completion); err != nil { return nil, err }
		used := tail-head
		if used == 0 { return nil, nil }
		offset := head & (s.completion-1)
		remaining := s.completion-offset
		start := uint64(headerSize)+s.submission+offset
		record := s.memory[start:start+16]
		length := uint64(binary.LittleEndian.Uint32(record))
		id := binary.LittleEndian.Uint64(record[8:16])
		kind, code := record[4], record[5]
		if record[6] != 0 || record[7] != 0 { return nil, errors.New("nonzero reserved bytes") }
		if kind == 0 {
			if length != remaining-16 || remaining > used || code != 0 || id != 0 {
				return nil, errors.New("invalid pad record")
			}
			atomic.StoreUint64(s.word64(256), head+remaining)
			continue
		}
		size := recordSize(length)
		if kind != 1 || length > maxDetail || size > remaining || size > used ||
			code > 13 || (code == 0 && length != 0) {
			return nil, errors.New("invalid transaction completion")
		}
		payload := append([]byte(nil), s.memory[start+16:start+16+length]...)
		atomic.StoreUint64(s.word64(256), head+size)
		return &completion{id, code, payload}, nil
	}
}

func (s *session) waitFor(id uint64) (*completion, error) {
	deadline := time.Now().Add(5 * time.Second)
	ended := false
	for {
		for {
			reply, err := s.readCompletion()
			if err != nil { return nil, err }
			if reply == nil { break }
			if reply.id == id { return reply, nil }
		}
		if ended { return nil, errors.New("session ended; check the signature before retrying") }
		left := time.Until(deadline)
		if left <= 0 { return nil, errors.New("no completion within 5 seconds; check the signature before retrying") }
		atomic.SwapUint32(s.word32(384), 1)
		if atomic.LoadUint64(s.word64(192)) != atomic.LoadUint64(s.word64(256)) {
			atomic.StoreUint32(s.word32(384), 0)
			continue
		}
		watch := []unix.PollFd{{Fd: int32(s.fd), Events: unix.POLLIN}}
		ready, err := unix.Poll(watch, int((left+time.Millisecond-1)/time.Millisecond))
		atomic.StoreUint32(s.word32(384), 0)
		if err == unix.EINTR { continue }
		if err != nil { return nil, err }
		if ready != 0 {
			ended = watch[0].Revents&(unix.POLLERR|unix.POLLHUP|unix.POLLNVAL) != 0
			var wakeups [128]byte
			for {
				n, _, err := unix.Recvfrom(s.fd, wakeups[:], unix.MSG_DONTWAIT)
				if err == unix.EINTR { continue }
				if err == unix.EAGAIN || err == unix.EWOULDBLOCK { break }
				if err != nil || n == 0 { ended = true; break }
			}
		}
	}
}

func run() (bool, error) {
	if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" { return false, errors.New("this client requires Linux x86_64") }
	if len(os.Args) != 3 { return false, errors.New("usage: ipc-send SOCKET_PATH TRANSACTION_FILE") }
	file, err := os.Open(os.Args[2])
	if err != nil { return false, err }
	defer file.Close()
	payload, err := io.ReadAll(io.LimitReader(file, maxPayload+1))
	if err != nil { return false, err }
	if len(payload) == 0 || len(payload) > maxPayload { return false, errors.New("transaction payload must hold 1 to 16403 bytes") }
	s, err := connectAgent(os.Args[1])
	if err != nil { return false, err }
	defer unix.Close(s.fd)
	defer unix.Munmap(s.memory)
	if err := s.submit(1, payload); err != nil { return false, err }
	reply, err := s.waitFor(1)
	if err != nil { return false, err }
	if len(reply.payload) != 0 {
		var rejection struct { Reason string `json:"reason"` }
		if !utf8.Valid(reply.payload) { return false, errors.New("invalid UTF-8 rejection detail") }
		if err := json.Unmarshal(reply.payload, &rejection); err != nil { return false, err }
		if rejection.Reason == "" { return false, errors.New("invalid rejection detail") }
	}
	fmt.Printf("code %d\n", reply.code)
	if len(reply.payload) != 0 { fmt.Println(string(reply.payload)) }
	return reply.code == 0, nil
}

func main() {
	accepted, err := run()
	if err != nil { fmt.Fprintln(os.Stderr, err) }
	if err != nil || !accepted { os.Exit(1) }
}
