<commit_before>/*
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * 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 ofthe 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 specificlanguage governing permissions and
 * limitations under the License.
 *
 */

package websocket

import (
	fmt "fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	auth "github.com/abbot/go-http-auth"
	"github.com/gorilla/websocket"

	"github.com/skydive-project/skydive/common"
	shttp "github.com/skydive-project/skydive/http"
	"github.com/skydive-project/skydive/logging"
	"github.com/skydive-project/skydive/rbac"
)

type clientPromoter func(c *wsIncomingClient) (Speaker, error)

// IncomerHandler incoming client handler interface.
type IncomerHandler func(*websocket.Conn, *auth.AuthenticatedRequest, clientPromoter) (Speaker, error)

// Server implements a websocket server. It owns a Pool of incoming Speakers.
type Server struct {
	common.RWMutex
	*incomerPool
	server         *shttp.Server
	incomerHandler IncomerHandler
	opts           ServerOpts
}

// ServerOpts defines server options
type ServerOpts struct {
	WriteCompression bool
	QueueSize        int
	PingDelay        time.Duration
	PongTimeout      time.Duration
	Logger           logging.Logger
}

func getRequestParameter(r *http.Request, name string) string {
	param := r.Header.Get(name)
	if param == "" {
		param = r.URL.Query().Get(strings.ToLower(name))
	}
	return param
}

func (s *Server) serveMessages(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	s.opts.Logger.Debugf("Enforcing websocket for %s, %s", s.name, r.Username)
	if rbac.Enforce(r.Username, "websocket", s.name) == false {
		w.Header().Set("Connection", "close")
		w.WriteHeader(http.StatusForbidden)
		return
	}

	// if X-Host-ID specified avoid having twice the same ID
	host := getRequestParameter(&r.Request, "X-Host-ID")
	if host == "" {
		host = r.RemoteAddr
	}
	s.opts.Logger.Debugf("Serving messages for client %s for pool %s", host, s.GetName())

	s.incomerPool.RLock()
	c := s.GetSpeakerByRemoteHost(host)
	if c != nil {
		s.opts.Logger.Errorf("host_id '%s' (%s) conflicts, same host_id used by %+v", host, r.RemoteAddr, c)
		s.incomerPool.RUnlock()
		w.Header().Set("Connection", "close")
		w.WriteHeader(http.StatusConflict)<commit_msg>websocket: remove data race in conflict message logging<commit_after>/*
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * 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 ofthe 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 specificlanguage governing permissions and
 * limitations under the License.
 *
 */

package websocket

import (
	fmt "fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	auth "github.com/abbot/go-http-auth"
	"github.com/gorilla/websocket"

	"github.com/skydive-project/skydive/common"
	shttp "github.com/skydive-project/skydive/http"
	"github.com/skydive-project/skydive/logging"
	"github.com/skydive-project/skydive/rbac"
)

type clientPromoter func(c *wsIncomingClient) (Speaker, error)

// IncomerHandler incoming client handler interface.
type IncomerHandler func(*websocket.Conn, *auth.AuthenticatedRequest, clientPromoter) (Speaker, error)

// Server implements a websocket server. It owns a Pool of incoming Speakers.
type Server struct {
	common.RWMutex
	*incomerPool
	server         *shttp.Server
	incomerHandler IncomerHandler
	opts           ServerOpts
}

// ServerOpts defines server options
type ServerOpts struct {
	WriteCompression bool
	QueueSize        int
	PingDelay        time.Duration
	PongTimeout      time.Duration
	Logger           logging.Logger
}

func getRequestParameter(r *http.Request, name string) string {
	param := r.Header.Get(name)
	if param == "" {
		param = r.URL.Query().Get(strings.ToLower(name))
	}
	return param
}

func (s *Server) serveMessages(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	s.opts.Logger.Debugf("Enforcing websocket for %s, %s", s.name, r.Username)
	if rbac.Enforce(r.Username, "websocket", s.name) == false {
		w.Header().Set("Connection", "close")
		w.WriteHeader(http.StatusForbidden)
		return
	}

	// if X-Host-ID specified avoid having twice the same ID
	host := getRequestParameter(&r.Request, "X-Host-ID")
	if host == "" {
		host = r.RemoteAddr
	}
	s.opts.Logger.Debugf("Serving messages for client %s for pool %s", host, s.GetName())

	s.incomerPool.RLock()
	c := s.GetSpeakerByRemoteHost(host)
	if c != nil {
		s.opts.Logger.Errorf("host_id '%s' (%s) conflicts, same host_id used by %s:%s", host, r.RemoteAddr, c.GetRemoteHost(), c.GetRemoteServiceType())
		s.incomerPool.RUnlock()
		w.Header().Set("Connection", "close")
		w.WriteHeader(http.StatusConflict)
{'fraction_non_alphanumeric': 0.11743838685586258, 'fraction_numerical': 0.002987303958177745, 'mean_word_length': 4.030046948356808, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4584098', 'n_tokens_mistral': 1787, 'n_tokens_neox': 1750, 'n_words': 493}