Skip to content

Commit

Permalink
support server plugin feature
Browse files Browse the repository at this point in the history
  • Loading branch information
fatedier committed Dec 23, 2019
1 parent a57679f commit 91e46a2
Show file tree
Hide file tree
Showing 18 changed files with 410 additions and 9 deletions.
2 changes: 1 addition & 1 deletion client/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (

"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
"github.com/fatedier/frp/models/plugin"
plugin "github.com/fatedier/frp/models/plugin/client"
"github.com/fatedier/frp/models/proto/udp"
"github.com/fatedier/frp/utils/limit"
frpNet "github.com/fatedier/frp/utils/net"
Expand Down
1 change: 1 addition & 0 deletions client/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
PrivilegeKey: util.GetAuthKey(svr.cfg.Token, now),
Timestamp: now,
RunId: svr.runId,
Metas: svr.cfg.Metas,
}

if err = msg.WriteMsg(conn, loginMsg); err != nil {
Expand Down
10 changes: 10 additions & 0 deletions conf/frps_full.ini
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,13 @@ tcp_mux = true

# custom 404 page for HTTP requests
# custom_404_page = /path/to/404.html

[plugin.user-manager]
addr = 127.0.0.1:9000
path = /handler
ops = Login

[plugin.port-manager]
addr = 127.0.0.1:9001
path = /handler
ops = NewProxy
24 changes: 24 additions & 0 deletions models/config/server_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

ini "github.com/vaughan0/go-ini"

plugin "github.com/fatedier/frp/models/plugin/server"
"github.com/fatedier/frp/utils/util"
)

Expand Down Expand Up @@ -134,6 +135,8 @@ type ServerCommonConf struct {
// UserConnTimeout specifies the maximum time to wait for a work
// connection. By default, this value is 10.
UserConnTimeout int64 `json:"user_conn_timeout"`
// HTTPPlugins specify the server plugins support HTTP protocol.
HTTPPlugins map[string]plugin.HTTPPluginOptions `json:"http_plugins"`
}

// GetDefaultServerConf returns a server configuration with reasonable
Expand Down Expand Up @@ -167,6 +170,7 @@ func GetDefaultServerConf() ServerCommonConf {
HeartBeatTimeout: 90,
UserConnTimeout: 10,
Custom404Page: "",
HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
}
}

Expand All @@ -181,6 +185,8 @@ func UnmarshalServerConfFromIni(content string) (cfg ServerCommonConf, err error
return ServerCommonConf{}, err
}

UnmarshalPluginsFromIni(conf, &cfg)

var (
tmpStr string
ok bool
Expand Down Expand Up @@ -375,6 +381,24 @@ func UnmarshalServerConfFromIni(content string) (cfg ServerCommonConf, err error
return
}

func UnmarshalPluginsFromIni(sections ini.File, cfg *ServerCommonConf) {
for name, section := range sections {
if strings.HasPrefix(name, "plugin.") {
name = strings.TrimSpace(strings.TrimPrefix(name, "plugin."))
options := plugin.HTTPPluginOptions{
Name: name,
Addr: section["addr"],
Path: section["path"],
Ops: strings.Split(section["ops"], ","),
}
for i, _ := range options.Ops {
options.Ops[i] = strings.TrimSpace(options.Ops[i])
}
cfg.HTTPPlugins[name] = options
}
}
}

func (cfg *ServerCommonConf) Check() (err error) {
return
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
104 changes: 104 additions & 0 deletions models/plugin/server/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright 2019 fatedier, [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package plugin

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"reflect"
)

type HTTPPluginOptions struct {
Name string
Addr string
Path string
Ops []string
}

type httpPlugin struct {
options HTTPPluginOptions

url string
client *http.Client
}

func NewHTTPPluginOptions(options HTTPPluginOptions) Plugin {
return &httpPlugin{
options: options,
url: fmt.Sprintf("http://%s%s", options.Addr, options.Path),
client: &http.Client{},
}
}

func (p *httpPlugin) Name() string {
return p.options.Name
}

func (p *httpPlugin) IsSupport(op string) bool {
for _, v := range p.options.Ops {
if v == op {
return true
}
}
return false
}

func (p *httpPlugin) Handle(ctx context.Context, op string, content interface{}) (*Response, interface{}, error) {
r := &Request{
Version: APIVersion,
Op: op,
Content: content,
}
var res Response
res.Content = reflect.New(reflect.TypeOf(content)).Interface()
if err := p.do(ctx, r, &res); err != nil {
return nil, nil, err
}
return &res, res.Content, nil
}

func (p *httpPlugin) do(ctx context.Context, r *Request, res *Response) error {
buf, err := json.Marshal(r)
if err != nil {
return err
}
req, err := http.NewRequest("POST", p.url, bytes.NewReader(buf))
if err != nil {
return err
}
req = req.WithContext(ctx)
req.Header.Set("X-Frp-Reqid", GetReqidFromContext(ctx))
resp, err := p.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("do http request error code: %d", resp.StatusCode)
}
buf, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err = json.Unmarshal(buf, res); err != nil {
return err
}
return nil
}
105 changes: 105 additions & 0 deletions models/plugin/server/manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright 2019 fatedier, [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package plugin

import (
"context"
"errors"
"fmt"

"github.com/fatedier/frp/utils/util"
"github.com/fatedier/frp/utils/xlog"
)

type Manager struct {
loginPlugins []Plugin
newProxyPlugins []Plugin
}

func NewManager() *Manager {
return &Manager{
loginPlugins: make([]Plugin, 0),
newProxyPlugins: make([]Plugin, 0),
}
}

func (m *Manager) Register(p Plugin) {
if p.IsSupport(OpLogin) {
m.loginPlugins = append(m.loginPlugins, p)
}
if p.IsSupport(OpNewProxy) {
m.newProxyPlugins = append(m.newProxyPlugins, p)
}
}

func (m *Manager) Login(content *LoginContent) (*LoginContent, error) {
var (
res = &Response{
Reject: false,
Unchange: true,
}
retContent interface{}
err error
)
reqid, _ := util.RandId()
xl := xlog.New().AppendPrefix("reqid: " + reqid)
ctx := xlog.NewContext(context.Background(), xl)
ctx = NewReqidContext(ctx, reqid)

for _, p := range m.loginPlugins {
res, retContent, err = p.Handle(ctx, OpLogin, *content)
if err != nil {
xl.Warn("send Login request to plugin [%s] error: %v", p.Name(), err)
return nil, errors.New("send Login request to plugin error")
}
if res.Reject {
return nil, fmt.Errorf("%s", res.RejectReason)
}
if !res.Unchange {
content = retContent.(*LoginContent)
}
}
return content, nil
}

func (m *Manager) NewProxy(content *NewProxyContent) (*NewProxyContent, error) {
var (
res = &Response{
Reject: false,
Unchange: true,
}
retContent interface{}
err error
)
reqid, _ := util.RandId()
xl := xlog.New().AppendPrefix("reqid: " + reqid)
ctx := xlog.NewContext(context.Background(), xl)
ctx = NewReqidContext(ctx, reqid)

for _, p := range m.newProxyPlugins {
res, retContent, err = p.Handle(ctx, OpNewProxy, *content)
if err != nil {
xl.Warn("send NewProxy request to plugin [%s] error: %v", p.Name(), err)
return nil, errors.New("send NewProxy request to plugin error")
}
if res.Reject {
return nil, fmt.Errorf("%s", res.RejectReason)
}
if !res.Unchange {
content = retContent.(*NewProxyContent)
}
}
return content, nil
}
32 changes: 32 additions & 0 deletions models/plugin/server/plugin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2019 fatedier, [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package plugin

import (
"context"
)

const (
APIVersion = "0.1.0"

OpLogin = "Login"
OpNewProxy = "NewProxy"
)

type Plugin interface {
Name() string
IsSupport(op string) bool
Handle(ctx context.Context, op string, content interface{}) (res *Response, retContent interface{}, err error)
}
34 changes: 34 additions & 0 deletions models/plugin/server/tracer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2019 fatedier, [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package plugin

import (
"context"
)

type key int

const (
reqidKey key = 0
)

func NewReqidContext(ctx context.Context, reqid string) context.Context {
return context.WithValue(ctx, reqidKey, reqid)
}

func GetReqidFromContext(ctx context.Context) string {
ret, _ := ctx.Value(reqidKey).(string)
return ret
}
Loading

0 comments on commit 91e46a2

Please sign in to comment.