Skip to content

Commit

Permalink
add timeout waiting for client input
Browse files Browse the repository at this point in the history
  • Loading branch information
jarod committed Sep 20, 2013
1 parent 31de0f7 commit 1a12542
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions fsp.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"io/ioutil"
"log"
"net"
"strings"
"time"
)

const (
Expand Down Expand Up @@ -55,17 +57,44 @@ func (fs *FspServer) LoadPolicy(src io.Reader) {
func (fs *FspServer) handleConnection(conn *net.TCPConn) {
defer conn.Close()

r := bufio.NewReader(conn)
_, err := r.ReadString('\x00')
if err != nil {
if err != io.EOF {
log.Println(err)
select {
case ok := <-fs.read(conn):
if !ok {
return
}
case <-fs.timeout(time.Second * 2):
log.Println("Timeout reading from", conn.RemoteAddr().String())
return
}

w := bufio.NewWriterSize(conn, len(fs.policyData))
w.Write(fs.policyData)
w.Flush()
log.Printf("Sent policy file to %s", conn.RemoteAddr().String())
log.Println("Sent policy file to", conn.RemoteAddr().String())
}

func (fs *FspServer) read(conn *net.TCPConn) (c chan bool) {
c = make(chan bool)
go func() {
r := bufio.NewReader(conn)
_, err := r.ReadString('\x00')
if err != nil {
if err != io.EOF && !strings.HasSuffix(err.Error(), "use of closed network connection") {
log.Println(err)
}
c <- false
} else {
c <- true
}
}()
return
}

func (fs *FspServer) timeout(d time.Duration) (c chan bool) {
c = make(chan bool)
go func() {
time.Sleep(d)
c <- true
}()
return
}

0 comments on commit 1a12542

Please sign in to comment.