-#XXX: ensure we override /etc/profile, gets loaded after .zshenv
-source ~/.zshenv
+# NOTE:
+# our .zprofile is expensive, so we keep track of what has been run already,
+# and only set up what is necessary. additionally, we want to ensure that our
+# environment is set up as early as possible, so we also source .zprofile in
+# .zshenv for new non-login shells.
+#
+# these issues are handled by using these methods:
+# * the parent shell that starts the user's session after logging in to some
+# graphical environments may not be a login shell—due to misconfiguration
+# or otherwise—which means .zprofile is not ran and the environment is not
+# properly configured for any child processes.
+# * some desktop environments/graphical terminal emulators will start new
+# terminal windows with login shells, which runs .zprofile every time and
+# leads to noticably slow startup times.
+# * switching users without wiping the environment will result in paths and
+# variables intended for the old user being used for the new user. while
+# this may be considered an edge-case that should not be supported, there
+# are legitimate reasons to want to do this, and in any case the shell
+# should not choke or cause unexpected problems should it happen anyway.
-t="${TMPDIR:-/tmp}/home-$LOGNAME"
-h="$HOME/tmp"
-if [[ ! -e "$t" ]] {
- mkdir -m 700 "$t" > /dev/null 2>&1
- #TODO: check if dir exists after mkdir
+### cleanup
+# XXX: only call after relevant vars have been set up, defined early so that
+# below code can utilize it after they do so
+function _sev_zcleanup {
+ ## gpg forwarding
+ if [[ -d $_sev_gpg_forward_dir && ( -z $1 || $1 == 'gpg-forward' ) ]] {
+ # clean up forward dirs if its session is dead or we ask for it
+ find $_sev_gpg_forward_dir -mindepth 1 -maxdepth 1 -type d |
+ while {read -r x} {
+ # NOTE: the only way we can get here is if we have not been
+ # forwarded before, if the user asks for it, or during
+ # logout. if our own pid already has a dir, it is most likely
+ # stale, the user wants it removed, or something is very
+ # broken—in all 3 of these cases the best choice is remove it.
+ p=$(basename $x)
+ if {[[ -v _sev_gpg_forward_clean || $$ == $p ]] ||
+ ! kill -0 $p 2>/dev/null} {
+ find $x -mindepth 1 -maxdepth 1 | while {read -r y} {
+ # XXX: real dirs will stop unlink, consider it a feature
+ unlink $y
+ }
+ # don't force in case something important is still there
+ rmdir $x
+ }
+ }
+ # reset GNUPGHOME if we removed our own dir
+ if [[ $GNUPGHOME =~ '/.ssh_forward/\d+/*$' && ! -e $GNUPGHOME ]]
+ GNUPGHOME=${GNUPGHOME%$MATCH}
+ }
+
+ ## tmp
+ # NOTE: _sev_tmp is not unset so session dirs will not be recreated
+ # NOTE: XDG dirs that use our tmp are not unset here, they are in zlogout
+ if [[ -d $_sev_tmp && ( -z $1 || $1 == 'tmp' ) ]] {
+ # clean up tmp dirs if its session is dead or we ask for it
+ find $_sev_tmp -mindepth 1 -maxdepth 1 -name '.session.*' -type d |
+ while {read -r x} {
+ # NOTE: same rationale as above
+ p=${$(basename $x)#.session.}
+ if {[[ -v _sev_tmp_clean || $$ == $p ]] ||
+ ! kill -0 $p 2>/dev/null} {
+ rm -rf $x
+ }
+ }
+ }
+
+ unset x p y
+}
+
+### lang
+export CHARSET=${CHARSET:-UTF-8}
+export LANG=${LANG:-en_US.UTF-8}
+export LC_CTYPE=${LC_TYPE:-$LANG}
+
+### path
+# NOTE: we utilize the fact that unique arrays keep the first occurrence and
+# remove any further occurences to capture elements from the old PATH
+# that we did not anticipate and shift them to the front, since they are
+# probably important to the system
+if [[ ! -v _sev_setup_path || -o login ]] {
+ typeset -U path fpath
+ # add as many generic paths as possible to keep the order we want
+ # NOTE: /usr/{local,pkg,games} are unix/bsdisms
+ # XXX: PREFIX not validated, non-posix but Termux uses it
+ syspath=("$path[@]")
+ path=(~/{s,}bin
+ {~/.local,{$PREFIX,}{,/opt,/usr{,/local,pkg}}}/sbin
+ {~/.local,{$PREFIX,}{,/opt,/usr{,/local,pkg}}}/bin
+ /usr/{X11R{7,6}/bin,games})
+ ((len=$#path))
+ path=("$path[@]" "$syspath[@]")
+ # remove nonexistent and duplicate paths
+ for (( i = 1; i <= $#path; i++ )) {
+ if [[ ! -e $path[$i] ]] {
+ path[$i]=()
+ ((i <= len)) && ((len--))
+ ((i--))
+ continue
+ }
+ }
+ # shift valid system paths to the front if there are any left
+ ((len > 0 && len < $#path)) && path=("${(@)path[len + 1, -1]}" "${(@)path[1, len]}")
+ unset syspath len i
+ # include our zsh dir in fpath. unlike above, we always prefer our paths
+ fpath=(${ZDOTDIR:-~/.zsh}/functions/{*,Completions/*}(N) "$fpath[@]")
+ # FPATH is not exported by default
+ export FPATH
+ typeset +U path fpath
+ export _sev_setup_path=
+}
+
+### tmp
+# NOTE: specs say that POSIX tmp and XDG runtime directories should exist
+# until the last session is logged out (POSIX can exist for longer).
+# since we can't reliably keep track of sessions in a cross-platform
+# manner, the current implementation should use a separate directory per
+# toplevel session (i.e. SHLVL=1). this should placate most applications,
+# though it is not expressly spec compliant.
+if [[ ! -v _sev_tmp ]] {
+ _sev_tmp=~/tmp
+ # create personal tmp dir
+ t=${TMPDIR:-${TEMP:-${TMP:-/tmp}}}/.home-$LOGNAME
+ [[ ! -e $t ]] && mkdir -m700 $t 2>/dev/null
+ if [[ ! -d $t ]] {
+ [[ -o interactive ]] &&
+ print -P "%F{red}!!! Can't create tmpdir $t%f"
+ # fallback bare directories
+ [[ -h $_sev_tmp ]] && unlink $_sev_tmp 2>/dev/null
+ [[ ! -e $_sev_tmp ]] && mkdir -m700 $_sev_tmp 2>/dev/null
+ }
+ # link home tmp for convenience if there isn't anything meaningful there
+ [[ -h $_sev_tmp || ! -e $_sev_tmp ]] && ln -sfn $t $_sev_tmp 2>/dev/null
+ export _sev_tmp=$(realpath $_sev_tmp)
+ # ensure dir is clean
+ _sev_zcleanup tmp
+ # finally create our subdir for this session
+ h=$_sev_tmp/.session.$$
+ mkdir -m700 $h 2>/dev/null
+ export TMPDIR=$h TEMP=$h TMP=$h
+ unset t h
+}
+
+### xdg
+if [[ ! -v _sev_setup_xdg ]] {
+ # merge with any existing dirs and remove duplicates using unique arrays
+ # NOTE: include and then remove CONFIG_HOME and DATA_HOME to ensure they
+ # are not present in the array if it was added before we got to it
+ typeset -UT XDG_CONFIG_DIRS xdg_config_dirs
+ export XDG_CONFIG_HOME=~/etc
+ mkdir $XDG_CONFIG_HOME 2>/dev/null
+ xdg_config_dirs=($XDG_CONFIG_HOME ~/.config
+ {/opt,/usr/local,/usr/pkg,}/etc/xdg
+ "${XDG_CONFIG_DIRS:+${xdg_config_dirs[@]}}")
+ export XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS#$XDG_CONFIG_HOME}
+
+ typeset -UT XDG_DATA_DIRS xdg_data_dirs
+ export XDG_DATA_HOME=~/share
+ mkdir $XDG_DATA_HOME 2>/dev/null
+ xdg_data_dirs=($XDG_DATA_HOME ~/.local/share
+ /{opt,usr/local,usr/pkg,usr}/share
+ "${XDG_DATA_DIRS:+${xdg_data_dirs[@]}}")
+ export XDG_DATA_DIRS=${XDG_DATA_DIRS#$XDG_DATA_HOME}
+
+ mkdir ~/var 2>/dev/null
+ export XDG_STATE_HOME=~/var/lib
+ mkdir $XDG_STATE_HOME 2>/dev/null
+
+ if [[ -v _sev_tmp ]] {
+ export XDG_CACHE_HOME=$_sev_tmp/.xdg.cache
+ mkdir $XDG_CACHE_HOME 2>/dev/null
+
+ export XDG_RUNTIME_DIR=$TMPDIR/.xdg.runtime
+ # same as in tmpdir creation, ensure it doesn't exist
+ if [[ -h $XDG_RUNTIME_DIR ]]; then
+ unlink $XDG_RUNTIME_DIR 2>/dev/null
+ elif [[ -e $XDG_RUNTIME_DIR ]]; then
+ rm -rf $XDG_RUNTIME_DIR 2>/dev/null
+ fi
+ mkdir -m700 $XDG_RUNTIME_DIR 2>/dev/null
+ }
+
+ # source user dirs after other vars
+ [[ -e $XDG_CONFIG_HOME/user-dirs.dirs ]] &&
+ emulate sh -c "source $XDG_CONFIG_HOME/user-dirs.dirs"
+ export _sev_setup_xdg=
}
-#allow opaque entries to override
-if [[ ! -e "$h" ]] {
- ln -sf "$t" "$h" > /dev/null 2>&1
+
+### dbus
+if [[ ! -v DBUS_SESSION_BUS_ADDRESS && -v commands[dbus-launch] ]] {
+ eval $(dbus-launch)
+ export DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID
}
-unset t
-unset h
+
+### gpg home
+if [[ ! -v GNUPGHOME ]] {
+ export GNUPGHOME=~/etc/gnupg
+ if [[ -d ~/.gnupg ]] {
+ mv ~/.gnupg ~/etc/gnupg
+ }
+}
+
+### gpg agent + forwarding
+# NOTE: while ssh manages its auth sock in its protocol when ForwardSsh is
+# enabled, GPG must be forwarded manually over Unix socket. to support
+# this, we forward the restricted gpg-agent extra socket to the remote
+# host with a RemoteForward rule in ~/.ssh/config that uses the
+# _GNUPG_SOCK_* env vars. to avoid conflicts with other ssh sessions
+# where the same user is connecting to the same host from different
+# machines, gpg in each environment should utilize its own forwarded
+# socket, rather than replace the sockets in GNUPGHOME which will be
+# overridden on the next connection. previously, you could provide a path
+# to the agent socket in GPG_AGENT_INFO, but that was deprecated in GPG
+# v2.1. instead, we must clone GNUPGHOME with links and replace the agent
+# sockets there with the forwarded one.
+# NOTE: since Unix sockets are not supported under Windows, this will not work
+# under msys, cygwin, mingw, etc., but may work under wsl2.
+# HACK: without SendEnv, which is disabled by default in most sshd configs,
+# there is no foolproof way to prevent race conditions via filename
+# collisions or to pass the desired forward path to the remote host
+# environment. we just have to guess the path we choose is good on the
+# desination, and assume the newest matching socket is the correct one
+# after connecting. in theory, we could occlude the ssh binary on PATH
+# with an alias or script that would allow us to communicate with the
+# remote host before opening a shell, so that we can have the host
+# communicate back to the client where it wants a socket created or ask
+# the host if the path the client wants to use is writable. however, this
+# would open up too many edge cases where it wouldn't work or be clunky
+# (e.g. asking for password twice) to make it worth it.
+function _gpg_socketpath {
+ # dirs are percent-encoded: https://stackoverflow.com/a/64312099
+ echo ${1//(#b)%([[:xdigit:]](#c2))/${(#):-0x$match[1]}}
+}
+if [[ ! -v _sev_setup_gpg_forward && -v commands[gpg] ]] {
+ export _GNUPG_SOCK_DEST_BASE=/tmp/.gpg-agent-forward
+ export _GNUPG_SOCK_DEST_EXT=$(date +%s).$RANDOM
+ export _GNUPG_SOCK_DEST=$_GNUPG_SOCK_DEST_BASE.$_GNUPG_SOCK_DEST_EXT
+ export _sev_gpg_forward_dir=${GNUPGHOME:-~/.gnupg}/.ssh_forward
+ _sev_zcleanup gpg-forward
+
+ # find our forwarded socket
+ s=($_GNUPG_SOCK_DEST_BASE*(N=oc[1]))
+ if [[ -n $s && -v SSH_CLIENT ]] {
+ # create new forward dir
+ export _sev_setup_gpg_forward=
+ h=$_sev_gpg_forward_dir/$$
+ mkdir -pm700 $h
+ # XXX: is it safe to link scdaemon socket? can its name be changed?
+ for x (S.scdaemon gpg.conf gpg-agent.conf sshcontrol random_seed
+ pubring.kbx{,~} trustdb.gpg private-keys-v1.d crls.d) {
+ ln -s ${GNUPGHOME:-~/.gnupg}/$x $h
+ }
+ export GNUPGHOME=$h
+ unset h
+ for x in $(gpgconf --list-dirs | grep 'agent-.*-\?socket:'); do
+ x=$(_gpg_socketpath ${x/#agent-*socket:})
+ if [[ ! -v orig ]] {
+ # move forwarded socket to first valid agent socket path
+ # XXX: if tmp is on different filesystem this may not work
+ mv $s $x
+ orig=$x
+ } else {
+ # make links to forwarded socket for any others
+ ln -s $orig $x
+ }
+ done
+ unset x orig
+ }
+ unset s
+
+ # what we will forward if we start a new ssh connection
+ # NOTE: do this after setting up GNUPGHOME to pick up new socket path;
+ # if already connected over SSH, extra should be the remote one
+ export _GNUPG_SOCK_SRC=$(_gpg_socketpath \
+ $(gpgconf --list-dirs agent-extra-socket))
+} elif [[ ! -v _sev_setup_gpg_forward ]] {
+ # required for RemoteForward to not error out if the vars are unset
+ [[ ! -v _GNUPG_SOCK_SRC ]] && export _GNUPG_SOCK_SRC=/nonexistent
+ [[ ! -v _GNUPG_SOCK_DEST ]] && export _GNUPG_SOCK_DEST=/nonexistent
+}
+
+### gpg agent
+if [[ -v commands[gpg-connect-agent] && ( ! -v _sev_setup_gpgagent ||
+ ( -v _sev_first_display && -z $_sev_first_display ) ) ]] {
+ # avoid printing if we have already set up tty before
+ [[ ! -v _sev_setup_gpgagent && -o interactive ]] && p=true || p=false
+ if {$p} {
+ print -nP '%F{blue}>>>%f GPG: '
+ if [[ -v _sev_setup_gpg_forward ]] {
+ print -nP '%F{yellow}Forwarded agent '
+ } else {
+ print -nP '%F{green}Agent '
+ }
+ }
+ gpg-connect-agent /bye >/dev/null 2>&1
+ if [[ $? -ne 0 ]] {
+ $p && print -P '%F{red}communication error'
+ } else {
+ if [[ ! -v _sev_setup_gpg_forward ]] {
+ if [[ ${+GPG_TTY} -eq 0 && -o interactive ]]
+ export GPG_TTY=$(tty)
+ if [[ ( -v DISPLAY || -v WAYLAND_DISPLAY ) &&
+ ${PINENTRY_USER_DATA/USE_TTY=0} == $PINENTRY_USER_DATA ]]
+ export PINENTRY_USER_DATA=USE_TTY=$((
+ ${+DISPLAY} + ${+WAYLAND_DISPLAY} == 0))
+ # XXX: don't know if gpg-agent supports comments after directives
+ # XXX: path could have #
+ sed -Ei 's#^([[:space:]]*pinentry-program[[:space:]]).*$#\1'${commands[pinentry]:-/dev/null}'#' \
+ ${GNUPGHOME:-~/.gnupg}/gpg-agent.conf
+ # XXX: could check for changes before doing this to save perf
+ gpg-connect-agent RELOADAGENT UPDATESTARTUPTTY /bye >/dev/null 2>&1
+ if {$p} {
+ gpg-connect-agent /subst /serverpid \
+ "/echo pid \${get serverpid} on $GPG_TTY" /bye 2>/dev/null
+ print -nP '%f'
+ }
+ } elif {$p} {
+ print -P '%f'
+ }
+ export _sev_setup_gpgagent=
+ }
+ unset p
+}
+
+### ssh agent
+if [[ ! -v _sev_setup_ssh ]] {
+ # NOTE: preferred order of agents to check: okcagent, gnupg, openssh
+ # first block takes care of okcagent and openssh, second gnupg
+ # XXX: doesn't actually check if ssh is enabled in gpg
+ [[ -o interactive ]] && print -nP '%F{blue}>>>%f SSH: %F{green}'
+ if [[ ! -v SSH_AUTH_SOCK && ( -v commands[okc-ssh-agent] ||
+ ( -v commands[ssh-agent] && ! -v commands[gpg] ) ) ]] {
+ okc=${commands[okc-ssh-agent]:+okc-}
+ e=$_sev_tmp/${okc}ssh-agent-exports
+ typeset sock=
+ typeset -i pid=
+ if [[ -f $e ]] {
+ IFS=$'\0' read -r sock pid <$e
+ }
+ if [[ -S $sock && $pid > 0 ]] && kill -0 $pid; then
+ [[ -o interactive ]] && print -P "Reusing agent PID $pid%f"
+ export SSH_AUTH_SOCK=$sock
+ export SSH_AGENT_PID=$pid
+ else
+ # TODO: ensure ssh-agent path looks legit to avoid unsafe eval?
+ # XXX: doesn't appear to be any other way to handle redirection.
+ # because eval needs to write to current scope environment
+ # subshells can't be used to capture output and print.
+ c='TMPDIR=$_sev_tmp ${okc}ssh-agent'
+ if [[ -o interactive ]] {
+ eval $(eval $=c)
+ print -nP '%f'
+ } else {
+ eval $(eval $=c) >/dev/null 2>&1
+ }
+ echo -n $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$e
+ unset c
+ fi
+ unset okc e sock pid
+ } elif [[ ! -v SSH_AUTH_SOCK && -v commands[gpg] ]] {
+ # since gpg should have been started above, just export and notify
+ if [[ -o interactive ]] {
+ if [[ -v _sev_setup_gpg_forward ]] {
+ echo 'Forwarded GPG agent'
+ } else {
+ gpg-connect-agent /subst /serverpid \
+ '/echo GPG agent pid ${get serverpid}' /bye
+ }
+ print -nP '%f'
+ }
+ export SSH_AUTH_SOCK=$(_gpg_socketpath \
+ $(gpgconf --list-dirs agent-ssh-socket))
+ } elif [[ -v SSH_AUTH_SOCK ]] {
+ [[ -o interactive ]] && print -P 'Preconfigured agent%f'
+ } else {
+ [[ -o interactive ]] && print -P '%F{red}No agent available%f'
+ }
+
+ export _sev_setup_ssh=
+}
+unfunction _gpg_socketpath
+
+### perl local lib
+[[ -v commands[perl] && -d $XDG_DATA_HOME/perl5/lib/perl5 &&
+ ! -v PERL_LOCAL_LIB_ROOT ]] &&
+ eval $(perl -I$XDG_DATA_HOME/perl5/lib/perl5 \
+ -Mlocal::lib=$XDG_DATA_HOME/perl5 2>/dev/null)
+
+
+### load site-specific
+if [[ -f ~/.zprofile.local ]] { source ~/.zprofile.local }
+
+# vim: et sts=4 sw=4 ts=8 tw=79