// elevated means we try running as user
434913
func doRun(elevated bool) error {
	argsIndex := 1 // 0 is the name of this program, 1 is either the one to launch or the "wait" option

	if len(os.Args) < 2 {
		log.Fatal("ERROR: no arguments. Use [-wait] programname [arg arg arg]\n")
	}

	// Do this awkward thing so we can pass along the rest of the command line as-is

	doWait := false
	doHide := true
	for i := 1; i < 3 && (i+1) < len(os.Args); i++ {
		if strings.EqualFold(os.Args[argsIndex], "-wait") {
			argsIndex++
			doWait = true
		} else if strings.EqualFold(os.Args[argsIndex], "-show") {
			argsIndex++
			doHide = false
		}
	}
	attr := &syscall.ProcAttr{
		Files: []uintptr{uintptr(syscall.Stdin), uintptr(syscall.Stdout), uintptr(syscall.Stderr)},
		Env:   syscall.Environ(),
		Sys: &syscall.SysProcAttr{
			HideWindow:    doHide,
			CreationFlags: flagCreateNewConsole,
		},
	}
	fmt.Printf("Launching %s with args %v\n", os.Args[argsIndex], os.Args[argsIndex:])

	var err error
	var pid int

	if elevated {
		token, _ := getUserToken()

		pid, _, err = CreateProcessWithTokenW(token, os.Args[argsIndex:], attr)
		defer syscall.CloseHandle(syscall.Handle(token))
		if err != nil {
			fmt.Printf("CreateProcessWithTokenW error: %s\n", err.Error())
			return err
		}
	} else {
		pid, _, err = syscall.StartProcess(os.Args[argsIndex], os.Args[argsIndex:], attr)
	}

	if err != nil {
		fmt.Printf("StartProcess error: %s\n", err.Error())
		return err
	} else if doWait {
		p, err := os.FindProcess(pid)
		if err != nil {
			fmt.Printf("Launcher can't find %d\n", pid)
			return err
		}

		timeout := make(chan time.Time, 1)

		go func() {
			pstate, err := p.Wait()

			if err == nil && pstate.Success() {
				time.Sleep(100 * time.Millisecond)
			} else {
				fmt.Printf("Unsuccessful wait: Error %v, pstate %v\n", err, *pstate)
			}
			timeout <- time.Now()
		}()

		// Only wait 15 seconds because an erroring command was shown to hang
		// up an installer on Win7
		select {
		case _ = <-timeout:
			// success
		case <-time.After(15 * time.Second):
			fmt.Println("timed out")
		}
	}
	return nil
}
22403
func (s *Service) UpdateUser(ctx context.Context, id platform.ID, upd platform.UserUpdate) (*platform.User, error) {
	o, err := s.FindUserByID(ctx, id)
	if err != nil {
		return nil, &platform.Error{
			Err: err,
			Op:  OpPrefix + platform.OpUpdateUser,
		}
	}

	if upd.Name != nil {
		o.Name = *upd.Name
	}

	s.userKV.Store(o.ID.String(), o)

	return o, nil
}
434642
func (t *LLRB) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
	t.ascendRange(t.root, greaterOrEqual, lessThan, iterator)
}
269756
func validateUser(r *http.Request, event *common.EventInfo) error {

	// Find the calling user.
	parts := strings.Split(r.RemoteAddr, ":")
	if len(parts) != 3 {
		return fmt.Errorf("Invalid user context")
	}

	// Accept all requests from root users
	if parts[0] == "0" {
		return nil
	}

	// The target process must be valid.
	p, err := process.NewProcess(event.PID)
	if err != nil {
		return fmt.Errorf("Process not found")
	}

	// The UID of the calling process must match the UID of the target process.
	uids, err := p.Uids()
	if err != nil {
		return fmt.Errorf("Unknown user ID")
	}

	match := false
	for _, uid := range uids {
		if strconv.Itoa(int(uid)) == parts[0] {
			match = true
		}
	}

	if !match {
		return fmt.Errorf("Invalid user - no access to this process: %+v PARTS: %+v", event, parts)
	}

	return nil
}
1056508
func (e *Bootstrap) Run(m libkb.MetaContext) error {
	e.status.Registered = e.signedUp(m)

	// if any Login engine worked previously, then ActiveDevice will
	// be valid:
	validActiveDevice := m.G().ActiveDevice.Valid()

	// the only way for ActiveDevice to be valid is to be logged in
	// (and provisioned)
	e.status.LoggedIn = validActiveDevice
	if !e.status.LoggedIn {
		m.Debug("Bootstrap: not logged in")
		return nil
	}
	m.Debug("Bootstrap: logged in (valid active device)")

	var uv keybase1.UserVersion
	uv, e.status.DeviceID, e.status.DeviceName, _, _ = e.G().ActiveDevice.AllFields()
	e.status.Uid = uv.Uid
	e.status.Username = e.G().ActiveDevice.Username(m).String()
	m.Debug("Bootstrap status: uid=%s, username=%s, deviceID=%s, deviceName=%s", e.status.Uid, e.status.Username, e.status.DeviceID, e.status.DeviceName)

	// get user summaries
	ts := libkb.NewTracker2Syncer(e.G(), e.status.Uid, true)
	if e.G().ConnectivityMonitor.IsConnected(context.Background()) == libkb.ConnectivityMonitorYes {
		m.Debug("connected, loading self user upak for cache")
		arg := libkb.NewLoadUserArgWithMetaContext(m).WithUID(e.status.Uid)
		if _, _, err := e.G().GetUPAKLoader().Load(arg); err != nil {
			m.Debug("Bootstrap: error loading upak user for cache priming: %s", err)
		}

		m.Debug("connected, running full tracker2 syncer")
		if err := libkb.RunSyncer(m, ts, e.status.Uid, false /* loggedIn */, false /* forceReload */); err != nil {
			m.Warning("error running Tracker2Syncer: %s", err)
			return nil
		}
	} else {
		m.Debug("not connected, running cached tracker2 syncer")
		if err := libkb.RunSyncerCached(m, ts, e.status.Uid); err != nil {
			m.Warning("error running Tracker2Syncer (cached): %s", err)
			return nil
		}
	}
	e.usums = ts.Result()

	// filter usums into followers, following
	for _, u := range e.usums.Users {
		if u.IsFollower {
			e.status.Followers = append(e.status.Followers, u.Username)
		}
		if u.IsFollowee {
			e.status.Following = append(e.status.Following, u.Username)
		}
	}
	if chatHelper := e.G().ChatHelper; chatHelper != nil {
		e.status.UserReacjis = chatHelper.UserReacjis(m.Ctx(), e.status.Uid.ToBytes())
	}

	e.lookupFullname(m, uv)

	return nil
}
1062726
func (t *BTree) Ascend(iterator ItemIterator) {
	if t.root == nil {
		return
	}
	t.root.iterate(ascend, nil, nil, false, false, iterator)
}
1004832
func (c UserClient) LoadMySettings(ctx context.Context, sessionID int) (res UserSettings, err error) {
	__arg := LoadMySettingsArg{SessionID: sessionID}
	err = c.Cli.Call(ctx, "keybase.1.user.loadMySettings", []interface{}{__arg}, &res)
	return
}
333938
func UserRoot() string {
	//  pam_systemd sets XDG_RUNTIME_DIR but not other dirs.
	xdgDataHome := os.Getenv("XDG_DATA_HOME")
	if xdgDataHome != "" {
		dirs := strings.Split(xdgDataHome, ":")
		return filepath.Join(dirs[0], "buildkit")
	}
	home := os.Getenv("HOME")
	if home != "" {
		return filepath.Join(home, ".local", "share", "buildkit")
	}
	return Root
}
806087
func (f UserConversionFunc) User(chain []*x509.Certificate) (*authenticator.Response, bool, error) {
	return f(chain)
}
336849
func Authorized(caller *querypb.VTGateCallerID) bool {
	if allowAll {
		return true
	}

	user := caller.GetUsername()
	_, ok := acl[user]
	return ok
}
1104143
func (s *Simulation) RunSimulation(w http.ResponseWriter, req *http.Request) {
	log.Debug("RunSimulation endpoint running")
	s.runC <- struct{}{}
	w.WriteHeader(http.StatusOK)
}
127459
func (conn *Conn) User(ident, name string) {
	conn.Raw(USER + " " + ident + " 12 * :" + name)
}
424241
func (e *EmptyService) Up(ctx context.Context, options options.Up) error {
	return nil
}
1260356
func (r *Client) AddActualOrgUser(userRole UserRole) (StatusMessage, error) {
	var (
		raw  []byte
		resp StatusMessage
		err  error
	)
	if raw, err = json.Marshal(userRole); err != nil {
		return StatusMessage{}, err
	}
	if raw, _, err = r.post("api/org/users", nil, raw); err != nil {
		return StatusMessage{}, err
	}
	if err = json.Unmarshal(raw, &resp); err != nil {
		return StatusMessage{}, err
	}
	return resp, nil
}
1364531
func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool {
	if _, err := h.authorityForCert(services.UserCA, cert); err != nil {
		return false
	}

	return true
}
512289
func (v *CredentialAuthority) runLoop() {
	done := false
	for !done {
		select {
		case <-v.eng.GetPokeCh():
			// Noop, but poke main loop for testing.
		case <-v.shutdownCh:
			done = true
		case ca := <-v.checkCh:
			v.log.Debug("Checking %s", ca)
			u := v.makeUser(ca.uid)
			go u.sendCheck(ca)
		case uid := <-v.invalidateCh:
			if uw := v.users[uid]; uw != nil {
				v.log.Debug("Invalidating %s", uw)
				delete(v.users, uid)
				go uw.u.sendStop()
			}
		case ci := <-v.cleanItemCh:
			v.cleanSchedule = append(v.cleanSchedule, ci)
		}
		v.clean()
	}
}
1103754
func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) {
	req, err := dcontext.GetRequest(ctx)
	if err != nil {
		return nil, err
	}

	if req.Header.Get("Authorization") == "" {
		challenge := challenge{
			realm:   ac.realm,
			service: ac.service,
		}

		if len(accessRecords) > 0 {
			var scopes []string
			for _, access := range accessRecords {
				scopes = append(scopes, fmt.Sprintf("%s:%s:%s", access.Type, access.Resource.Name, access.Action))
			}
			challenge.scope = strings.Join(scopes, " ")
		}

		return nil, &challenge
	}

	ctx = auth.WithUser(ctx, auth.UserInfo{Name: "silly"})
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, auth.UserNameKey, auth.UserKey))

	return ctx, nil

}