github.com/openziti/transport@v0.1.5/udp/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 udp 18 19 import ( 20 "bufio" 21 "github.com/michaelquigley/pfxlog" 22 "github.com/openziti/foundation/identity/identity" 23 "github.com/openziti/transport" 24 udp2 "github.com/openziti/foundation/udp" 25 "github.com/sirupsen/logrus" 26 "io" 27 "math" 28 "net" 29 ) 30 31 func Listen(bindAddress *net.UDPAddr, name string, i *identity.TokenId, incoming chan transport.Connection) (io.Closer, error) { 32 log := pfxlog.ContextLogger(name + "/udp:" + bindAddress.String()) 33 34 listener, err := udp2.Listen("udp", bindAddress) 35 if err != nil { 36 return nil, err 37 } 38 39 go acceptLoop(log.Entry, name, listener, incoming) 40 41 return listener, nil 42 } 43 44 func acceptLoop(log *logrus.Entry, name string, listener net.Listener, incoming chan transport.Connection) { 45 defer log.Error("exited") 46 47 for { 48 socket, err := listener.Accept() 49 if err != nil { 50 if netErr, ok := err.(net.Error); ok && !netErr.Temporary() { 51 log.WithField("err", err).Error("accept failed. Failure not recoverable. Exiting listen loop") 52 return 53 } 54 log.WithField("err", err).Error("accept failed") 55 } else { 56 log.Info("new udp connection accepted") 57 connection := &Connection{ 58 detail: &transport.ConnectionDetail{ 59 Address: "udp:" + socket.RemoteAddr().String(), 60 InBound: true, 61 Name: name, 62 }, 63 socket: socket, 64 reader: bufio.NewReaderSize(socket, math.MaxUint16), 65 } 66 incoming <- connection 67 } 68 } 69 }