]> git.sev.monster Git - dotfiles.git/blame - etc/zsh/.zprofile
.zshrc: don't override graphical mode env vars
[dotfiles.git] / etc / zsh / .zprofile
CommitLineData
79d4a356 1# NOTE:
8d4a98e1 2# our .zprofile can be expensive, so we keep track of what has been run
b31a3fb1 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.
79d4a356 5#
b31a3fb1 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.
9#
10# this file respects non-interactive sessions and will not intentionally emit
11# output.
79d4a356 12
6d54344e 13### cleanup
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
16function _sev_zcleanup {
17 ## gpg forwarding
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
a8dee69a 20 find $_sev_gpg_forward_dir -mindepth 1 -maxdepth 1 -type d |
6d54344e 21 while {read -r x} {
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.
27 p=$(basename $x)
28 if {[[ -v _sev_gpg_forward_clean || $$ == $p ]] ||
8d4a98e1 29 ! kill -0 $p 2>/dev/null} {
6d54344e 30 find $x -mindepth 1 -maxdepth 1 | while {read -r y} {
31 # XXX: real dirs will stop unlink, consider it a feature
32 unlink $y
33 }
34 # don't force in case something important is still there
35 rmdir $x
36 }
37 }
38 # reset GNUPGHOME if we removed our own dir
4581a6bf 39 if [[ $GNUPGHOME =~ '/.ssh_forward/\d+/*$' && ! -e $GNUPGHOME ]]
40 GNUPGHOME=${GNUPGHOME%$MATCH}
6d54344e 41 }
42
43 ## tmp
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
a8dee69a 48 find $_sev_tmp -mindepth 1 -maxdepth 1 -name '.session.*' -type d |
6d54344e 49 while {read -r x} {
50 # NOTE: same rationale as above
51 p=${$(basename $x)#.session.}
52 if {[[ -v _sev_tmp_clean || $$ == $p ]] ||
8d4a98e1 53 ! kill -0 $p 2>/dev/null} {
6d54344e 54 rm -rf $x
55 }
56 }
57 }
58
59 unset x p y
60}
61
8d4a98e1 62### xdg local dir
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.
b31a3fb1 67[[ -e ~/.local ]] || mkdir -m760 ~/.local
8d4a98e1 68
6d54344e 69### tmp
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,
b31a3fb1 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.
6d54344e 79if [[ ! -v _sev_tmp ]] {
b31a3fb1 80 # create personal TMPDIR under system tmp
81 t=${TMPDIR:-${TEMPDIR:-${TEMP:-${TMP:-/tmp}}}}/.home-$LOGNAME
8d4a98e1 82 [[ -e $t ]] || mkdir -m700 $t 2>/dev/null
b31a3fb1 83 _sev_tmp=~/.local/tmp
833b2af3 84 if [[ ! -d $t ]] {
b31a3fb1 85 # fallback TMPDIR to bare local directory or existing softlink
833b2af3 86 [[ -o interactive ]] &&
b31a3fb1 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
8d4a98e1 90 if [[ ! -d $_sev_tmp ]] {
b31a3fb1 91 _sev_tmp=${$(mktemp 2>/dev/null):/tmp}
8d4a98e1 92 [[ -o interactive ]] &&
b31a3fb1 93 print -P "%F{red}!!! Can't create tmp dir, using $_sev_tmp%f"
8d4a98e1 94 }
b31a3fb1 95 } elif [[ -f $_sev_tmp || ( -d $_sev_tmp && ! -h $_sev_tmp ) ]] {
96 # file or non-softlink directory is on our local dir
8d4a98e1 97 [[ -o interactive ]] &&
b31a3fb1 98 print -P "%F{orange}*** $_sev_tmp exists, can't link to tmp dir $t, ignoring it%f"
8d4a98e1 99 _sev_tmp=$t
100 } else {
b31a3fb1 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
107 }
8d4a98e1 108 ln -s $t $_sev_tmp 2>/dev/null
109 }
110 if [[ -v _sev_tmp ]] {
111 # ensure dir is clean
112 _sev_zcleanup tmp
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 ]] &&
b31a3fb1 117 print -P "%F{red}!!! Can't create session tmp subdir $t, using $_sev_tmp%f"
8d4a98e1 118 t=$_sev_tmp
119 fi
b31a3fb1 120 export _sev_tmp TMPDIR=$t TEMPDIR=$t TEMP=$t TMP=$t
833b2af3 121 }
b31a3fb1 122 unset t
833b2af3 123}
124
125### xdg
79d4a356 126if [[ ! -v _sev_setup_xdg ]] {
8d4a98e1 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
833b2af3 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
b31a3fb1 132
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"
139
d23b28eb 140 typeset -UT XDG_DATA_DIRS xdg_data_dirs
8d4a98e1 141 if [[ -v XDG_DATA_HOME ]] {
142 export XDG_DATA_HOME
143 } elif [[ ! -e ~/.local/share ]] {
144 mkdir -m760 ~/.local/share
145 }
146 xdg_data_dirs=($XDG_DATA_HOME /{opt,usr/local,usr/pkg,usr}/share
3fcf651c 147 ${XDG_DATA_DIRS:+"$xdg_data_dirs[@]"})
8d4a98e1 148 # XXX: if colons are not escaped, could remove unintended part of string
b31a3fb1 149 # TODO: remove empty element via array not scalar
8d4a98e1 150 export XDG_DATA_DIRS=${XDG_DATA_DIRS#$XDG_DATA_HOME:}
d23b28eb 151
8d4a98e1 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
157 }
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
b31a3fb1 163 # TODO: remove empty element via array not scalar
8d4a98e1 164 export XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS#$XDG_CONFIG_HOME:}
6d54344e 165
8d4a98e1 166 if [[ -v XDG_STATE_HOME ]] {
167 export XDG_STATE_HOME
168 } elif [[ ! -e ~/.local/state ]] {
169 mkdir -m760 ~/.local/state
170 }
d23b28eb 171
72de94eb 172 if [[ -v XDG_CACHE_HOME ]] {
173 export XDG_CACHE_HOME
174 } else {
8d4a98e1 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 ]] {
179 mkdir -m700 ~/.cache
180 }
181 }
182
e69caf64 183 if [[ -v XDG_RUNTIME_DIR ]] {
3fcf651c 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
e69caf64 188 export XDG_RUNTIME_DIR
b31a3fb1 189 } elif [[ -v TMPDIR ]] {
e69caf64 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
197 }
198 mkdir -m700 $XDG_RUNTIME_DIR 2>/dev/null
6d54344e 199 }
d23b28eb 200
79d4a356 201 export _sev_setup_xdg=
d569f3f7 202}
79d4a356 203
6d54344e 204### dbus
205if [[ ! -v DBUS_SESSION_BUS_ADDRESS && -v commands[dbus-launch] ]] {
206 eval $(dbus-launch)
207 export DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID
208}
209
210### gpg home
211if [[ ! -v GNUPGHOME ]] {
8d4a98e1 212 export GNUPGHOME=${XDG_CONFIG_HOME:-~/.config}/gnupg
b31a3fb1 213 # move existing gnupg dir to our new home
214 if [[ -d ~/.gnupg && ! -d $GNUPGHOME ]] {
215 mv ~/.gnupg $GNUPGHOME
6d54344e 216 }
217}
218
219### gpg agent + forwarding
b31a3fb1 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.
224#
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
230# socket dir.
231#
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.
239#
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.
249#
79d4a356 250# NOTE: since Unix sockets are not supported under Windows, this will not work
833b2af3 251# under msys, cygwin, mingw, etc., but may work under wsl2.
b31a3fb1 252#
79d4a356 253# HACK: without SendEnv, which is disabled by default in most sshd configs,
b31a3fb1 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
79d4a356 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
8d4a98e1 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.
6d54344e 265function _gpg_socketpath {
266 # dirs are percent-encoded: https://stackoverflow.com/a/64312099
267 echo ${1//(#b)%([[:xdigit:]](#c2))/${(#):-0x$match[1]}}
268}
269if [[ ! -v _sev_setup_gpg_forward && -v commands[gpg] ]] {
b31a3fb1 270 # XXX: assuming /tmp exists and is writable on destination
6d54344e 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
b31a3fb1 274 export _sev_gpg_forward_dir=$XDG_RUNTIME_DIR/gnupg/.ssh_forward
6d54344e 275 _sev_zcleanup gpg-forward
79d4a356 276
6d54344e 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/$$
283 mkdir -pm700 $h
b31a3fb1 284 for x (gpg{,-agent}.conf sshcontrol random_seed
d9cf4c48 285 pubring.kbx{,~} trustdb.gpg private-keys-v1.d crls.d) {
6d54344e 286 ln -s ${GNUPGHOME:-~/.gnupg}/$x $h
79d4a356 287 }
6d54344e 288 export GNUPGHOME=$h
289 unset h
290 for x in $(gpgconf --list-dirs | grep 'agent-.*-\?socket:'); do
291 x=$(_gpg_socketpath ${x/#agent-*socket:})
b31a3fb1 292 if [[ ! -v primary ]] {
6d54344e 293 # move forwarded socket to first valid agent socket path
294 # XXX: if tmp is on different filesystem this may not work
295 mv $s $x
b31a3fb1 296 primary=$x
6d54344e 297 } else {
298 # make links to forwarded socket for any others
b31a3fb1 299 ln -s $primary $x
6d54344e 300 }
301 done
b31a3fb1 302 unset x primary
6d54344e 303 }
304 unset s
79d4a356 305
6d54344e 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
315}
79d4a356 316
6d54344e 317### gpg agent
8d4a98e1 318if [[ -v commands[gpg-connect-agent] &&
319 ( ! -v _sev_setup_gpgagent || -v _sev_refresh_gpgagent ) ]] {
6d54344e 320 # avoid printing if we have already set up tty before
321 [[ ! -v _sev_setup_gpgagent && -o interactive ]] && p=true || p=false
322 if {$p} {
323 print -nP '%F{blue}>>>%f GPG: '
324 if [[ -v _sev_setup_gpg_forward ]] {
d42865fe 325 print -nP '%F{yellow}Forwarded agent '
326 } else {
327 print -nP '%F{green}Agent '
328 }
79d4a356 329 }
6d54344e 330 gpg-connect-agent /bye >/dev/null 2>&1
331 if [[ $? -ne 0 ]] {
d42865fe 332 $p && print -P '%F{red}communication error'
6d54344e 333 } else {
d42865fe 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 #
54a85d6c 343 # XXX: we are assuming this is our pinentry from .local/bin
b31a3fb1 344 sed -Ei 's#^([[:space:]]*pinentry-program[[:space:]]).*$#\1'$HOME'/.local/bin/pinentry#' \
54a85d6c 345 ${GNUPGHOME:-~/.gnupg}/gpg-agent.conf 2>/dev/null
d42865fe 346 # XXX: could check for changes before doing this to save perf
347 gpg-connect-agent RELOADAGENT UPDATESTARTUPTTY /bye >/dev/null 2>&1
348 if {$p} {
349 gpg-connect-agent /subst /serverpid \
350 "/echo pid \${get serverpid} on $GPG_TTY" /bye 2>/dev/null
351 print -nP '%f'
352 }
353 } elif {$p} {
354 print -P '%f'
355 }
6d54344e 356 export _sev_setup_gpgagent=
79d4a356 357 }
8d4a98e1 358 unset p _sev_refresh_gpgagent
6d54344e 359}
79d4a356 360
6d54344e 361### ssh agent
362if [[ ! -v _sev_setup_ssh ]] {
79d4a356 363 # NOTE: preferred order of agents to check: okcagent, gnupg, openssh
364 # first block takes care of okcagent and openssh, second gnupg
6d54344e 365 # XXX: doesn't actually check if ssh is enabled in gpg
79d4a356 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-}
e6e7ad69 370 e=$_sev_tmp/${okc}ssh-agent-exports
79d4a356 371 typeset sock=
372 typeset -i pid=
6d54344e 373 if [[ -f $e ]] {
374 IFS=$'\0' read -r sock pid <$e
79d4a356 375 }
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
380 else
79d4a356 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.
e6e7ad69 385 c='TMPDIR=$_sev_tmp ${okc}ssh-agent'
79d4a356 386 if [[ -o interactive ]] {
e6e7ad69 387 eval $(eval $=c)
79d4a356 388 print -nP '%f'
389 } else {
e6e7ad69 390 eval $(eval $=c) >/dev/null 2>&1
79d4a356 391 }
6d54344e 392 echo -n $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$e
e6e7ad69 393 unset c
79d4a356 394 fi
e6e7ad69 395 unset okc e sock pid
79d4a356 396 } elif [[ ! -v SSH_AUTH_SOCK && -v commands[gpg] ]] {
6d54344e 397 # since gpg should have been started above, just export and notify
79d4a356 398 if [[ -o interactive ]] {
6d54344e 399 if [[ -v _sev_setup_gpg_forward ]] {
400 echo 'Forwarded GPG agent'
79d4a356 401 } else {
402 gpg-connect-agent /subst /serverpid \
6d54344e 403 '/echo GPG agent pid ${get serverpid}' /bye
79d4a356 404 }
405 print -nP '%f'
406 }
6d54344e 407 export SSH_AUTH_SOCK=$(_gpg_socketpath \
79d4a356 408 $(gpgconf --list-dirs agent-ssh-socket))
409 } elif [[ -v SSH_AUTH_SOCK ]] {
410 [[ -o interactive ]] && print -P 'Preconfigured agent%f'
411 } else {
412 [[ -o interactive ]] && print -P '%F{red}No agent available%f'
413 }
414
6d54344e 415 export _sev_setup_ssh=
79d4a356 416}
6d54344e 417unfunction _gpg_socketpath
79d4a356 418
6d54344e 419### perl local lib
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 \
833b2af3 423 -Mlocal::lib=$XDG_DATA_HOME/perl5 2>/dev/null)
79d4a356 424
833b2af3 425### load site-specific
4ced48ed 426load-site-dotfile zprofile
This page took 0.150549 seconds and 4 git commands to generate.