github.com/gdamore/mangos@v1.4.0/connipc_posix.go (about) 1 // +build !windows 2 3 // Copyright 2018 The Mangos Authors 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use file except in compliance with the License. 7 // You may obtain a copy of the license at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 package mangos 18 19 import ( 20 "encoding/binary" 21 "io" 22 "net" 23 ) 24 25 // NewConnPipeIPC allocates a new Pipe using the IPC exchange protocol. 26 func NewConnPipeIPC(c net.Conn, sock Socket, props ...interface{}) (Pipe, error) { 27 p := &connipc{conn: conn{c: c, proto: sock.GetProtocol(), sock: sock}} 28 29 if err := p.handshake(props); err != nil { 30 return nil, err 31 } 32 33 return p, nil 34 } 35 36 func (p *connipc) Send(msg *Message) error { 37 38 l := uint64(len(msg.Header) + len(msg.Body)) 39 // one := [1]byte{1} 40 var err error 41 42 // send length header 43 header := make([]byte, 9) 44 header[0] = 1 45 binary.BigEndian.PutUint64(header[1:], l) 46 47 if _, err = p.c.Write(header[:]); err != nil { 48 return err 49 } 50 51 if _, err = p.c.Write(msg.Header); err != nil { 52 return err 53 } 54 // hope this works 55 if _, err = p.c.Write(msg.Body); err != nil { 56 return err 57 } 58 msg.Free() 59 return nil 60 } 61 62 func (p *connipc) Recv() (*Message, error) { 63 64 var sz int64 65 var err error 66 var msg *Message 67 var one [1]byte 68 69 if _, err = p.c.Read(one[:]); err != nil { 70 return nil, err 71 } 72 if err = binary.Read(p.c, binary.BigEndian, &sz); err != nil { 73 return nil, err 74 } 75 76 // Limit messages to the maximum receive value, if not 77 // unlimited. This avoids a potential denaial of service. 78 if sz < 0 || (p.maxrx > 0 && sz > p.maxrx) { 79 return nil, ErrTooLong 80 } 81 msg = NewMessage(int(sz)) 82 msg.Body = msg.Body[0:sz] 83 if _, err = io.ReadFull(p.c, msg.Body); err != nil { 84 msg.Free() 85 return nil, err 86 } 87 return msg, nil 88 }