@@ -180,6 +180,8 @@ allowed_ip=%s/128`,
180180 }, exists , nil
181181}
182182
183+ type ipPortKey struct {}
184+
183185func (api * API ) handleTunnelMW (next http.Handler ) http.Handler {
184186 return http .HandlerFunc (func (rw http.ResponseWriter , r * http.Request ) {
185187 ctx := r .Context ()
@@ -210,36 +212,28 @@ func (api *API) handleTunnelMW(next http.Handler) http.Handler {
210212 return
211213 }
212214
213- dialCtx , dialCancel := context .WithTimeout (ctx , api .Options .PeerDialTimeout )
214- defer dialCancel ()
215-
216- nc , err := api .wgNet .DialContextTCPAddrPort (dialCtx , netip .AddrPortFrom (ip , tunnelsdk .TunnelPort ))
217- if err != nil {
218- httpapi .Write (ctx , rw , http .StatusBadGateway , tunnelsdk.Response {
219- Message : "Failed to dial peer." ,
220- Detail : err .Error (),
221- })
222- return
223- }
224-
225215 span := trace .SpanFromContext (ctx )
226216 span .SetAttributes (attribute .Bool ("proxy_request" , true ))
227217
218+ // The transport on the reverse proxy uses this ctx value to know which
219+ // IP to dial. See tunneld.go.
220+ ctx = context .WithValue (ctx , ipPortKey {}, netip .AddrPortFrom (ip , tunnelsdk .TunnelPort ))
221+ r = r .WithContext (ctx )
222+
228223 rp := httputil.ReverseProxy {
224+ // This can only happen when it fails to dial.
225+ ErrorHandler : func (w http.ResponseWriter , r * http.Request , err error ) {
226+ httpapi .Write (ctx , rw , http .StatusBadGateway , tunnelsdk.Response {
227+ Message : "Failed to dial peer." ,
228+ Detail : err .Error (),
229+ })
230+ },
229231 Director : func (rp * http.Request ) {
230232 rp .URL .Scheme = "http"
231233 rp .URL .Host = r .Host
232234 rp .Host = r .Host
233235 },
234- Transport : & http.Transport {
235- DialContext : func (ctx context.Context , network , addr string ) (net.Conn , error ) {
236- return & tracingConnWrapper {
237- Conn : nc ,
238- span : span ,
239- ctx : ctx ,
240- }, nil
241- },
242- },
236+ Transport : api .transport ,
243237 }
244238
245239 span .End ()
0 commit comments