You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
2.5 KiB
Go

package web
import (
"embed"
"io/fs"
"net/http"
4 years ago
"sync"
"github.com/gorilla/websocket"
"github.com/lqqyt2423/go-mitmproxy/addon"
4 years ago
"github.com/lqqyt2423/go-mitmproxy/flow"
_log "github.com/sirupsen/logrus"
)
var log = _log.WithField("at", "web addon")
//go:embed client/build
var assets embed.FS
func (web *WebAddon) echo(w http.ResponseWriter, r *http.Request) {
c, err := web.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
4 years ago
conn := newConn(c)
web.addConn(conn)
4 years ago
defer func() {
web.removeConn(conn)
4 years ago
c.Close()
}()
conn.readloop()
}
type WebAddon struct {
addon.Base
4 years ago
upgrader *websocket.Upgrader
4 years ago
conns []*concurrentConn
4 years ago
connsMu sync.RWMutex
}
4 years ago
func NewWebAddon(addr string) *WebAddon {
web := new(WebAddon)
web.upgrader = &websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
4 years ago
serverMux := new(http.ServeMux)
serverMux.HandleFunc("/echo", web.echo)
fsys, err := fs.Sub(assets, "client/build")
if err != nil {
panic(err)
}
4 years ago
serverMux.Handle("/", http.FileServer(http.FS(fsys)))
4 years ago
server := &http.Server{Addr: addr, Handler: serverMux}
log = log.WithField("in", "WebAddon")
web.conns = make([]*concurrentConn, 0)
go func() {
4 years ago
log.Infof("web interface start listen at %v\n", addr)
err := server.ListenAndServe()
log.Error(err)
}()
return web
}
func (web *WebAddon) addConn(c *concurrentConn) {
4 years ago
web.connsMu.Lock()
web.conns = append(web.conns, c)
4 years ago
web.connsMu.Unlock()
}
func (web *WebAddon) removeConn(conn *concurrentConn) {
4 years ago
web.connsMu.Lock()
defer web.connsMu.Unlock()
index := -1
for i, c := range web.conns {
if conn == c {
4 years ago
index = i
break
}
}
if index == -1 {
return
}
web.conns = append(web.conns[:index], web.conns[index+1:]...)
}
func (web *WebAddon) sendFlow(f *flow.Flow, msgFn func() *message) bool {
4 years ago
web.connsMu.RLock()
conns := web.conns
web.connsMu.RUnlock()
if len(conns) == 0 {
return false
4 years ago
}
msg := msgFn()
4 years ago
for _, c := range conns {
c.writeMessage(msg, f)
4 years ago
}
return true
4 years ago
}
4 years ago
func (web *WebAddon) Requestheaders(f *flow.Flow) {
web.sendFlow(f, func() *message {
return newMessageRequest(f)
})
}
func (web *WebAddon) Request(f *flow.Flow) {
web.sendFlow(f, func() *message {
return newMessageRequestBody(f)
})
}
func (web *WebAddon) Responseheaders(f *flow.Flow) {
web.sendFlow(f, func() *message {
return newMessageResponse(f)
})
4 years ago
}
func (web *WebAddon) Response(f *flow.Flow) {
web.sendFlow(f, func() *message {
return newMessageResponseBody(f)
})
4 years ago
}