// Regenerate regenerates a session store from old session ID to new one.
554636
func (p *FileProvider) Regenerate(oldsid, sid string) (_ RawStore, err error) {
	if err := p.regenerate(oldsid, sid); err != nil {
		return nil, err
	}

	return p.Read(sid)
}
703048
func (s *RethinkStore) delete(session *sessions.Session) error {
	_, err := r.Table(s.Table).Get(session.ID).Delete().Run(s.Rethink)
	return err
}
115447
func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (session Store) {
	sid, err := manager.sessionID()
	if err != nil {
		return
	}
	cookie, err := r.Cookie(manager.config.CookieName)
	if err != nil || cookie.Value == "" {
		//delete old cookie
		session, _ = manager.provider.SessionRead(sid)
		cookie = &http.Cookie{Name: manager.config.CookieName,
			Value:    url.QueryEscape(sid),
			Path:     "/",
			HttpOnly: true,
			Secure:   manager.isSecure(r),
			Domain:   manager.config.Domain,
		}
	} else {
		oldsid, _ := url.QueryUnescape(cookie.Value)
		session, _ = manager.provider.SessionRegenerate(oldsid, sid)
		cookie.Value = url.QueryEscape(sid)
		cookie.HttpOnly = true
		cookie.Path = "/"
	}
	if manager.config.CookieLifeTime > 0 {
		cookie.MaxAge = manager.config.CookieLifeTime
		cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
	}
	if manager.config.EnableSetCookie {
		http.SetCookie(w, cookie)
	}
	r.AddCookie(cookie)

	if manager.config.EnableSidInHttpHeader {
		r.Header.Set(manager.config.SessionNameInHttpHeader, sid)
		w.Header().Set(manager.config.SessionNameInHttpHeader, sid)
	}

	return
}
789506
func (s *HTTPServer) SessionCreate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Default the session to our node + serf check + release session
	// invalidate behavior.
	args := structs.SessionRequest{
		Op: structs.SessionCreate,
		Session: structs.Session{
			Node:      s.agent.config.NodeName,
			Checks:    []types.CheckID{structs.SerfCheckID},
			LockDelay: 15 * time.Second,
			Behavior:  structs.SessionKeysRelease,
			TTL:       "",
		},
	}
	s.parseDC(req, &args.Datacenter)
	s.parseToken(req, &args.Token)

	// Handle optional request body
	if req.ContentLength > 0 {
		fixup := func(raw interface{}) error {
			if err := FixupLockDelay(raw); err != nil {
				return err
			}
			if err := FixupChecks(raw, &args.Session); err != nil {
				return err
			}
			return nil
		}
		if err := decodeBody(req, &args.Session, fixup); err != nil {
			resp.WriteHeader(http.StatusBadRequest)
			fmt.Fprintf(resp, "Request decode failed: %v", err)
			return nil, nil
		}
	}

	// Create the session, get the ID
	var out string
	if err := s.agent.RPC("Session.Apply", &args, &out); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return sessionCreateResponse{out}, nil
}
1331965
func (c *CookieOverseer) Regenerate(w http.ResponseWriter, r *http.Request) error {
	panic("cookie sessions do not use session ids")
}
265230
func (p *MemcacheProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
	if p.Exist(sid) {
		return nil, fmt.Errorf("new sid '%s' already exists", sid)
	}

	item := NewItem(sid, []byte(""), p.expire)
	if p.Exist(oldsid) {
		item, err = p.c.Get(oldsid)
		if err != nil {
			return nil, err
		} else if err = p.c.Delete(oldsid); err != nil {
			return nil, err
		}
		item.Key = sid
	}
	if err = p.c.Set(item); err != nil {
		return nil, err
	}

	var kv map[interface{}]interface{}
	if len(item.Value) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = session.DecodeGob(item.Value)
		if err != nil {
			return nil, err
		}
	}

	return NewMemcacheStore(p.c, sid, p.expire, kv), nil
}
19004
func (s *MemcacheStore) save(session *sessions.Session) error {

	key := s.KeyPrefix + session.ID

	switch s.StoreMethod {

	case StoreMethodSecureCookie:

		encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
			s.Codecs...)
		if err != nil {
			if s.Logging > 0 {
				log.Printf("gorilla-sessions-memcache: set (method: securecookie, encoding error: %v)", err)
			}
			return err
		}

		_, err = s.Client.Set(key, encoded, 0, uint32(session.Options.MaxAge), 0)
		if s.Logging > 0 {
			log.Printf("gorilla-sessions-memcache: set (method: securecookie, session name: %v, memcache key: %v, memcache value: %v, error: %v)", session.Name(), key, encoded, err)
		}
		if err != nil {
			return err
		}

		return nil

	case StoreMethodGob:

		buf := &bytes.Buffer{}
		enc := gob.NewEncoder(buf)
		err := enc.Encode(session.Values)
		if err != nil {
			if s.Logging > 0 {
				log.Printf("gorilla-sessions-memcache: set (method: gob, encoding error: %v)", err)
			}
			return err
		}
		bufbytes := buf.Bytes()

		_, err = s.Client.Set(key, string(bufbytes), 0, uint32(session.Options.MaxAge), 0)
		if s.Logging > 0 {
			log.Printf("gorilla-sessions-memcache: set (method: gob, session name: %v, memcache key: %v, memcache value len: %v, error: %v)", session.Name(), key, len(bufbytes), err)
		}
		if err != nil {
			return err
		}

		return nil

	case StoreMethodJson:

		vals := make(map[string]interface{}, len(session.Values))
		for k, v := range session.Values {
			ks, ok := k.(string)
			if !ok {
				err := fmt.Errorf("Non-string key value, cannot jsonize: %v", k)
				log.Printf("gorilla-sessions-memcache: set (method: json, encoding error: %v)", err)
				return err
			}
			vals[ks] = v
		}

		bufbytes, err := json.Marshal(vals)
		if err != nil {
			if s.Logging > 0 {
				log.Printf("gorilla-sessions-memcache: set (method: json, encoding error: %v)", err)
			}
			return err
		}

		_, err = s.Client.Set(key, string(bufbytes), 0, uint32(session.Options.MaxAge), 0)
		if s.Logging > 0 {
			log.Printf("gorilla-sessions-memcache: set (method: json, session name: %v, memcache key: %v, memcache value: %v, error: %v)", session.Name(), key, string(bufbytes), err)
		}
		if err != nil {
			return err
		}

		return nil

	default:
		panic("Unknown StoreMethod: " + string(s.StoreMethod))
	}

	panic("Unreachable")
	return nil
}
1316509
func (ds *DiskStorage) StorageGeneration() (initTime time.Time, random string, err error) {
	return ds.gen.StorageGeneration()
}
968480
func (pder *CookieProvider) SessionRegenerate(oldsid, sid string) (Store, error) {
	return nil, nil
}
1351544
func (s *Restore) Session(sess *structs.Session) error {
	// Insert the session.
	if err := s.tx.Insert("sessions", sess); err != nil {
		return fmt.Errorf("failed inserting session: %s", err)
	}

	// Insert the check mappings.
	for _, checkID := range sess.Checks {
		mapping := &sessionCheck{
			Node:    sess.Node,
			CheckID: checkID,
			Session: sess.ID,
		}
		if err := s.tx.Insert("session_checks", mapping); err != nil {
			return fmt.Errorf("failed inserting session check mapping: %s", err)
		}
	}

	// Update the index.
	if err := indexUpdateMaxTxn(s.tx, sess.ModifyIndex, "sessions"); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}
1346835
func (s *Session) Renew(id string, q *WriteOptions) (*SessionEntry, *WriteMeta, error) {
	r := s.c.newRequest("PUT", "/v1/session/renew/"+id)
	r.setWriteOptions(q)
	rtt, resp, err := s.c.doRequest(r)
	if err != nil {
		return nil, nil, err
	}
	defer resp.Body.Close()

	wm := &WriteMeta{RequestTime: rtt}

	if resp.StatusCode == 404 {
		return nil, wm, nil
	} else if resp.StatusCode != 200 {
		return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode)
	}

	var entries []*SessionEntry
	if err := decodeBody(resp, &entries); err != nil {
		return nil, nil, fmt.Errorf("Failed to read response: %v", err)
	}
	if len(entries) > 0 {
		return entries[0], wm, nil
	}
	return nil, wm, nil
}
1124074
func (m *MemoryStorer) ResetExpiry(key string) error {
	m.mut.RLock()
	session, ok := m.sessions[key]
	m.mut.RUnlock()
	if !ok {
		return errNoSession{}
	}

	session.expires = time.Now().UTC().Add(m.maxAge)
	m.sessions[key] = session
	return nil
}
1135429
func (s *Server) invalidateSession(id string) {
	defer metrics.MeasureSince([]string{"session_ttl", "invalidate"}, time.Now())

	// Clear the session timer
	s.sessionTimers.Del(id)

	// Create a session destroy request
	args := structs.SessionRequest{
		Datacenter: s.config.Datacenter,
		Op:         structs.SessionDestroy,
		Session: structs.Session{
			ID: id,
		},
	}

	// Retry with exponential backoff to invalidate the session
	for attempt := uint(0); attempt < maxInvalidateAttempts; attempt++ {
		_, err := s.raftApply(structs.SessionRequestType, args)
		if err == nil {
			s.logger.Printf("[DEBUG] consul.state: Session %s TTL expired", id)
			return
		}

		s.logger.Printf("[ERR] consul.session: Invalidation failed: %v", err)
		time.Sleep((1 << attempt) * invalidateRetryBase)
	}
	s.logger.Printf("[ERR] consul.session: maximum revoke attempts reached for session: %s", id)
}
717996
func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) {
	req, extra, err := helpers.ParseCSR(csr)
	if err != nil {
		return nil, err
	} else if len(extra) > 0 {
		return nil, errors.New("csr: trailing data in certificate request")
	}

	return x509.CreateCertificateRequest(rand.Reader, req, priv)
}
417729
func (s *MemorySession) Reset() error {
	// reset counter and stores
	s.Counter.Reset()
	s.Incoming.Reset()
	s.Outgoing.Reset()

	return nil
}
655748
func (lk *consulLock) renewSession() {
	for {
		err := lk.client.Session().RenewPeriodic(lk.ttl, lk.sessionID, nil, lk.stopChan)
		if err == nil || lk.IsReleased() {
			// If lock was released, exit this go routine
			return
		}

		// Create new consul session
		err = lk.createSession()
		if err != nil {
			log.Errorf("Error Creating session for lock %s. Err: %v", lk.keyName, err)
		}
	}

}
1202006
func (s *Session) Destroy(ctx context.Context) error {
	sd := s.getSessionDataFromContext(ctx)

	sd.mu.Lock()
	defer sd.mu.Unlock()

	err := s.Store.Delete(sd.token)
	if err != nil {
		return err
	}

	sd.status = Destroyed

	// Reset everything else to defaults.
	sd.token = ""
	sd.Deadline = time.Now().Add(s.Lifetime).UTC()
	for key := range sd.Values {
		delete(sd.Values, key)
	}

	return nil
}