Skip to content

Commit

Permalink
Merge pull request #65 from Sylrelo/master
Browse files Browse the repository at this point in the history
Fix panic due to concurrent socket write
  • Loading branch information
azimjohn authored Jan 1, 2022
2 parents 023e53c + 42baa4d commit afad81e
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions jprq_cli/client/tunnel_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"bytes"
"context"
"fmt"
"github.com/azimjohn/jprq/jprq_http"
"github.com/gorilla/websocket"
"gopkg.in/mgo.v2/bson"
"io/ioutil"
"log"
"net/http"
urlpkg "net/url"
"os/user"

"github.com/azimjohn/jprq/jprq_http"
"github.com/gorilla/websocket"
"gopkg.in/mgo.v2/bson"
)

type HTTPTunnel struct {
Expand All @@ -21,6 +22,20 @@ type HTTPTunnel struct {
Error string `bson:"error"`
}

var writeSocket chan []byte

func socketMessageDispatch(ws *websocket.Conn) {
writeSocket = make(chan []byte)

for {
bytes := <-writeSocket
err := ws.WriteMessage(websocket.BinaryMessage, bytes)
if err != nil {
fmt.Printf("Error Sending Message to Server: %s", err)
}
}
}

func openHTTPTunnel(port int, host string, subdomain string, ctx context.Context) {
if subdomain == "" {
u, err := user.Current()
Expand Down Expand Up @@ -65,14 +80,15 @@ func openHTTPTunnel(port int, host string, subdomain string, ctx context.Context
defer close(requests)

go handleHTTPRequests(ws, requests)
go socketMessageDispatch(ws)

out:
for {
select {
case <-ctx.Done():
break out
case request := <-requests:
go handleHTTPRequest(ws, tunnel.Token, port, request)
go handleHTTPRequest(tunnel.Token, port, request)
}
}

Expand All @@ -94,7 +110,7 @@ func handleHTTPRequests(ws *websocket.Conn, requests chan<- jprq_http.RequestMes
}
}

func handleHTTPRequest(ws *websocket.Conn, token string, port int, r jprq_http.RequestMessage) {
func handleHTTPRequest(token string, port int, r jprq_http.RequestMessage) {
url := fmt.Sprintf("http://127.0.0.1:%d%s", port, r.URL)
request, err := http.NewRequest(r.Method, url, bytes.NewReader(r.Body))
if err != nil {
Expand Down Expand Up @@ -136,11 +152,7 @@ func handleHTTPRequest(ws *websocket.Conn, token string, port int, r jprq_http.R
return
}

err = ws.WriteMessage(websocket.BinaryMessage, message)
if err != nil {
fmt.Printf("Error Sending Message to Server: %s", err)
return
}
writeSocket <- message

fmt.Println(r.Method, r.URL, responseMessage.Status)
}

0 comments on commit afad81e

Please sign in to comment.