github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/util/unix_single_rwc.go (about) 1 // Copyright (c) 2014, Google Inc. All rights reserved. 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 util 16 17 import ( 18 "fmt" 19 "io" 20 "net" 21 "os" 22 ) 23 24 // A UnixSingleReadWriteCloser accepts a single connection and reads and writes 25 // to this connection 26 type UnixSingleReadWriteCloser struct { 27 l net.Listener 28 c net.Conn 29 } 30 31 // NewUnixSingleReadWriteCloser listens on a given Unix socket path and returns 32 // a UnixSingleReadWriteCloser that will accept a single connection on this 33 // socket and communicate only with it. 34 func NewUnixSingleReadWriteCloser(path string) io.ReadWriteCloser { 35 l, err := net.Listen("unix", path) 36 if err != nil { 37 fmt.Fprintf(os.Stderr, "Failed to listen on the channel: %s\n", err) 38 return nil 39 } 40 41 return &UnixSingleReadWriteCloser{l, nil} 42 } 43 44 // Read accepts a connection if there isn't one already and reads from the 45 // connection. 46 func (usrwc *UnixSingleReadWriteCloser) Read(p []byte) (int, error) { 47 var err error 48 if usrwc.c == nil { 49 usrwc.c, err = usrwc.l.Accept() 50 if err != nil { 51 return 0, err 52 } 53 } 54 55 return usrwc.c.Read(p) 56 } 57 58 // Write accepts a connection if there isn't one already and writes to the 59 // connection. 60 func (usrwc *UnixSingleReadWriteCloser) Write(p []byte) (int, error) { 61 var err error 62 if usrwc.c == nil { 63 usrwc.c, err = usrwc.l.Accept() 64 if err != nil { 65 return 0, err 66 } 67 } 68 69 return usrwc.c.Write(p) 70 } 71 72 // Close closes the connection if there is one and closes the listener. 73 func (usrwc *UnixSingleReadWriteCloser) Close() error { 74 if usrwc.c != nil { 75 usrwc.c.Close() 76 } 77 78 return usrwc.l.Close() 79 }