github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/acceptor.go (about) 1 // Copyright (c) 2023 Paweł Gaczyński 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package gain 16 17 import ( 18 "net" 19 "syscall" 20 "unsafe" 21 22 "github.com/pawelgaczynski/gain/pkg/errors" 23 "github.com/pawelgaczynski/gain/pkg/socket" 24 "github.com/pawelgaczynski/giouring" 25 ) 26 27 type acceptor struct { 28 ring *giouring.Ring 29 fd int 30 clientAddr *syscall.RawSockaddrAny 31 clientLenPointer *uint32 32 connectionManager *connectionManager 33 } 34 35 func (a *acceptor) addAcceptRequest() error { 36 entry := a.ring.GetSQE() 37 if entry == nil { 38 return errors.ErrGettingSQE 39 } 40 41 entry.PrepareAccept( 42 a.fd, uintptr(unsafe.Pointer(a.clientAddr)), uint64(uintptr(unsafe.Pointer(a.clientLenPointer))), 0) 43 entry.UserData = acceptDataFlag | uint64(a.fd) 44 45 return nil 46 } 47 48 func (a *acceptor) addAcceptConnRequest() error { 49 err := a.addAcceptRequest() 50 if err != nil { 51 return err 52 } 53 54 conn := a.connectionManager.getFd(a.fd) 55 conn.state = connAccept 56 57 return nil 58 } 59 60 func (a *acceptor) lastClientAddr() (net.Addr, error) { 61 addr, err := anyToSockaddr(a.clientAddr) 62 if err != nil { 63 return nil, err 64 } 65 66 return socket.SockaddrToTCPOrUnixAddr(addr), nil 67 } 68 69 func newAcceptor(ring *giouring.Ring, connectionManager *connectionManager) *acceptor { 70 acceptor := &acceptor{ 71 ring: ring, 72 connectionManager: connectionManager, 73 } 74 acceptor.clientAddr, acceptor.clientLenPointer = createClientAddr() 75 76 return acceptor 77 }