// Upgrade upgrades http connection to the websocket connection.
//
// It hijacks net.Conn from w and returns recevied net.Conn and
// bufio.ReadWriter. On successful handshake it returns Handshake struct
// describing handshake info.
506610
func (u HTTPUpgrader) Upgrade(r *http.Request, w http.ResponseWriter) (conn net.Conn, rw *bufio.ReadWriter, hs Handshake, err error) {
	// Hijack connection first to get the ability to write rejection errors the
	// same way as in Upgrader.
	hj, ok := w.(http.Hijacker)
	if ok {
		conn, rw, err = hj.Hijack()
	} else {
		err = ErrNotHijacker
	}
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// See https://tools.ietf.org/html/rfc6455#section-4.1
	// The method of the request MUST be GET, and the HTTP version MUST be at least 1.1.
	var nonce string
	if r.Method != http.MethodGet {
		err = ErrHandshakeBadMethod
	} else if r.ProtoMajor < 1 || (r.ProtoMajor == 1 && r.ProtoMinor < 1) {
		err = ErrHandshakeBadProtocol
	} else if r.Host == "" {
		err = ErrHandshakeBadHost
	} else if u := httpGetHeader(r.Header, headerUpgradeCanonical); u != "websocket" && !strEqualFold(u, "websocket") {
		err = ErrHandshakeBadUpgrade
	} else if c := httpGetHeader(r.Header, headerConnectionCanonical); c != "Upgrade" && !strHasToken(c, "upgrade") {
		err = ErrHandshakeBadConnection
	} else if nonce = httpGetHeader(r.Header, headerSecKeyCanonical); len(nonce) != nonceSize {
		err = ErrHandshakeBadSecKey
	} else if v := httpGetHeader(r.Header, headerSecVersionCanonical); v != "13" {
		// According to RFC6455:
		//
		// If this version does not match a version understood by the server,
		// the server MUST abort the WebSocket handshake described in this
		// section and instead send an appropriate HTTP error code (such as 426
		// Upgrade Required) and a |Sec-WebSocket-Version| header field
		// indicating the version(s) the server is capable of understanding.
		//
		// So we branching here cause empty or not present version does not
		// meet the ABNF rules of RFC6455:
		//
		// version = DIGIT | (NZDIGIT DIGIT) |
		// ("1" DIGIT DIGIT) | ("2" DIGIT DIGIT)
		// ; Limited to 0-255 range, with no leading zeros
		//
		// That is, if version is really invalid – we sent 426 status, if it
		// not present or empty – it is 400.
		if v != "" {
			err = ErrHandshakeUpgradeRequired
		} else {
			err = ErrHandshakeBadSecVersion
		}
	}
	if check := u.Protocol; err == nil && check != nil {
		ps := r.Header[headerSecProtocolCanonical]
		for i := 0; i < len(ps) && err == nil && hs.Protocol == ""; i++ {
			var ok bool
			hs.Protocol, ok = strSelectProtocol(ps[i], check)
			if !ok {
				err = ErrMalformedRequest
			}
		}
	}
	if check := u.Extension; err == nil && check != nil {
		xs := r.Header[headerSecExtensionsCanonical]
		for i := 0; i < len(xs) && err == nil; i++ {
			var ok bool
			hs.Extensions, ok = strSelectExtensions(xs[i], hs.Extensions, check)
			if !ok {
				err = ErrMalformedRequest
			}
		}
	}

	// Clear deadlines set by server.
	conn.SetDeadline(noDeadline)
	if t := u.Timeout; t != 0 {
		conn.SetWriteDeadline(time.Now().Add(t))
		defer conn.SetWriteDeadline(noDeadline)
	}

	var header handshakeHeader
	if h := u.Header; h != nil {
		header[0] = HandshakeHeaderHTTP(h)
	}
	if err == nil {
		httpWriteResponseUpgrade(rw.Writer, strToBytes(nonce), hs, header.WriteTo)
		err = rw.Writer.Flush()
	} else {
		var code int
		if rej, ok := err.(*rejectConnectionError); ok {
			code = rej.code
			header[1] = rej.header
		}
		if code == 0 {
			code = http.StatusInternalServerError
		}
		httpWriteResponseError(rw.Writer, err, code, header.WriteTo)
		// Do not store Flush() error to not override already existing one.
		rw.Writer.Flush()
	}
	return
}
254375
func Serve(w http.ResponseWriter, req *http.Request, handler func(ws *Conn)) {
	conn, err := websocketUpgrader.Upgrade(w, req, nil)
	if err != nil {
		logger.Errorf("problem initiating websocket: %v", err)
		return
	}
	handler(&Conn{conn})
}
963599
func (d *DebugUpgrader) Upgrade(conn io.ReadWriter) (hs ws.Handshake, err error) {
	var (
		// Take the Reader and Writer partst from conn to be probably replaced
		// below.
		r io.Reader = conn
		w io.Writer = conn
	)
	if onRequest := d.OnRequest; onRequest != nil {
		var buf bytes.Buffer
		// First, we must read the entire request.
		req, err := http.ReadRequest(bufio.NewReader(
			io.TeeReader(conn, &buf),
		))
		if err == nil {
			// Fulfill the buffer with the response body.
			io.Copy(ioutil.Discard, req.Body)
			req.Body.Close()
		}
		onRequest(buf.Bytes())

		r = io.MultiReader(
			&buf, conn,
		)
	}

	if onResponse := d.OnResponse; onResponse != nil {
		var buf bytes.Buffer
		// Intercept the response stream written by the Upgrade().
		w = io.MultiWriter(
			conn, &buf,
		)
		defer func() {
			onResponse(buf.Bytes())
		}()
	}

	return d.Upgrader.Upgrade(struct {
		io.Reader
		io.Writer
	}{r, w})
}
628868
func updateNetworks(ns structs.Networks, up structs.Networks, c *config.Config) structs.Networks {
	if c.NetworkInterface == "" {
		ns = up
	} else {
		// if a network is configured, use only that network
		// use the fingerprinted data
		for _, n := range up {
			if c.NetworkInterface == n.Device {
				ns = []*structs.NetworkResource{n}
			}
		}
		// if not matched, ns has the old data
	}
	if c.NetworkSpeed != 0 {
		for _, n := range ns {
			n.MBits = c.NetworkSpeed
		}
	}
	return ns
}
237114
func UpgradeHTTP(r *http.Request, w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, Handshake, error) {
	return DefaultHTTPUpgrader.Upgrade(r, w)
}
232956
func upgradeRequest(resp http.ResponseWriter, req *http.Request, o *Options) (*websocket.Conn, int, error) {
	if req.Method != "GET" {
		o.log("Method %s is not allowed", LogLevelWarning, req.RemoteAddr, req.Method)
		return nil, http.StatusMethodNotAllowed, errors.New("Method not allowed")
	}

	allowedOrigin := replacementRegexp.ReplaceAllString(o.AllowedOrigin, req.Host)
	if r, err := regexp.MatchString(allowedOrigin, req.Header.Get("Origin")); !r || err != nil {
		o.log("Origin %s is not allowed", LogLevelWarning, req.RemoteAddr, req.Host)
		return nil, http.StatusForbidden, errors.New("Origin not allowed")
	}

	o.log("Request to %s has been allowed for origin %s", LogLevelDebug, req.RemoteAddr, req.Host, req.Header.Get("Origin"))

	ws, err := websocket.Upgrade(resp, req, nil, 1024, 1024)
	if handshakeErr, ok := err.(websocket.HandshakeError); ok {
		o.log("Handshake failed: %s", LogLevelWarning, req.RemoteAddr, handshakeErr)
		return nil, http.StatusBadRequest, handshakeErr
	} else if err != nil {
		o.log("Handshake failed: %s", LogLevelWarning, req.RemoteAddr, err)
		return nil, http.StatusBadRequest, err
	}

	o.log("Connection established", LogLevelInfo, req.RemoteAddr)
	return ws, http.StatusOK, nil
}
754430
func IsWebsocketRequest(req *http.Request) bool {
	containsHeader := func(name, value string) bool {
		items := strings.Split(req.Header.Get(name), ",")
		for _, item := range items {
			if value == strings.ToLower(strings.TrimSpace(item)) {
				return true
			}
		}
		return false
	}
	return containsHeader(Connection, "upgrade") && containsHeader(Upgrade, "websocket")
}
708114
func upgrade(mgr Manager) error {
	// We'll start by fetching the service's current and latest version.
	ns := mgr.Namespace()
	currentVersion, err := mgr.CurrentVersion(ns)
	if err != nil {
		return err
	}
	versions := mgr.Versions()
	latestVersion := GetLatestVersion(versions)

	switch {
	// If the current version is greater than the latest, then the service
	// is attempting to revert to a previous version that's possibly
	// backwards-incompatible. To prevent this, we'll return an error
	// indicating so.
	case currentVersion > latestVersion:
		return ErrReversion

	// If the current version is behind the latest version, we'll need to
	// apply all of the newer versions in order to catch up to the latest.
	case currentVersion < latestVersion:
		versions := VersionsToApply(currentVersion, versions)
		mgrName := mgr.Name()
		ns := mgr.Namespace()

		for _, version := range versions {
			log.Infof("Applying %v migration #%d", mgrName,
				version.Number)

			// We'll only run a migration if there is one available
			// for this version.
			if version.Migration != nil {
				err := version.Migration(ns)
				if err != nil {
					log.Errorf("Unable to apply %v "+
						"migration #%d: %v", mgrName,
						version.Number, err)
					return err
				}
			}
		}

		// With all of the versions applied, we can now reflect the
		// latest version upon the service.
		if err := mgr.SetVersion(ns, latestVersion); err != nil {
			return err
		}

	// If the current version matches the latest one, there's no upgrade
	// needed and we can safely exit.
	case currentVersion == latestVersion:
	}

	return nil
}
1135801
func Update(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "text/plain")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
	var col, id, doc string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "id", &id) {
		return
	}
	defer r.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(r.Body)
	doc = string(bodyBytes)
	if doc == "" && !Require(w, r, "doc", &doc) {
		return
	}
	docID, err := strconv.Atoi(id)
	if err != nil {
		http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
		return
	}
	var newDoc map[string]interface{}
	if err := json.Unmarshal([]byte(doc), &newDoc); err != nil {
		http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", newDoc), 400)
		return
	}
	dbcol := HttpDB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	err = dbcol.Update(docID, newDoc)
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
		return
	}
}
634491
func (c *Connection) Update(data interface{}, params *url.Values) (*SolrUpdateResponse, error) {

	b, err := json2bytes(data)

	if err != nil {
		return nil, err
	}

	if params == nil {
		params = &url.Values{}
	}

	params.Set("wt", "json")

	r, err := HTTPPost(fmt.Sprintf("%s/%s/update/?%s", c.url.String(), c.core, params.Encode()), b, [][]string{{"Content-Type", "application/json"}}, c.username, c.password)

	if err != nil {
		return nil, err
	}
	resp, err := bytes2json(&r)
	if err != nil {
		return nil, err
	}
	// check error in resp
	if !successStatus(resp) || hasError(resp) {
		return &SolrUpdateResponse{Success: false, Result: resp}, nil
	}

	return &SolrUpdateResponse{Success: true, Result: resp}, nil
}
952324
func (s *BoltStateDB) Upgrade() error {
	// Check to see if the underlying DB needs upgrading.
	upgrade, err := NeedsUpgrade(s.db.BoltDB())
	if err != nil {
		return err
	}
	if !upgrade {
		// No upgrade needed!
		return nil
	}

	// Upgraded needed. Backup the boltdb first.
	backupFileName := filepath.Join(s.stateDir, "state.db.backup")
	if err := backupDB(s.db.BoltDB(), backupFileName); err != nil {
		return fmt.Errorf("error backing up state db: %v", err)
	}

	// Perform the upgrade
	if err := s.db.Update(func(tx *boltdd.Tx) error {
		if err := UpgradeAllocs(s.logger, tx); err != nil {
			return err
		}

		// Add standard metadata
		if err := addMeta(tx.BoltTx()); err != nil {
			return err
		}

		// Write the time the upgrade was done
		bkt, err := tx.CreateBucketIfNotExists(metaBucketName)
		if err != nil {
			return err
		}
		return bkt.Put(metaUpgradedKey, time.Now().Format(time.RFC3339))
	}); err != nil {
		return err
	}

	s.logger.Info("successfully upgraded state")
	return nil
}
1207515
func (h *Hook) Upgrade() error {
	match, err := h.matchesCurrent()
	if err != nil {
		return err
	}

	if !match {
		return nil
	}

	return h.write()
}
631221
func handleWsRequest(broker *wsBroker, w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		beeLogger.Log.Errorf("error while upgrading server connection: %v", err)
		return
	}

	client := &wsClient{
		broker: broker,
		conn:   conn,
		send:   make(chan []byte, 256),
	}
	client.broker.register <- client

	go client.writePump()
	client.readPump()
}
1148762
func (c *FakeValidatingWebhookConfigurations) Update(validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration) (result *v1beta1.ValidatingWebhookConfiguration, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(validatingwebhookconfigurationsResource, validatingWebhookConfiguration), &v1beta1.ValidatingWebhookConfiguration{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ValidatingWebhookConfiguration), err
}
394488
func (wh *Webhook) Update(client *messagebird.Client) error {
	var data struct {
		Data []Webhook `json:"data"`
	}
	if err := client.Request(&data, http.MethodPut, apiRoot+"/webhooks/"+wh.ID, wh); err != nil {
		return err
	}
	*wh = data.Data[0]
	return nil
}
580838
func (h *Client) update(ctx context.Context, req *rls.UpdateReleaseRequest) (*rls.UpdateReleaseResponse, error) {
	c, err := h.connect(ctx)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	rlc := rls.NewReleaseServiceClient(c)
	return rlc.UpdateRelease(ctx, req)
}
1297327
func (si *SolrInterface) Update(data interface{}, params *url.Values) (*SolrUpdateResponse, error) {
	if si.conn == nil {
		return nil, fmt.Errorf("No connection found for making request to solr")
	}
	return si.conn.Update(data, params)
}