diff --git a/chatclient.go b/chatclient.go index 78f7196..6820a88 100644 --- a/chatclient.go +++ b/chatclient.go @@ -3,7 +3,6 @@ package main import ( "fmt" "html" - "net" "strings" "unicode" @@ -150,11 +149,7 @@ func (cl *Client) Unmod() { } func (cl *Client) Host() string { - host, _, err := net.SplitHostPort(cl.conn.RemoteAddr().String()) - if err != nil { - host = "err" - } - return host + return cl.conn.Host() } var dumbSpaces = []string{ diff --git a/connection.go b/connection.go index bc510dc..9e98375 100644 --- a/connection.go +++ b/connection.go @@ -1,6 +1,7 @@ package main import ( + "net" "sync" "github.com/gorilla/websocket" @@ -8,7 +9,8 @@ import ( type chatConnection struct { *websocket.Conn - mutex sync.Mutex + mutex sync.Mutex + forwardedFor string } func (cc *chatConnection) ReadData(data interface{}) error { @@ -24,3 +26,15 @@ func (cc *chatConnection) WriteData(data interface{}) error { return cc.WriteJSON(data) } + +func (cc *chatConnection) Host() string { + if len(cc.forwardedFor) > 0 { + return cc.forwardedFor + } + + host, _, err := net.SplitHostPort(cc.RemoteAddr().String()) + if err != nil { + return cc.RemoteAddr().String() + } + return host +} diff --git a/handlers.go b/handlers.go index d5c674c..0819419 100644 --- a/handlers.go +++ b/handlers.go @@ -96,7 +96,10 @@ func wsHandler(w http.ResponseWriter, r *http.Request) { } chatConn := &chatConnection{ - Conn: conn, + Conn: conn, + // If the server is behind a reverse proxy (eg, Nginx), look + // for this header to get the real IP address of the client. + forwardedFor: r.Header.Get("X-Forwarded-For"), } go func() { diff --git a/settings.go b/settings.go index fceda84..be18cf8 100644 --- a/settings.go +++ b/settings.go @@ -107,6 +107,10 @@ func (s *Settings) Save() error { } func (s *Settings) AddBan(host string, names []string) error { + if host == "127.0.0.1" { + return fmt.Errorf("Cannot add a ban for localhost.") + } + b := BanInfo{ Names: names, IP: host,