| // |
| 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 proxy |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "net" |
| 22 | "reflect" |
| 23 | "strconv" |
| 24 | "time" |
| 25 |
| 26 | "github.com/fatedier/golib/errors" |
| 27 | libio "github.com/fatedier/golib/io" |
| 28 |
| 29 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 30 | "github.com/fatedier/frp/pkg/msg" |
| 31 | "github.com/fatedier/frp/pkg/proto/udp" |
| 32 | "github.com/fatedier/frp/pkg/util/limit" |
| 33 | netpkg "github.com/fatedier/frp/pkg/util/net" |
| 34 | "github.com/fatedier/frp/server/metrics" |
| 35 | ) |
| 36 |
| 37 | func init() { |
| 38 | RegisterProxyFactory(reflect.TypeFor[*v1.UDPProxyConfig](), NewUDPProxy) |
| 39 | } |
| 40 |
| 41 | type UDPProxy struct { |
| 42 | *BaseProxy |
| 43 | cfg *v1.UDPProxyConfig |
| 44 |
| 45 | realBindPort int |
| 46 |
| 47 | // udpConn is the listener of udp packages |
| 48 | udpConn *net.UDPConn |
| 49 |
| 50 | // there are always only one workConn at the same time |
| 51 | // get another one if it closed |
| 52 | workConn net.Conn |
| 53 |
| 54 | // sendCh is used for sending packages to workConn |
| 55 | sendCh chan *msg.UDPPacket |
| 56 |
| 57 | // readCh is used for reading packages from workConn |
| 58 | readCh chan *msg.UDPPacket |
| 59 |
| 60 | // checkCloseCh is used for watching if workConn is closed |
| 61 | checkCloseCh chan int |
| 62 |
| 63 | isClosed bool |
| 64 | } |
| 65 |
| 66 | func NewUDPProxy(baseProxy *BaseProxy) Proxy { |
| 67 | unwrapped, ok := baseProxy.GetConfigurer().(*v1.UDPProxyConfig) |
| 68 | if !ok { |
| 69 | return nil |
| 70 | } |
| 71 | baseProxy.usedPortsNum = 1 |
| 72 | return &UDPProxy{ |
| 73 | BaseProxy: baseProxy, |
| 74 | cfg: unwrapped, |
| 75 | } |
| 76 | } |
| 77 |
| 78 | func (pxy *UDPProxy) Run() (remoteAddr string, err error) { |
| 79 | xl := pxy.xl |
| 80 | pxy.realBindPort, err = pxy.rc.UDPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort) |
| 81 | if err != nil { |
| 82 | return "", fmt.Errorf("acquire port %d error: %v", pxy.cfg.RemotePort, err) |
| 83 | } |
| 84 | defer func() { |
| 85 | if err != nil { |
| 86 | pxy.rc.UDPPortManager.Release(pxy.realBindPort) |
| 87 | } |
| 88 | }() |
| 89 |
| 90 | remoteAddr = fmt.Sprintf(":%d", pxy.realBindPort) |
| 91 | pxy.cfg.RemotePort = pxy.realBindPort |
| 92 | addr, errRet := net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realBindPort))) |
| 93 | if errRet != nil { |
| 94 | err = errRet |
| 95 | return |
| 96 | } |
| 97 | udpConn, errRet := net.ListenUDP("udp", addr) |
| 98 | if errRet != nil { |
| 99 | err = errRet |
| 100 | xl.Warnf("listen udp port error: %v", err) |
| 101 | return |
| 102 | } |
| 103 | xl.Infof("udp proxy listen port [%d]", pxy.cfg.RemotePort) |
| 104 |
| 105 | pxy.udpConn = udpConn |
| 106 | pxy.sendCh = make(chan *msg.UDPPacket, 1024) |
| 107 | pxy.readCh = make(chan *msg.UDPPacket, 1024) |
| 108 | pxy.checkCloseCh = make(chan int) |
| 109 |
| 110 | // read message from workConn, if it returns any error, notify proxy to start a new workConn |
| 111 | workConnReaderFn := func(payloadConn *msg.Conn) { |
| 112 | for { |
| 113 | var ( |
| 114 | rawMsg msg.Message |
| 115 | errRet error |
| 116 | ) |
| 117 | xl.Tracef("loop waiting message from udp workConn") |
| 118 | // client will send heartbeat in workConn for keeping alive |
| 119 | _ = payloadConn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second)) |
| 120 | if rawMsg, errRet = payloadConn.ReadMsg(); errRet != nil { |
| 121 | xl.Warnf("read from workConn for udp error: %v", errRet) |
| 122 | _ = payloadConn.Close() |
| 123 | // notify proxy to start a new work connection |
| 124 | // ignore error here, it means the proxy is closed |
| 125 | _ = errors.PanicToError(func() { |
| 126 | pxy.checkCloseCh <- 1 |
| 127 | }) |
| 128 | return |
| 129 | } |
| 130 | if err := payloadConn.SetReadDeadline(time.Time{}); err != nil { |
| 131 | xl.Warnf("set read deadline error: %v", err) |
| 132 | } |
| 133 | switch m := rawMsg.(type) { |
| 134 | case *msg.Ping: |
| 135 | xl.Tracef("udp work conn get ping message") |
| 136 | continue |
| 137 | case *msg.UDPPacket: |
| 138 | if errRet := errors.PanicToError(func() { |
| 139 | xl.Tracef("get udp message from workConn, len: %d", len(m.Content)) |
| 140 | pxy.readCh <- m |
| 141 | metrics.Server.AddTrafficOut( |
| 142 | pxy.GetName(), |
| 143 | pxy.GetConfigurer().GetBaseConfig().Type, |
| 144 | int64(len(m.Content)), |
| 145 | ) |
| 146 | }); errRet != nil { |
| 147 | _ = payloadConn.Close() |
| 148 | xl.Infof("reader goroutine for udp work connection closed") |
| 149 | return |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 |
| 155 | // send message to workConn |
| 156 | workConnSenderFn := func(payloadConn *msg.Conn, ctx context.Context) { |
| 157 | var errRet error |
| 158 | for { |
| 159 | select { |
| 160 | case udpMsg, ok := <-pxy.sendCh: |
| 161 | if !ok { |
| 162 | xl.Infof("sender goroutine for udp work connection closed") |
| 163 | return |
| 164 | } |
| 165 | if errRet = payloadConn.WriteMsg(udpMsg); errRet != nil { |
| 166 | xl.Infof("sender goroutine for udp work connection closed: %v", errRet) |
| 167 | _ = payloadConn.Close() |
| 168 | return |
| 169 | } |
| 170 | xl.Tracef("send message to udp workConn, len: %d", len(udpMsg.Content)) |
| 171 | metrics.Server.AddTrafficIn( |
| 172 | pxy.GetName(), |
| 173 | pxy.GetConfigurer().GetBaseConfig().Type, |
| 174 | int64(len(udpMsg.Content)), |
| 175 | ) |
| 176 | continue |
| 177 | case <-ctx.Done(): |
| 178 | xl.Infof("sender goroutine for udp work connection closed") |
| 179 | return |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 |
| 184 | go func() { |
| 185 | // Sleep a while for waiting control send the NewProxyResp to client. |
| 186 | time.Sleep(500 * time.Millisecond) |
| 187 | for { |
| 188 | workConn, err := pxy.GetWorkConnFromPool(nil, nil) |
| 189 | if err != nil { |
| 190 | time.Sleep(1 * time.Second) |
| 191 | // check if proxy is closed |
| 192 | select { |
| 193 | case _, ok := <-pxy.checkCloseCh: |
| 194 | if !ok { |
| 195 | return |
| 196 | } |
| 197 | default: |
| 198 | } |
| 199 | continue |
| 200 | } |
| 201 | // close the old workConn and replace it with a new one |
| 202 | if pxy.workConn != nil { |
| 203 | pxy.workConn.Close() |
| 204 | } |
| 205 |
| 206 | var rwc io.ReadWriteCloser = workConn |
| 207 | if pxy.cfg.Transport.UseEncryption { |
| 208 | rwc, err = libio.WithEncryption(rwc, pxy.encryptionKey) |
| 209 | if err != nil { |
| 210 | xl.Errorf("create encryption stream error: %v", err) |
| 211 | workConn.Close() |
| 212 | continue |
| 213 | } |
| 214 | } |
| 215 | if pxy.cfg.Transport.UseCompression { |
| 216 | rwc = libio.WithCompression(rwc) |
| 217 | } |
| 218 |
| 219 | if pxy.GetLimiter() != nil { |
| 220 | rwc = libio.WrapReadWriteCloser(limit.NewReader(rwc, pxy.GetLimiter()), limit.NewWriter(rwc, pxy.GetLimiter()), func() error { |
| 221 | return rwc.Close() |
| 222 | }) |
| 223 | } |
| 224 |
| 225 | pxy.workConn = netpkg.WrapReadWriteCloserToConn(rwc, workConn) |
| 226 | // Plain UDP payload follows the negotiated wire protocol for message framing. |
| 227 | payloadConn := msg.NewConn(pxy.workConn, msg.NewReadWriter(pxy.workConn, pxy.wireProtocol)) |
| 228 | ctx, cancel := context.WithCancel(context.Background()) |
| 229 | go workConnReaderFn(payloadConn) |
| 230 | go workConnSenderFn(payloadConn, ctx) |
| 231 | _, ok := <-pxy.checkCloseCh |
| 232 | cancel() |
| 233 | if !ok { |
| 234 | return |
| 235 | } |
| 236 | } |
| 237 | }() |
| 238 |
| 239 | // Read from user connections and send wrapped udp message to sendCh (forwarded by workConn). |
| 240 | // Client will transfor udp message to local udp service and waiting for response for a while. |
| 241 | // Response will be wrapped to be forwarded by work connection to server. |
| 242 | // Close readCh and sendCh at the end. |
| 243 | go func() { |
| 244 | udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh, int(pxy.serverCfg.UDPPacketSize)) |
| 245 | pxy.Close() |
| 246 | }() |
| 247 | return remoteAddr, nil |
| 248 | } |
| 249 |
| 250 | func (pxy *UDPProxy) Close() { |
| 251 | pxy.mu.Lock() |
| 252 | defer pxy.mu.Unlock() |
| 253 | if !pxy.isClosed { |
| 254 | pxy.isClosed = true |
| 255 |
| 256 | pxy.BaseProxy.Close() |
| 257 | if pxy.workConn != nil { |
| 258 | pxy.workConn.Close() |
| 259 | } |
| 260 | pxy.udpConn.Close() |
| 261 |
| 262 | // all channels only closed here |
| 263 | close(pxy.checkCloseCh) |
| 264 | close(pxy.readCh) |
| 265 | close(pxy.sendCh) |
| 266 | } |
| 267 | pxy.rc.UDPPortManager.Release(pxy.realBindPort) |
| 268 | } |