| // |
| 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 group |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "net" |
| 20 |
| 21 | "github.com/fatedier/frp/pkg/util/vhost" |
| 22 | ) |
| 23 |
| 24 | type HTTPSGroupController struct { |
| 25 | groupRegistry[*HTTPSGroup] |
| 26 | httpsMuxer *vhost.HTTPSMuxer |
| 27 | } |
| 28 |
| 29 | func NewHTTPSGroupController(httpsMuxer *vhost.HTTPSMuxer) *HTTPSGroupController { |
| 30 | return &HTTPSGroupController{ |
| 31 | groupRegistry: newGroupRegistry[*HTTPSGroup](), |
| 32 | httpsMuxer: httpsMuxer, |
| 33 | } |
| 34 | } |
| 35 |
| 36 | func (ctl *HTTPSGroupController) Listen( |
| 37 | ctx context.Context, |
| 38 | group, groupKey string, |
| 39 | routeConfig vhost.RouteConfig, |
| 40 | ) (l net.Listener, err error) { |
| 41 | for { |
| 42 | g := ctl.getOrCreate(group, func() *HTTPSGroup { |
| 43 | return NewHTTPSGroup(ctl) |
| 44 | }) |
| 45 | l, err = g.Listen(ctx, group, groupKey, routeConfig) |
| 46 | if err == errGroupStale { |
| 47 | continue |
| 48 | } |
| 49 | return |
| 50 | } |
| 51 | } |
| 52 |
| 53 | type HTTPSGroup struct { |
| 54 | baseGroup |
| 55 |
| 56 | domain string |
| 57 | ctl *HTTPSGroupController |
| 58 | } |
| 59 |
| 60 | func NewHTTPSGroup(ctl *HTTPSGroupController) *HTTPSGroup { |
| 61 | return &HTTPSGroup{ |
| 62 | ctl: ctl, |
| 63 | } |
| 64 | } |
| 65 |
| 66 | func (g *HTTPSGroup) Listen( |
| 67 | ctx context.Context, |
| 68 | group, groupKey string, |
| 69 | routeConfig vhost.RouteConfig, |
| 70 | ) (ln *Listener, err error) { |
| 71 | g.mu.Lock() |
| 72 | defer g.mu.Unlock() |
| 73 | if !g.ctl.isCurrent(group, func(cur *HTTPSGroup) bool { return cur == g }) { |
| 74 | return nil, errGroupStale |
| 75 | } |
| 76 | if len(g.lns) == 0 { |
| 77 | // the first listener, listen on the real address |
| 78 | httpsLn, errRet := g.ctl.httpsMuxer.Listen(ctx, &routeConfig) |
| 79 | if errRet != nil { |
| 80 | return nil, errRet |
| 81 | } |
| 82 |
| 83 | g.domain = routeConfig.Domain |
| 84 | g.initBase(group, groupKey, httpsLn, func() { |
| 85 | g.ctl.removeIf(g.group, func(cur *HTTPSGroup) bool { |
| 86 | return cur == g |
| 87 | }) |
| 88 | }) |
| 89 | ln = g.newListener(httpsLn.Addr()) |
| 90 | go g.worker(httpsLn, g.acceptCh) |
| 91 | } else { |
| 92 | // route config in the same group must be equal |
| 93 | if g.group != group || g.domain != routeConfig.Domain { |
| 94 | return nil, ErrGroupParamsInvalid |
| 95 | } |
| 96 | if g.groupKey != groupKey { |
| 97 | return nil, ErrGroupAuthFailed |
| 98 | } |
| 99 | ln = g.newListener(g.lns[0].Addr()) |
| 100 | } |
| 101 | return |
| 102 | } |