// SessionRead Read file session by sid.
// if file is not exist, create it.
// the file path is generated from sid string.
776588
func (fp *FileProvider) SessionRead(sid string) (Store, error) {
	filepder.lock.Lock()
	defer filepder.lock.Unlock()

	err := os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777)
	if err != nil {
		SLogger.Println(err.Error())
	}
	_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	var f *os.File
	if err == nil {
		f, err = os.OpenFile(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), os.O_RDWR, 0777)
	} else if os.IsNotExist(err) {
		f, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	} else {
		return nil, err
	}
	os.Chtimes(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), time.Now(), time.Now())
	var kv map[interface{}]interface{}
	b, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, err
	}
	if len(b) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = DecodeGob(b)
		if err != nil {
			return nil, err
		}
	}
	f.Close()
	ss := &FileSessionStore{sid: sid, values: kv}
	return ss, nil
}
257501
func readSdID(r io.RuneScanner) (string, error) {
	rv := &bytes.Buffer{}
	for {
		ch, _, err := r.ReadRune()
		if err != nil {
			return "", err
		}
		if ch == ' ' || ch == ']' {
			r.UnreadRune()
			return string(rv.Bytes()), nil
		}
		rv.WriteRune(ch)
	}
}
711756
func removeSessionFile(sid string) {
	sessionFile, err := getSessionFile(sid)
	if err != nil {
		return
	}
	os.Remove(sessionFile)
}
387306
func (fp *FileProvider) SessionInit(maxlifetime int64, savePath string) error {
	fp.maxlifetime = maxlifetime
	fp.savePath = savePath
	return nil
}
773640
func loadSessionV8(sid string) (*sessionV8, *probe.Error) {
	if !isSessionDirExists() {
		return nil, errInvalidArgument().Trace()
	}
	sessionFile, err := getSessionFile(sid)
	if err != nil {
		return nil, err.Trace(sid)
	}

	if _, e := os.Stat(sessionFile); e != nil {
		return nil, probe.NewError(e)
	}

	// Initialize new session.
	s := &sessionV8{
		Header: &sessionV8Header{
			Version: globalSessionConfigVersion,
		},
		SessionID: sid,
	}

	// Initialize session config loader.
	qs, e := quick.NewConfig(s.Header, nil)
	if e != nil {
		return nil, probe.NewError(e).Trace(sid, s.Header.Version)
	}

	if e = qs.Load(sessionFile); e != nil {
		return nil, probe.NewError(e).Trace(sid, s.Header.Version)
	}

	// Validate if the version matches with expected current version.
	sV8Header := qs.Data().(*sessionV8Header)
	if sV8Header.Version != globalSessionConfigVersion {
		msg := fmt.Sprintf("Session header version %s does not match mc session version %s.\n",
			sV8Header.Version, globalSessionConfigVersion)
		return nil, probe.NewError(errors.New(msg)).Trace(sid, sV8Header.Version)
	}

	s.mutex = new(sync.Mutex)
	s.Header = sV8Header

	sessionDataFile, err := getSessionDataFile(s.SessionID)
	if err != nil {
		return nil, err.Trace(sid, s.Header.Version)
	}

	dataFile, e := os.Open(sessionDataFile)
	if e != nil {
		return nil, probe.NewError(e)
	}
	s.DataFP = &sessionDataFP{false, dataFile}

	return s, nil
}
549965
func (s *SwarmSyncerServer) SessionIndex() (uint64, error) {
	return s.store.BinIndex(s.po), nil
}
885299
func (k *SimpleFS) SimpleFSRead(ctx context.Context,
	arg keybase1.SimpleFSReadArg) (_ keybase1.FileContent, err error) {
	ctx = k.makeContext(ctx)
	k.lock.RLock()
	h, ok := k.handles[arg.OpID]
	k.lock.RUnlock()
	if !ok {
		return keybase1.FileContent{}, errNoSuchHandle
	}
	opDesc := keybase1.NewOpDescriptionWithRead(
		keybase1.ReadArgs{
			OpID:   arg.OpID,
			Path:   h.path,
			Offset: arg.Offset,
			Size:   arg.Size,
		})
	ctx, err = k.startReadWriteOp(ctx, arg.OpID, keybase1.AsyncOps_READ, opDesc)
	if err != nil {
		return keybase1.FileContent{}, err
	}
	k.setProgressTotals(arg.OpID, int64(arg.Size), 1)
	defer func() {
		if err == nil {
			k.updateReadProgress(arg.OpID, 0, 1)
		}
	}()

	defer func() { k.doneReadWriteOp(ctx, arg.OpID, err) }()

	// Print this so we can correlate the ID in
	k.log.CDebugf(ctx, "Starting read for OpID=%X, offset=%d, size=%d",
		arg.OpID, arg.Offset, arg.Size)

	_, err = h.file.Seek(arg.Offset, io.SeekStart)
	if err != nil {
		return keybase1.FileContent{}, err
	}

	bs := make([]byte, arg.Size)
	// TODO: make this a proper buffered read so we can get finer progress?
	reader := &progressReader{k, arg.OpID, h.file}
	n, err := reader.Read(bs)
	if err != nil && err != io.EOF {
		return keybase1.FileContent{}, err
	}
	bs = bs[:n]
	return keybase1.FileContent{
		Data: bs,
	}, nil
}
664673
func (s *SimpleFSHandler) SimpleFSRead(ctx context.Context, arg keybase1.SimpleFSReadArg) (keybase1.FileContent, error) {
	ctx, cancel := s.wrapContextWithTimeout(ctx)
	defer cancel()
	cli, err := s.client()
	if err != nil {
		return keybase1.FileContent{}, err
	}
	return cli.SimpleFSRead(ctx, arg)
}
428321
func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	entry, err := req.Storage.Get(ctx, "config/connection")
	if err != nil {
		return nil, fmt.Errorf("failed to read connection configuration")
	}
	if entry == nil {
		return nil, nil
	}

	var config connectionConfig
	if err := entry.DecodeJSON(&config); err != nil {
		return nil, err
	}

	return &logical.Response{
		Data: map[string]interface{}{
			"max_open_connections": config.MaxOpenConnections,
		},
	}, nil
}
1369814
func (m *Manager) Read(sid string) (RawStore, error) {
	// Ensure we're trying to read a valid session ID
	if _, err := m.validSessionID(sid); err != nil {
		return nil, err
	}

	return m.provider.Read(sid)
}
11681
func (fp *FileProvider) SessionRegenerate(oldsid, sid string) (Store, error) {
	filepder.lock.Lock()
	defer filepder.lock.Unlock()

	err := os.MkdirAll(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])), 0777)
	if err != nil {
		SLogger.Println(err.Error())
	}
	err = os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777)
	if err != nil {
		SLogger.Println(err.Error())
	}
	_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	var newf *os.File
	if err == nil {
		return nil, errors.New("newsid exist")
	} else if os.IsNotExist(err) {
		newf, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	}

	_, err = os.Stat(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1]), oldsid))
	var f *os.File
	if err == nil {
		f, err = os.OpenFile(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1]), oldsid), os.O_RDWR, 0777)
		io.Copy(newf, f)
	} else if os.IsNotExist(err) {
		newf, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	} else {
		return nil, err
	}
	f.Close()
	os.Remove(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])))
	os.Chtimes(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), time.Now(), time.Now())
	var kv map[interface{}]interface{}
	b, err := ioutil.ReadAll(newf)
	if err != nil {
		return nil, err
	}
	if len(b) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = DecodeGob(b)
		if err != nil {
			return nil, err
		}
	}
	ss := &FileSessionStore{sid: sid, values: kv}
	return ss, nil
}
1193019
func (s *ScanService) sessionCreate(req *restful.Request, resp *restful.Response, sc *scan.Scan) {
	// TODO (m0sth8): Check permissions for this scan to create other session
	// TODO (m0sth8): Check permissions for this scan to create session with this plugin
	raw := &scan.Session{}
	if err := req.ReadEntity(raw); err != nil {
		logrus.Warn(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusBadRequest, services.WrongEntityErr)
		return
	}

	if raw.Step == nil {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("step is required"))
		return
	}

	if raw.Step.Plugin == "" {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("step.plugin is required"))
		return
	}

	//	if raw.Step.Conf == nil {
	//		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("step.conf is required"))
	//		return
	//	}

	if raw.Scan != sc.Id {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("wrong scan id"))
		return
	}
	if sc.Status != scan.StatusWorking {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("scan should have working status"))
		return
	}
	if raw.Parent == "" {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("parent field is required"))
		return
	}
	parent := sc.GetSession(raw.Parent)
	if parent == nil {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("parent not found"))
		return
	}
	if parent.Status != scan.StatusWorking {
		resp.WriteServiceError(http.StatusBadRequest, services.NewBadReq("parent should have working status"))
		return
	}

	mgr := s.Manager()
	defer mgr.Close()

	pl, err := mgr.Plugins.GetByName(raw.Step.Plugin)
	if err != nil {
		if mgr.IsNotFound(err) {
			resp.WriteServiceError(http.StatusBadRequest,
				services.NewBadReq(fmt.Sprintf("plugin %s is not found", raw.Step.Plugin)))
			return
		}
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
		return
	}

	now := time.Now().UTC()
	sess := scan.Session{
		Id:     mgr.NewId(),
		Status: scan.StatusCreated,
		Scan:   sc.Id,
		Parent: parent.Id,
		Step:   raw.Step,
		Plugin: pl.Id,
		Dates: scan.Dates{
			Created: &now,
			Updated: &now,
		},
	}

	parent.Children = append(parent.Children, &sess)
	if err := mgr.Scans.Update(sc); err != nil {
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
		return
	}

	s.Scheduler().UpdateScan(sc)

	resp.WriteHeader(http.StatusCreated)
	resp.WriteEntity(sess)
}
1240564
func (i *UI) rawRead(f *os.File) (string, error) {

	// In windows, Handle can be used to examine or modify the system resource.
	// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724457(v=vs.85).aspx
	handle := syscall.Handle(f.Fd())

	resetFunc, err := makeRaw(handle)
	if err != nil {
		return "", err
	}
	defer resetFunc()

	return i.rawReadline(f)
}
122646
func (s *DbSession) ReadFile(id, prefix string, file *File) error {
	f, err := s.gridFS(prefix).OpenId(bson.ObjectIdHex(id))
	if err != nil {
		return err
	}
	n := f.Size()
	if n == 0 {
		n = 8192
	}
	b := make([]byte, n)
	_, err = f.Read(b)

	err = f.Close()
	if err != nil {
		return err
	}

	file.ID = id
	file.Data = b
	file.Name = f.Name()
	file.ContentType = f.ContentType()

	return nil
}
1369524
func readFile(filePath, CertFile, KeyFile, CAFile string) ([]byte, error) {
	u, _ := url.Parse(filePath)
	p := getter.All(settings)

	// FIXME: maybe someone handle other protocols like ftp.
	getterConstructor, err := p.ByScheme(u.Scheme)

	if err != nil {
		return ioutil.ReadFile(filePath)
	}

	getter, err := getterConstructor(filePath, CertFile, KeyFile, CAFile)
	if err != nil {
		return []byte{}, err
	}
	data, err := getter.Get(filePath)
	return data.Bytes(), err
}
824920
func (c *Client) UploadSessionRecording(r events.SessionRecording) error {
	file := roundtrip.File{
		Name:     "recording",
		Filename: "recording",
		Reader:   r.Recording,
	}
	values := url.Values{
		"sid":       []string{string(r.SessionID)},
		"namespace": []string{r.Namespace},
	}
	_, err := c.PostForm(c.Endpoint("namespaces", r.Namespace, "sessions", string(r.SessionID), "recording"), values, file)
	if err != nil {
		return trace.Wrap(err)
	}
	return nil
}
263278
func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	entry, err := req.Storage.Get(ctx, "config/connection")
	if err != nil {
		return nil, fmt.Errorf("failed to read connection configuration")
	}
	if entry == nil {
		return nil, nil
	}

	return nil, nil
}