// appSynRetrieveState retrieves state for the the application Syn packet.
// It creates a new connection by default
437967
func (d *Datapath) appSynRetrieveState(p *packet.Packet) (*connection.TCPConnection, error) {

	context, err := d.contextFromIP(true, p.Mark, p.SourcePort(), packet.IPProtocolTCP)
	if err != nil {
		return nil, err
	}

	if conn, err := d.appOrigConnectionTracker.GetReset(p.L4FlowHash(), 0); err == nil {
		return conn.(*connection.TCPConnection), nil
	}
	return connection.NewTCPConnection(context, p), nil
}
481056
func (c *Conn) recvSynAck() (err error) {
	mu.Lock()
	defer mu.Unlock()
	c.waitAck(1)
	if c.err != nil {
		err = c.err
	}
	c.synAcked = true
	c.updateCanWrite()
	return err
}
191798
func (c *Conn) ConnectionState() ConnectionState {
	c.handshakeMutex.Lock()
	defer c.handshakeMutex.Unlock()

	var state ConnectionState
	state.HandshakeComplete = c.handshakeComplete
	if c.handshakeComplete {
		state.Version = c.vers
		state.NegotiatedProtocol = c.clientProtocol
		state.DidResume = c.didResume
		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
		state.CipherSuite = c.cipherSuite
		state.PeerCertificates = c.peerCertificates
		state.VerifiedChains = c.verifiedChains
		state.ServerName = c.serverName
		state.SignedCertificateTimestamps = c.scts
		state.OCSPResponse = c.ocspResponse
		if !c.didResume {
			state.TLSUnique = c.firstFinished[:]
		}
	}

	return state
}
275794
func (process *TeleportProcess) syncRotationState(conn *Connector) (*rotationStatus, error) {
	connectors := process.getConnectors()
	ca, err := process.getCertAuthority(conn, services.CertAuthID{
		DomainName: conn.ClientIdentity.ClusterName,
		Type:       services.HostCA,
	}, false)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var status rotationStatus
	status.ca = ca
	for _, conn := range connectors {
		serviceStatus, err := process.syncServiceRotationState(ca, conn)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		if serviceStatus.needsReload {
			status.needsReload = true
		}
		if serviceStatus.phaseChanged {
			status.phaseChanged = true
		}
	}
	return &status, nil
}
69267
func (exp *explorerUI) SyncStatusAPIIntercept(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if exp.ShowingSyncStatusPage() {
			exp.HandleApiRequestsOnSync(w, r)
			return
		}
		// Otherwise, proceed to the next http handler.
		next.ServeHTTP(w, r)
	})
}
332511
func (a *MobileAppState) State() keybase1.MobileAppState {
	a.Lock()
	defer a.Unlock()
	return a.state
}
1132596
func (d *Datapath) appRetrieveState(p *packet.Packet) (*connection.TCPConnection, error) {
	hash := p.L4FlowHash()

	// If this ack packet is from Server, Did we see a network Syn for this server PU?
	conn, err := d.appReplyConnectionTracker.GetReset(hash, 0)
	if err == nil {
		if uerr := updateTimer(d.appReplyConnectionTracker, hash, conn.(*connection.TCPConnection)); uerr != nil {
			zap.L().Error("entry expired just before updating the timer", zap.String("flow", hash))
			return nil, uerr
		}

		return conn.(*connection.TCPConnection), nil
	}

	// If this ack packet is from client, Did we see an Application Syn packet before?
	conn, err = d.appOrigConnectionTracker.GetReset(hash, 0)
	if err == nil {
		if uerr := updateTimer(d.appOrigConnectionTracker, hash, conn.(*connection.TCPConnection)); uerr != nil {
			return nil, uerr
		}
		return conn.(*connection.TCPConnection), nil
	}

	if p.GetTCPFlags()&packet.TCPSynAckMask == packet.TCPAckMask {
		// Let's try if its an existing connection
		context, err := d.contextFromIP(true, p.Mark, p.SourcePort(), packet.IPProtocolTCP)
		if err != nil {
			return nil, errors.New("No context in app processing")
		}
		conn = connection.NewTCPConnection(context, p)
		conn.(*connection.TCPConnection).SetState(connection.UnknownState)
		return conn.(*connection.TCPConnection), nil
	}

	return nil, errNoConnFound
}
69898
func (kern *Kernel) LoadState(genesisDoc *genesis.GenesisDoc) (err error) {
	var existing bool
	existing, kern.Blockchain, err = bcm.LoadOrNewBlockchain(kern.database, genesisDoc, kern.Logger)
	if err != nil {
		return fmt.Errorf("error creating or loading blockchain state: %v", err)
	}

	if existing {
		kern.Logger.InfoMsg("Loading application state", "height", kern.Blockchain.LastBlockHeight())
		kern.State, err = state.LoadState(kern.database, execution.VersionAtHeight(kern.Blockchain.LastBlockHeight()))
		if err != nil {
			return fmt.Errorf("could not load persisted execution state at hash 0x%X: %v",
				kern.Blockchain.AppHashAfterLastBlock(), err)
		}

		if !bytes.Equal(kern.State.Hash(), kern.Blockchain.AppHashAfterLastBlock()) {
			return fmt.Errorf("state and blockchain disagree on app hash at height %d: "+
				"state gives %X, blockchain gives %X", kern.Blockchain.LastBlockHeight(),
				kern.State.Hash(), kern.Blockchain.AppHashAfterLastBlock())
		}

	} else {
		kern.Logger.InfoMsg("Creating new application state from genesis")
		kern.State, err = state.MakeGenesisState(kern.database, genesisDoc)
		if err != nil {
			return fmt.Errorf("could not build genesis state: %v", err)
		}

		if err = kern.State.InitialCommit(); err != nil {
			return err
		}
	}

	kern.Logger.InfoMsg("State loading successful")

	params := execution.ParamsFromGenesis(genesisDoc)
	kern.checker = execution.NewBatchChecker(kern.State, params, kern.Blockchain, kern.Logger)
	kern.committer = execution.NewBatchCommitter(kern.State, params, kern.Blockchain, kern.Emitter, kern.Logger, kern.exeOptions...)
	return nil
}
373762
func (c *ClusterClient) ReloadState() error {
	_, err := c.state.Reload()
	return err
}
932109
func vpnGatewayAttachStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	var start time.Time
	return func() (interface{}, string, error) {
		if start.IsZero() {
			start = time.Now()
		}

		resp, err := conn.DescribeVpnGateways(&ec2.DescribeVpnGatewaysInput{
			VpnGatewayIds: []*string{aws.String(id)},
		})

		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnGatewayID.NotFound" {
				resp = nil
			} else {
				log.Printf("[ERROR] Error on VpnGatewayStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		vpnGateway := resp.VpnGateways[0]
		if len(vpnGateway.VpcAttachments) == 0 {
			// No attachments, we're detached
			return vpnGateway, "detached", nil
		}

		vpnAttachment := vpnGatewayGetAttachment(vpnGateway)
		return vpnGateway, *vpnAttachment.State, nil
	}
}
64335
func (c context) GetAppStatePath() string {
	roamingDir, _ := roamingDataDir()
	return filepath.Join(roamingDir, "Keybase", "app-state.json")
}
1309626
func (actor Actor) RestageApplication(app Application, client NOAAClient) (<-chan *LogMessage, <-chan error, <-chan ApplicationStateChange, <-chan string, <-chan error) {
	messages, logErrs := actor.GetStreamingLogs(app.GUID, client)

	appState := make(chan ApplicationStateChange)
	allWarnings := make(chan string)
	errs := make(chan error)
	go func() {
		defer close(appState)
		defer close(allWarnings)
		defer close(errs)
		defer client.Close() // automatic close to prevent stale clients

		appState <- ApplicationStateStaging
		restagedApp, warnings, err := actor.CloudControllerClient.RestageApplication(ccv2.Application{
			GUID: app.GUID,
		})

		for _, warning := range warnings {
			allWarnings <- warning
		}
		if err != nil {
			errs <- err
			return
		}

		actor.waitForApplicationStageAndStart(Application(restagedApp), client, appState, allWarnings, errs)
	}()

	return messages, logErrs, appState, allWarnings, errs
}
1247463
func newAppConnectionState(nativeID, serviceID string, p *pucontext.PUContext, r *http.Request, originalDestination *net.TCPAddr) *connectionState {

	sourceIP := "0.0.0.0/0"
	sourcePort := 0
	if sourceAddress, err := net.ResolveTCPAddr("tcp", r.RemoteAddr); err == nil {
		sourceIP = sourceAddress.IP.String()
		sourcePort = sourceAddress.Port
	}

	return &connectionState{
		stats: &collector.FlowRecord{
			ContextID: nativeID,
			Destination: &collector.EndPoint{
				URI:        r.Method + " " + r.RequestURI,
				HTTPMethod: r.Method,
				Type:       collector.EndPointTypeExternalIP,
				Port:       uint16(originalDestination.Port),
				IP:         originalDestination.IP.String(),
				ID:         collector.DefaultEndPoint,
			},
			Source: &collector.EndPoint{
				Type:       collector.EnpointTypePU,
				ID:         p.ManagementID(),
				IP:         sourceIP,
				Port:       uint16(sourcePort),
				HTTPMethod: r.Method,
				URI:        r.Method + " " + r.RequestURI,
			},
			Action:      policy.Reject,
			L4Protocol:  packet.IPProtocolTCP,
			ServiceType: policy.ServiceHTTP,
			ServiceID:   serviceID,
			Tags:        p.Annotations(),
			PolicyID:    "default",
			Count:       1,
		},
	}
}
836928
func databaseConfigurationV1StateRefreshFunc(client *gophercloud.ServiceClient, cgroupID string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		i, err := configurations.Get(client, cgroupID).Extract()
		if err != nil {
			if _, ok := err.(gophercloud.ErrDefault404); ok {
				return i, "DELETED", nil
			}
			return nil, "", err
		}

		return i, "ACTIVE", nil
	}
}
827347
func (sm *StateMachine) LoadState(in *Msg) {
	tmp, err := json.Marshal(sm.state)
	if err != nil {
		sm.plugin.Log.Info("failed to marshal state for db.", err)
		return
	}

	// Using upsert to either insert and return a value or on conflict to
	// update and return a value doesn't work, leading to this longer form.
	// Could it be a Postgres bug? This can and should be optimized.
	if in.User.ID > 0 {
		q := `INSERT INTO states
		      (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)`
		_, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp,
			sm.plugin.Config.Name)
	} else {
		q := `INSERT INTO states
		      (key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)`
		_, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID,
			in.User.FlexIDType, tmp, sm.plugin.Config.Name)
	}
	if err != nil {
		if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` &&
			err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` {
			sm.plugin.Log.Info("could not insert value into states.", err)
			sm.state = 0
			return
		}
		if in.User.ID > 0 {
			q := `SELECT value FROM states
			      WHERE userid=$1 AND key=$2 AND pluginname=$3`
			err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey,
				sm.plugin.Config.Name)
		} else {
			q := `SELECT value FROM states
			      WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4`
			err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID,
				in.User.FlexIDType, StateKey, sm.plugin.Config.Name)
		}
		if err != nil {
			sm.plugin.Log.Info("failed to get value from state.", err)
			return
		}
	}
	var val int
	if err = json.Unmarshal(tmp, &val); err != nil {
		sm.plugin.Log.Info("failed unmarshaling state from db.", err)
		return
	}
	sm.state = val

	// Have we already entered a state?
	sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool()
	return
}
893117
func (st *State) GoalState() (application.GoalState, error) {
	var result params.GoalStateResults

	gs := application.GoalState{}

	args := params.Entities{
		Entities: []params.Entity{
			{Tag: st.unitTag.String()},
		},
	}

	err := st.facade.FacadeCall("GoalStates", args, &result)
	if err != nil {
		return gs, err
	}
	if len(result.Results) != 1 {
		return gs, errors.Errorf("expected 1 result, got %d", len(result.Results))
	}
	if err := result.Results[0].Error; err != nil {
		return gs, err
	}
	gs = goalStateFromParams(result.Results[0].Result)
	return gs, nil
}
406400
func (s *Swap) loadState(peer *protocols.Peer) (err error) {
	var peerBalance int64
	peerID := peer.ID()
	//only load if the current instance doesn't already have this peer's
	//balance in memory
	if _, ok := s.balances[peerID]; !ok {
		err = s.stateStore.Get(peerID.String(), &peerBalance)
		s.balances[peerID] = peerBalance
	}
	return
}