2 # our .zprofile can be expensive, so we keep track of what has been run
3 # already, and only set up what is necessary. this also allows us to re-source
4 # the file to reinitialize specific parts when desired.
6 # in order to ensure future interactive environments are set up as early as
7 # possible, we source this file from .zshenv for non-login shells, under some
8 # specific conditions outlined there.
10 # this file respects non-interactive sessions and will not intentionally emit
14 # XXX: only call after relevant vars have been set up, defined early so that
15 # below code can utilize it after they do so
16 function _sev_zcleanup {
18 if [[ -d $_sev_gpg_forward_dir && ( -z $1 || $1 == 'gpg-forward' ) ]] {
19 # clean up forward dirs if its session is dead or we ask for it
20 find $_sev_gpg_forward_dir -mindepth 1 -maxdepth 1 -type d |
22 # NOTE: the only way we can get here is if we have not been
23 # forwarded before, if the user asks for it, or during
24 # logout. if our own pid already has a dir, it is most likely
25 # stale, the user wants it removed, or something is very
26 # broken—in all 3 of these cases the best choice is remove it.
28 if {[[ -v _sev_gpg_forward_clean || $$ == $p ]] ||
29 ! kill -0 $p 2>/dev/null} {
30 find $x -mindepth 1 -maxdepth 1 | while {read -r y} {
31 # XXX: real dirs will stop unlink, consider it a feature
34 # don't force in case something important is still there
38 # reset GNUPGHOME if we removed our own dir
39 if [[ $GNUPGHOME =~ '/.ssh_forward/\d+/*$' && ! -e $GNUPGHOME ]]
40 GNUPGHOME=${GNUPGHOME%$MATCH}
44 # NOTE: _sev_tmp is not unset so session dirs will not be recreated
45 # NOTE: XDG dirs that use our tmp are not unset here, they are in zlogout
46 if [[ -d $_sev_tmp && ( -z $1 || $1 == 'tmp' ) ]] {
47 # clean up tmp dirs if its session is dead or we ask for it
48 find $_sev_tmp -mindepth 1 -maxdepth 1 -name '.session.*' -type d |
50 # NOTE: same rationale as above
51 p=${$(basename $x)#.session.}
52 if {[[ -v _sev_tmp_clean || $$ == $p ]] ||
53 ! kill -0 $p 2>/dev/null} {
63 # NOTE: need this for tmp, so confirm it exists.
64 # XXX: perms are not specified for XDG dirs except runtime, but I think 760
65 # makes the most sense. shouldn't break anything since no one else should
66 # be poking around in our dir.
67 [[ -e ~/.local ]] || mkdir -m760 ~/.local
70 # NOTE: specs say that POSIX tmp and XDG runtime directories should exist
71 # until the last session is logged out (POSIX can exist for longer).
72 # since we can't reliably keep track of sessions in a cross-platform
73 # manner, the current implementation should use a separate directory per
74 # toplevel session (i.e. SHLVL=1). this should placate most applications,
75 # though it is not expressly spec compliant. this may also cause problems
76 # with disowned applications that still try to use the directories after
77 # the toplevel shell has already logged out and the dirs removed, but the
78 # chances of that are slim.
79 if [[ ! -v _sev_tmp ]] {
80 # create personal TMPDIR under system tmp
81 t=${TMPDIR:-${TEMPDIR:-${TEMP:-${TMP:-/tmp}}}}/.home-$LOGNAME
82 [[ -e $t ]] || mkdir -m700 $t 2>/dev/null
85 # fallback TMPDIR to bare local directory or existing softlink
86 [[ -o interactive ]] &&
87 print -P "%F{orange}*** Can't create tmp dir $t, using $_sev_tmp%f"
88 [[ -h $_sev_tmp && ! -d _sev_tmp ]] && unlink $_sev_tmp 2>/dev/null
89 [[ ! -e $_sev_tmp ]] && mkdir -m700 $_sev_tmp 2>/dev/null
90 if [[ ! -d $_sev_tmp ]] {
91 _sev_tmp=${$(mktemp 2>/dev/null):/tmp}
92 [[ -o interactive ]] &&
93 print -P "%F{red}!!! Can't create tmp dir, using $_sev_tmp%f"
95 } elif [[ -f $_sev_tmp || ( -d $_sev_tmp && ! -h $_sev_tmp ) ]] {
96 # file or non-softlink directory is on our local dir
97 [[ -o interactive ]] &&
98 print -P "%F{orange}*** $_sev_tmp exists, can't link to tmp dir $t, ignoring it%f"
101 # link local dir to tmp dir
102 if [[ -h $_sev_tmp && $_sev_tmp:P != $t:P ]] {
103 [[ -o interactive ]] &&
104 print -P "%F{orange}*** $_sev_tmp links to ${_sev_tmp:P} and not ${t:P}, unlinking it%f"
105 # XXX: race condition for existing sessions still using this dir
106 unlink $_sev_tmp 2>/dev/null
108 ln -s $t $_sev_tmp 2>/dev/null
110 if [[ -v _sev_tmp ]] {
111 # ensure dir is clean
113 # finally create our subdir for this session
114 t=$_sev_tmp/.session.$$
115 if ! mkdir -m700 $t 2>/dev/null; then
116 [[ -o interactive ]] &&
117 print -P "%F{red}!!! Can't create session tmp subdir $t, using $_sev_tmp%f"
120 export _sev_tmp TMPDIR=$t TEMPDIR=$t TEMP=$t TMP=$t
126 if [[ ! -v _sev_setup_xdg ]] {
127 ## merge with any existing dirs and remove duplicates using unique arrays
128 # NOTE: we are accepting whatever value might be set for CONFIG and DATA;
129 # if it wasn't set, we just use default and leave it unset
130 # NOTE: include and then remove CONFIG_HOME and DATA_HOME to ensure they
131 # are not present in the array if it was added before we got to it
133 # source user dirs before other vars; technically it is against spec to
134 # include any of the below dirs there, but you never know what crazy shit
135 # people will do. I rather handle them sanely with our own code than let
136 # them override after the fact.
137 [[ -e $XDG_CONFIG_HOME/user-dirs.dirs ]] &&
138 emulate sh -c "source $XDG_CONFIG_HOME/user-dirs.dirs"
140 typeset -UT XDG_DATA_DIRS xdg_data_dirs
141 if [[ -v XDG_DATA_HOME ]] {
143 } elif [[ ! -e ~/.local/share ]] {
144 mkdir -m760 ~/.local/share
146 xdg_data_dirs=($XDG_DATA_HOME /{opt,usr/local,usr/pkg,usr}/share
147 ${XDG_DATA_DIRS:+"$xdg_data_dirs[@]"})
148 # XXX: if colons are not escaped, could remove unintended part of string
149 # TODO: remove empty element via array not scalar
150 export XDG_DATA_DIRS=${XDG_DATA_DIRS#$XDG_DATA_HOME:}
152 typeset -UT XDG_CONFIG_DIRS xdg_config_dirs
153 if [[ -v XDG_CONFIG_HOME ]] {
154 export XDG_CONFIG_HOME
155 } elif [[ ! -e ~/.config ]] {
156 mkdir -m760 ~/.config
158 # I am of the belief .local should follow FHS /usr/local...
159 [[ -e ~/.local/etc ]] || ln -s ~/.config ~/.local/etc
160 xdg_config_dirs=($XDG_CONFIG_HOME ${XDG_CONFIG_DIRS:+"$xdg_config_dirs[@]"}
161 {/opt,/usr/local,/usr/pkg,}/etc/xdg)
162 # XXX: if colons are not escaped, could remove unintended part of string
163 # TODO: remove empty element via array not scalar
164 export XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS#$XDG_CONFIG_HOME:}
166 if [[ -v XDG_STATE_HOME ]] {
167 export XDG_STATE_HOME
168 } elif [[ ! -e ~/.local/state ]] {
169 mkdir -m760 ~/.local/state
172 if [[ -v XDG_CACHE_HOME ]] {
173 export XDG_CACHE_HOME
175 if [[ -v _sev_tmp ]] {
176 export XDG_CACHE_HOME=$_sev_tmp/.xdg.cache
177 [[ -e $XDG_CACHE_HOME ]] || mkdir -m700 $XDG_CACHE_HOME
178 } elif [[ ! -e ~/.cache ]] {
183 if [[ -v XDG_RUNTIME_DIR ]] {
184 # NOTE: this can be set by systemd or other pre-shell supervisor, and
185 # if any services were started such as pipewire, we need to use
186 # the existing runtime dir so that we can get any existing
187 # program sockets or other data
188 export XDG_RUNTIME_DIR
189 } elif [[ -v TMPDIR ]] {
190 # make runtime dir in our session-specific tmpdir
191 export XDG_RUNTIME_DIR=$TMPDIR/.xdg.runtime
192 # same as in tmpdir creation, ensure dir doesn't exist
193 if [[ -h $XDG_RUNTIME_DIR ]] {
194 unlink $XDG_RUNTIME_DIR 2>/dev/null
195 } elif [[ -e $XDG_RUNTIME_DIR ]] {
196 rm -rf $XDG_RUNTIME_DIR 2>/dev/null
198 mkdir -m700 $XDG_RUNTIME_DIR 2>/dev/null
201 export _sev_setup_xdg=
205 if [[ ! -v DBUS_SESSION_BUS_ADDRESS && -v commands[dbus-launch] ]] {
207 export DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID
211 if [[ ! -v GNUPGHOME ]] {
212 export GNUPGHOME=${XDG_CONFIG_HOME:-~/.config}/gnupg
213 # move existing gnupg dir to our new home
214 if [[ -d ~/.gnupg && ! -d $GNUPGHOME ]] {
215 mv ~/.gnupg $GNUPGHOME
219 ### gpg agent + forwarding
220 # NOTE: while ssh manages its auth sock in-protocol when ForwardSsh is enabled,
221 # GPG must be forwarded manually over Unix socket. to support this, we
222 # forward the restricted gpg-agent extra socket to the remote host with a
223 # RemoteForward rule in ~/.ssh/config that uses the _GNUPG_SOCK_* vars.
225 # to avoid conflicts with other ssh sessions where the same user is
226 # connecting to the same host from different machines, gpg should utilize
227 # its own forwarded socket for each session. previously, you could
228 # provide a path to the agent socket in GPG_AGENT_INFO, but that was
229 # deprecated in GPG v2.1; instead, we must replace the socket in gpg's
232 # gnupg commits fb88f37–aab8a0b moved sockets from GNUPGHOME by default
233 # to directories under /run. aab8a0b in particular solidifies the
234 # functionality shift to utilize systemd-logind's user runtime
235 # directories. if the dir isn't found, gpg will fall back to the homedir.
236 # since previous functionality allowed multiple homedirs with multiple
237 # sockets, a provision was added where changing GNUPGHOME will also
238 # change the socket dir to a hashed dir under the usual runtime dir.
240 # utilizing this information, we can conclude:
241 # - on systems with user runtime dirs, changing GNUPGHOME will also
242 # give us a unique socket dir under the user runtime dir;
243 # - on other systems, the socket dir follows GNUPGHOME.
244 # therefore, the safest way to ensure unique sockets while not having to
245 # write specific logic for both scenarios is to simply change GNUPGHOME.
246 # the easiest way to do this is to create a new dir and link the contents
247 # of GNUPGHOME to the new home. we can then replace the agent sockets
248 # there with the forwarded one.
250 # NOTE: since Unix sockets are not supported under Windows, this will not work
251 # under msys, cygwin, mingw, etc., but may work under wsl2.
253 # HACK: without SendEnv, which is disabled by default in most sshd configs,
254 # there is no foolproof way to prevent race conditions via socket
255 # filename collisions or to pass the desired forward path to the remote
256 # host environment. we just have to guess the path we choose is good on
257 # the desination, and assume the newest matching socket is the correct
258 # one after connecting. in theory, we could occlude the ssh binary on
259 # PATH with an alias or script that would allow us to communicate with
260 # the remote host before opening a shell, so that we can have the host
261 # communicate back to the client where it wants a socket created or ask
262 # the host if the path the client wants to use is writable. however, this
263 # would open up too many edge cases where it wouldn't work or be too
264 # clunky (e.g. asking for password twice) to make it worth it.
265 function _gpg_socketpath {
266 # dirs are percent-encoded: https://stackoverflow.com/a/64312099
267 echo ${1//(#b)%([[:xdigit:]](#c2))/${(#):-0x$match[1]}}
269 if [[ ! -v _sev_setup_gpg_forward && -v commands[gpg] ]] {
270 # XXX: assuming /tmp exists and is writable on destination
271 export _GNUPG_SOCK_DEST_BASE=/tmp/.gpg-agent-forward
272 export _GNUPG_SOCK_DEST_EXT=$(date +%s).$RANDOM
273 export _GNUPG_SOCK_DEST=$_GNUPG_SOCK_DEST_BASE.$_GNUPG_SOCK_DEST_EXT
274 export _sev_gpg_forward_dir=$XDG_RUNTIME_DIR/gnupg/.ssh_forward
275 _sev_zcleanup gpg-forward
277 # find our forwarded socket
278 s=($_GNUPG_SOCK_DEST_BASE*(N=oc[1]))
279 if [[ -n $s && -v SSH_CLIENT ]] {
280 # create new forward dir
281 export _sev_setup_gpg_forward=
282 h=$_sev_gpg_forward_dir/$$
284 for x (gpg{,-agent}.conf sshcontrol random_seed
285 pubring.kbx{,~} trustdb.gpg private-keys-v1.d crls.d) {
286 ln -s ${GNUPGHOME:-~/.gnupg}/$x $h
290 for x in $(gpgconf --list-dirs | grep 'agent-.*-\?socket:'); do
291 x=$(_gpg_socketpath ${x/#agent-*socket:})
292 if [[ ! -v primary ]] {
293 # move forwarded socket to first valid agent socket path
294 # XXX: if tmp is on different filesystem this may not work
298 # make links to forwarded socket for any others
306 # what we will forward if we start a new ssh connection
307 # NOTE: do this after setting up GNUPGHOME to pick up new socket path;
308 # if already connected over SSH, extra should be the remote one
309 export _GNUPG_SOCK_SRC=$(_gpg_socketpath \
310 $(gpgconf --list-dirs agent-extra-socket))
311 } elif [[ ! -v _sev_setup_gpg_forward ]] {
312 # required for RemoteForward to not error out if the vars are unset
313 [[ ! -v _GNUPG_SOCK_SRC ]] && export _GNUPG_SOCK_SRC=/nonexistent
314 [[ ! -v _GNUPG_SOCK_DEST ]] && export _GNUPG_SOCK_DEST=/nonexistent
318 if [[ -v commands[gpg-connect-agent] &&
319 ( ! -v _sev_setup_gpgagent || -v _sev_refresh_gpgagent ) ]] {
320 # avoid printing if we have already set up tty before
321 [[ ! -v _sev_setup_gpgagent && -o interactive ]] && p=true || p=false
323 print -nP '%F{blue}>>>%f GPG: '
324 if [[ -v _sev_setup_gpg_forward ]] {
325 print -nP '%F{yellow}Forwarded agent '
327 print -nP '%F{green}Agent '
330 gpg-connect-agent /bye >/dev/null 2>&1
332 $p && print -P '%F{red}communication error'
334 if [[ ! -v _sev_setup_gpg_forward ]] {
335 if [[ ${+GPG_TTY} -eq 0 && -o interactive ]]
336 export GPG_TTY=$(tty)
337 if [[ ( -v DISPLAY || -v WAYLAND_DISPLAY ) &&
338 ${PINENTRY_USER_DATA/USE_TTY=0} == $PINENTRY_USER_DATA ]]
339 export PINENTRY_USER_DATA=USE_TTY=$((
340 ${+DISPLAY} + ${+WAYLAND_DISPLAY} == 0))
341 # XXX: don't know if gpg-agent supports comments after directives
342 # XXX: path could have #
343 # XXX: we are assuming this is our pinentry from .local/bin
344 sed -Ei 's#^([[:space:]]*pinentry-program[[:space:]]).*$#\1'$HOME'/.local/bin/pinentry#' \
345 ${GNUPGHOME:-~/.gnupg}/gpg-agent.conf 2>/dev/null
346 # XXX: could check for changes before doing this to save perf
347 gpg-connect-agent RELOADAGENT UPDATESTARTUPTTY /bye >/dev/null 2>&1
349 gpg-connect-agent /subst /serverpid \
350 "/echo pid \${get serverpid} on $GPG_TTY" /bye 2>/dev/null
356 export _sev_setup_gpgagent=
358 unset p _sev_refresh_gpgagent
362 if [[ ! -v _sev_setup_ssh ]] {
363 # NOTE: preferred order of agents to check: okcagent, gnupg, openssh
364 # first block takes care of okcagent and openssh, second gnupg
365 # XXX: doesn't actually check if ssh is enabled in gpg
366 [[ -o interactive ]] && print -nP '%F{blue}>>>%f SSH: %F{green}'
367 if [[ ! -v SSH_AUTH_SOCK && ( -v commands[okc-ssh-agent] ||
368 ( -v commands[ssh-agent] && ! -v commands[gpg] ) ) ]] {
369 okc=${commands[okc-ssh-agent]:+okc-}
370 e=$_sev_tmp/${okc}ssh-agent-exports
374 IFS=$'\0' read -r sock pid <$e
376 if [[ -S $sock && $pid > 0 ]] && kill -0 $pid; then
377 [[ -o interactive ]] && print -P "Reusing agent PID $pid%f"
378 export SSH_AUTH_SOCK=$sock
379 export SSH_AGENT_PID=$pid
381 # TODO: ensure ssh-agent path looks legit to avoid unsafe eval?
382 # XXX: doesn't appear to be any other way to handle redirection.
383 # because eval needs to write to current scope environment
384 # subshells can't be used to capture output and print.
385 c='TMPDIR=$_sev_tmp ${okc}ssh-agent'
386 if [[ -o interactive ]] {
390 eval $(eval $=c) >/dev/null 2>&1
392 echo -n $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$e
396 } elif [[ ! -v SSH_AUTH_SOCK && -v commands[gpg] ]] {
397 # since gpg should have been started above, just export and notify
398 if [[ -o interactive ]] {
399 if [[ -v _sev_setup_gpg_forward ]] {
400 echo 'Forwarded GPG agent'
402 gpg-connect-agent /subst /serverpid \
403 '/echo GPG agent pid ${get serverpid}' /bye
407 export SSH_AUTH_SOCK=$(_gpg_socketpath \
408 $(gpgconf --list-dirs agent-ssh-socket))
409 } elif [[ -v SSH_AUTH_SOCK ]] {
410 [[ -o interactive ]] && print -P 'Preconfigured agent%f'
412 [[ -o interactive ]] && print -P '%F{red}No agent available%f'
415 export _sev_setup_ssh=
417 unfunction _gpg_socketpath
420 [[ -v commands[perl] && -d $XDG_DATA_HOME/perl5/lib/perl5 &&
421 ! -v PERL_LOCAL_LIB_ROOT ]] &&
422 eval $(perl -I$XDG_DATA_HOME/perl5/lib/perl5 \
423 -Mlocal::lib=$XDG_DATA_HOME/perl5 2>/dev/null)
425 ### load site-specific
426 load-site-dotfile zprofile