// CreateWebSocketServer creates a new WS server that listens on the provided address.
510284
func CreateWebSocketServer(address string) (*WebSocketServer, error) {
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return nil, err
	}

	return NewWebSocketServer(listener), nil
}
842432
func (f *httpForwarder) serveWebSocket(w http.ResponseWriter, req *http.Request, ctx *handlerContext) {
	if f.log.GetLevel() >= log.DebugLevel {
		logEntry := f.log.WithField("Request", utils.DumpHttpRequest(req))
		logEntry.Debug("vulcand/oxy/forward/websocket: begin ServeHttp on request")
		defer logEntry.Debug("vulcand/oxy/forward/websocket: completed ServeHttp on request")
	}

	outReq := f.copyWebSocketRequest(req)

	dialer := websocket.DefaultDialer

	if outReq.URL.Scheme == "wss" && f.tlsClientConfig != nil {
		dialer.TLSClientConfig = f.tlsClientConfig.Clone()
		// WebSocket is only in http/1.1
		dialer.TLSClientConfig.NextProtos = []string{"http/1.1"}
	}
	targetConn, resp, err := dialer.DialContext(outReq.Context(), outReq.URL.String(), outReq.Header)
	if err != nil {
		if resp == nil {
			ctx.errHandler.ServeHTTP(w, req, err)
		} else {
			f.log.Errorf("vulcand/oxy/forward/websocket: Error dialing %q: %v with resp: %d %s", outReq.Host, err, resp.StatusCode, resp.Status)
			hijacker, ok := w.(http.Hijacker)
			if !ok {
				f.log.Errorf("vulcand/oxy/forward/websocket: %s can not be hijack", reflect.TypeOf(w))
				ctx.errHandler.ServeHTTP(w, req, err)
				return
			}

			conn, _, errHijack := hijacker.Hijack()
			if errHijack != nil {
				f.log.Errorf("vulcand/oxy/forward/websocket: Failed to hijack responseWriter")
				ctx.errHandler.ServeHTTP(w, req, errHijack)
				return
			}
			defer conn.Close()

			errWrite := resp.Write(conn)
			if errWrite != nil {
				f.log.Errorf("vulcand/oxy/forward/websocket: Failed to forward response")
				ctx.errHandler.ServeHTTP(w, req, errWrite)
				return
			}
		}
		return
	}

	// Only the targetConn choose to CheckOrigin or not
	upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
		return true
	}}

	utils.RemoveHeaders(resp.Header, WebsocketUpgradeHeaders...)
	utils.CopyHeaders(resp.Header, w.Header())

	underlyingConn, err := upgrader.Upgrade(w, req, resp.Header)
	if err != nil {
		f.log.Errorf("vulcand/oxy/forward/websocket: Error while upgrading connection : %v", err)
		return
	}
	defer func() {
		underlyingConn.Close()
		targetConn.Close()
		if f.websocketConnectionClosedHook != nil {
			f.websocketConnectionClosedHook(req, underlyingConn.UnderlyingConn())
		}
	}()

	errClient := make(chan error, 1)
	errBackend := make(chan error, 1)
	replicateWebsocketConn := func(dst, src *websocket.Conn, errc chan error) {

		forward := func(messageType int, reader io.Reader) error {
			writer, err := dst.NextWriter(messageType)
			if err != nil {
				return err
			}
			_, err = io.Copy(writer, reader)
			if err != nil {
				return err
			}
			return writer.Close()
		}

		src.SetPingHandler(func(data string) error {
			return forward(websocket.PingMessage, bytes.NewReader([]byte(data)))
		})

		src.SetPongHandler(func(data string) error {
			return forward(websocket.PongMessage, bytes.NewReader([]byte(data)))
		})

		for {
			msgType, reader, err := src.NextReader()

			if err != nil {
				m := websocket.FormatCloseMessage(websocket.CloseNormalClosure, fmt.Sprintf("%v", err))
				if e, ok := err.(*websocket.CloseError); ok {
					if e.Code != websocket.CloseNoStatusReceived {
						m = nil
						// Following codes are not valid on the wire so just close the
						// underlying TCP connection without sending a close frame.
						if e.Code != websocket.CloseAbnormalClosure &&
							e.Code != websocket.CloseTLSHandshake {

							m = websocket.FormatCloseMessage(e.Code, e.Text)
						}
					}
				}
				errc <- err
				if m != nil {
					forward(websocket.CloseMessage, bytes.NewReader([]byte(m)))
				}
				break
			}
			err = forward(msgType, reader)
			if err != nil {
				errc <- err
				break
			}
		}
	}

	go replicateWebsocketConn(underlyingConn, targetConn, errClient)
	go replicateWebsocketConn(targetConn, underlyingConn, errBackend)

	var message string
	select {
	case err = <-errClient:
		message = "vulcand/oxy/forward/websocket: Error when copying from backend to client: %v"
	case err = <-errBackend:
		message = "vulcand/oxy/forward/websocket: Error when copying from client to backend: %v"

	}
	if e, ok := err.(*websocket.CloseError); !ok || e.Code == websocket.CloseAbnormalClosure {
		f.log.Errorf(message, err)
	}
}
31737
func CreateNetServer(address string) (*NetServer, error) {
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return nil, err
	}

	return NewNetServer(listener), nil
}
166169
func (s *StdoutClient) CreateSocket() error {
	if s.FD == nil {
		s.FD = os.Stdout
	}
	return nil
}
635060
func NewWebsocketManager(funcMap map[string]*RPCFunc, logger *logging.Logger,
	wsConnOptions ...func(*wsConnection)) *WebsocketManager {
	return &WebsocketManager{
		funcMap: funcMap,
		Upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				// TODO ???
				return true
			},
		},
		logger:        logger,
		wsConnOptions: wsConnOptions,
	}
}
954850
func NewPushSocket() (*PushSocket, error) {
	s, err := NewSocket(AF_SP, PUSH)
	return &PushSocket{s}, err
}
1066109
func createNewSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
	lnrpc.SubServer, lnrpc.MacaroonPerms, error) {

	// We'll attempt to look up the config that we expect, according to our
	// subServerName name. If we can't find this, then we'll exit with an
	// error, as we're unable to properly initialize ourselves without this
	// config.
	routeServerConf, ok := configRegistry.FetchConfig(subServerName)
	if !ok {
		return nil, nil, fmt.Errorf("unable to find config for "+
			"subserver type %s", subServerName)
	}

	// Now that we've found an object mapping to our service name, we'll
	// ensure that it's the type we need.
	config, ok := routeServerConf.(*Config)
	if !ok {
		return nil, nil, fmt.Errorf("wrong type of config for "+
			"subserver %s, expected %T got %T", subServerName,
			&Config{}, routeServerConf)
	}

	// Before we try to make the new router service instance, we'll perform
	// some sanity checks on the arguments to ensure that they're useable.
	switch {
	case config.Router == nil:
		return nil, nil, fmt.Errorf("Router must be set to create " +
			"Routerpc")
	}

	return New(config)
}
278748
func IsWebSocketRequest(r *http.Request) bool {
	var _ interface{}
	_, hasUpgrade := r.Header["Upgrade"]
	_, hasSec := r.Header["Sec-Websocket-Version"]
	_, hasExt := r.Header["Sec-Websocket-Extensions"]
	_, hasKey := r.Header["Sec-Websocket-Key"]
	return hasUpgrade && hasSec && hasExt && hasKey
}
579344
func CreateUnixSocket(path string) (net.Listener, error) {
	// BSDs have a 104 limit
	if len(path) > 104 {
		return nil, errors.Errorf("%q: unix socket path too long (> 104)", path)
	}
	if err := os.MkdirAll(filepath.Dir(path), 0660); err != nil {
		return nil, err
	}
	if err := unix.Unlink(path); err != nil && !os.IsNotExist(err) {
		return nil, err
	}
	return net.Listen("unix", path)
}
548590
func (m *Manager) HandleHTTPWebSocket(pattern string) {
	log.Infof("workflow Manager listening to websocket traffic at %v", pattern)
	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if x := recover(); x != nil {
				errMsg := fmt.Sprintf("uncaught panic: %v", x)
				log.Error(errMsg)
				http.Error(w, errMsg, http.StatusInternalServerError)
			}
		}()

		// Check ACL.
		if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil {
			msg := fmt.Sprintf("WorkflowManager acl.CheckAccessHTTP failed: %v", err)
			log.Error(msg)
			http.Error(w, msg, http.StatusUnauthorized)
			return
		}

		// Upgrade to WebSocket.
		c, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Errorf("upgrade error: %v", err)
			return
		}
		defer c.Close()

		// Register the handler.
		tree, notifications, i, err := m.getAndWatchFullTree(r.URL)
		if err != nil {
			log.Warningf("GetAndWatchFullTree failed: %v", err)
			return
		}
		if notifications != nil {
			defer m.NodeManager().CloseWatcher(i)
		}

		// First we send the full dump
		if err := c.WriteMessage(websocket.TextMessage, tree); err != nil {
			log.Warningf("WriteMessage(tree) failed: %v", err)
			return
		}

		// If we didn't get a channel back (redirect case), we're done.
		// We will just return the redirect, and close the websocket.
		if notifications == nil {
			return
		}

		// Start a go routine to get messages, send them to a channel.
		recv := make(chan *ActionParameters, 10)
		go func() {
			for {
				mt, message, err := c.ReadMessage()
				if err != nil {
					log.Warningf("failed to read message from websocket: %v", err)
					close(recv)
					return
				}
				if mt != websocket.TextMessage {
					log.Warningf("weird message type: %v", mt)
				}

				ap := &ActionParameters{}
				if err := json.Unmarshal(message, ap); err != nil {
					log.Warningf("failed to JSON-decode message from websocket: %v", err)
					close(recv)
					return
				}
				recv <- ap
			}
		}()

		// Let's listen to the channels until we're done.
		for {
			select {
			case ap, ok := <-recv:
				if !ok {
					// The websocket was most likely closed.
					return
				}

				ctx := context.TODO()
				if err := m.NodeManager().Action(ctx, ap); err != nil {
					log.Warningf("Action failed: %v", err)
				}

			case message, ok := <-notifications:
				if !ok {
					// We ran out of space on the update
					// channel, so we had to close it.
					return
				}
				if err := c.WriteMessage(websocket.TextMessage, message); err != nil {
					log.Warningf("WriteMessage(tree) failed: %v", err)
					return
				}
			}
		}
	})
}
1056561
func NewSocket(i *websocket.Conn, c *Context, f *Fibre) *Socket {
	return &Socket{i, c, f, nil}
}
1147132
func DialWebsocket(uri string, cfg *config.Config) (*WebsocketSession, error) {
	u, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}

	h := http.Header{
		"Origin": {u.Scheme + "://" + u.Host},
	}

	serverID := threeDigits()
	sessionID := utils.RandomString(20)

	u = makeWebsocketURL(u, serverID, sessionID)

	conn, _, err := cfg.Websocket.Dial(u.String(), h)
	if err != nil {
		return nil, err
	}

	session := NewWebsocketSession(conn)
	session.id = sessionID
	session.req = &http.Request{
		URL:    u,
		Header: h,
	}

	return session, nil
}
458902
func (g *GSLB) CreateGSLBServer(ip string) *GSLBServer {
	return &GSLBServer{
		IPAddress: ip,
		Enabled:   "True",
		Weight:    "1",
	}
}
915865
func NewAtomicWebSocketSet() AtomicWebSocketSet {
	return AtomicWebSocketSet{
		sockets: map[uint64]*websocket.Conn{},
		mutex:   &sync.Mutex{},
	}
}
1322000
func NewServer() *Server {
	return &Server{tlsPeerNameFunc: defaultTlsPeerName, datagramPool: sync.Pool{
		New: func() interface{} {
			return make([]byte, 65536)
		},
	}}
}
600363
func New(name string, port uint16) *Server {
	// Create router
	router := http.NewServeMux()

	logPrefix := "[" + name + "] "

	// Create server
	s := &Server{
		name: name,
		server: &http.Server{
			Handler:  router,
			ErrorLog: log.New(os.Stderr, logPrefix, 0),
		},
		connSet:   &connSet{conns: make(map[*conn]struct{})},
		statusLog: log.New(os.Stdout, logPrefix, 0),
		liveCSS:   true,
	}
	s.setPort(port)

	// Handle JS
	router.HandleFunc("/livereload.js", jsHandler(s))

	// Handle reload requests
	router.HandleFunc("/livereload", webSocketHandler(s))

	return s
}
1127215
func NewBasicWebsocketServer(uri string) *WebsocketServer {
	logger.Println("NewBasicWebsocketServer")
	s, _ := NewWebsocketServer(map[string]Realm{uri: {}})
	return s
}