github.com/openziti/transport@v0.1.5/tcp/listener.go (about) 1 /* 2 Copyright NetFoundry, Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 https://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tcp 18 19 import ( 20 "github.com/michaelquigley/pfxlog" 21 "github.com/openziti/transport" 22 "github.com/sirupsen/logrus" 23 "io" 24 "net" 25 ) 26 27 func Listen(bindAddress, name string, incoming chan transport.Connection) (io.Closer, error) { 28 log := pfxlog.ContextLogger(name + "/tcp:" + bindAddress) 29 30 listener, err := net.Listen("tcp", bindAddress) 31 if err != nil { 32 return nil, err 33 } 34 35 go acceptLoop(log.Entry, name, listener, incoming) 36 37 return listener, nil 38 } 39 40 func acceptLoop(log *logrus.Entry, name string, listener net.Listener, incoming chan transport.Connection) { 41 defer log.Error("exited") 42 43 for { 44 socket, err := listener.Accept() 45 if err != nil { 46 if netErr, ok := err.(net.Error); ok && !netErr.Temporary() { 47 log.WithField("err", err).Error("accept failed. failure not recoverable. exiting listen loop") 48 return 49 } 50 log.WithField("err", err).Error("accept failed") 51 52 } else { 53 connection := &Connection{ 54 detail: &transport.ConnectionDetail{ 55 Address: "tcp:" + socket.RemoteAddr().String(), 56 InBound: true, 57 Name: name, 58 }, 59 socket: socket, 60 } 61 incoming <- connection 62 63 log.WithField("addr", socket.RemoteAddr().String()).Info("accepted connection") 64 } 65 } 66 }