]> git.sev.monster Git - dotfiles.git/blame_incremental - etc/zsh/.zprofile
zsh: reorder zshrc, fix zoxide, git aliases
[dotfiles.git] / etc / zsh / .zprofile
... / ...
CommitLineData
1# NOTE:
2# our .zprofile can be expensive, so we keep track of what has been run
3# already, and only set up what is necessary. additionally, we want to ensure
4# that our environment is set up as early as possible, so we also source
5# .zprofile in .zshenv for new non-login shells.
6#
7# these issues are handled by using these methods:
8# * the parent shell that starts the user's session after logging in to some
9# graphical environments may not be a login shell—due to misconfiguration
10# or otherwise—which means .zprofile is not ran and the environment is not
11# properly configured for any child processes.
12# * some desktop environments/graphical terminal emulators will start new
13# terminal windows with login shells, which runs .zprofile every time and
14# leads to noticably slow startup times if we have not already ran it.
15
16### cleanup
17# XXX: only call after relevant vars have been set up, defined early so that
18# below code can utilize it after they do so
19function _sev_zcleanup {
20 ## gpg forwarding
21 if [[ -d $_sev_gpg_forward_dir && ( -z $1 || $1 == 'gpg-forward' ) ]] {
22 # clean up forward dirs if its session is dead or we ask for it
23 find $_sev_gpg_forward_dir -mindepth 1 -maxdepth 1 -type d |
24 while {read -r x} {
25 # NOTE: the only way we can get here is if we have not been
26 # forwarded before, if the user asks for it, or during
27 # logout. if our own pid already has a dir, it is most likely
28 # stale, the user wants it removed, or something is very
29 # broken—in all 3 of these cases the best choice is remove it.
30 p=$(basename $x)
31 if {[[ -v _sev_gpg_forward_clean || $$ == $p ]] ||
32 ! kill -0 $p 2>/dev/null} {
33 find $x -mindepth 1 -maxdepth 1 | while {read -r y} {
34 # XXX: real dirs will stop unlink, consider it a feature
35 unlink $y
36 }
37 # don't force in case something important is still there
38 rmdir $x
39 }
40 }
41 # reset GNUPGHOME if we removed our own dir
42 if [[ $GNUPGHOME =~ '/.ssh_forward/\d+/*$' && ! -e $GNUPGHOME ]]
43 GNUPGHOME=${GNUPGHOME%$MATCH}
44 }
45
46 ## tmp
47 # NOTE: _sev_tmp is not unset so session dirs will not be recreated
48 # NOTE: XDG dirs that use our tmp are not unset here, they are in zlogout
49 if [[ -d $_sev_tmp && ( -z $1 || $1 == 'tmp' ) ]] {
50 # clean up tmp dirs if its session is dead or we ask for it
51 find $_sev_tmp -mindepth 1 -maxdepth 1 -name '.session.*' -type d |
52 while {read -r x} {
53 # NOTE: same rationale as above
54 p=${$(basename $x)#.session.}
55 if {[[ -v _sev_tmp_clean || $$ == $p ]] ||
56 ! kill -0 $p 2>/dev/null} {
57 rm -rf $x
58 }
59 }
60 }
61
62 unset x p y
63}
64
65### path
66# NOTE: we utilize the fact that unique arrays keep the first occurrence and
67# remove any further occurences to capture elements from the old PATH
68# that we did not anticipate and shift them to the front, since they are
69# probably important to the system
70if [[ ! -v _sev_setup_path || -o login ]] {
71 typeset -U path fpath
72 # add as many generic paths as possible to keep the order we want
73 # NOTE: /usr/{local,pkg,games} are unix/bsdisms
74 # XXX: PREFIX not validated, non-posix but Termux uses it, maybe others
75 # XXX: XDG specifies ~/.local/bin as the only user-writable dir for
76 # executables, but we specify more; technically this is against spec
77 syspath=("$path[@]")
78 path=({{${_sev_home:-~},~}{/.local,},{$PREFIX,}{,/opt,/usr{,/local,/pkg}}}/{s,}bin
79 /usr/{X11R{7,6}/bin,games})
80 ((len=$#path))
81 path=("$path[@]" "$syspath[@]")
82 # remove nonexistent and duplicate paths
83 for (( i = 1; i <= $#path; i++ )) {
84 if [[ ! -e $path[$i] ]] {
85 path[$i]=()
86 ((i <= len)) && ((len--))
87 ((i--))
88 continue
89 }
90 }
91 # shift valid system paths to the front if there are any left
92 ((len > 0 && len < $#path)) && path=("${(@)path[len + 1, -1]}" "${(@)path[1, len]}")
93 unset syspath len i
94 # include our zsh dir in fpath. unlike above, we always prefer our paths
95 fpath=(${ZDOTDIR:-~/.zsh}/functions/{*,Completions/*}(N) "$fpath[@]")
96 # FPATH is not exported by default
97 export FPATH
98 typeset +U path fpath
99 export _sev_setup_path=
100}
101
102### autoload to load site specific dotfiles now that fpath is set
103autoload -Uz load-site-dotfile
104
105### load zshenv site-specific
106# NOTE: this has to be here since fpath isn't set in .zshenv
107load-site-dotfile zshenv
108
109### lang
110export CHARSET=${CHARSET:-UTF-8}
111export LANG=${LANG:-en_US.UTF-8}
112
113### xdg local dir
114# NOTE: need this for tmp, so confirm it exists.
115# XXX: perms are not specified for XDG dirs except runtime, but I think 760
116# makes the most sense. shouldn't break anything since no one else should
117# be poking around in our dir.
118[[ -e ${_sev_home:-~}/.local ]] || mkdir -m760 ${_sev_home:-~}/.local
119
120### tmp
121# NOTE: specs say that POSIX tmp and XDG runtime directories should exist
122# until the last session is logged out (POSIX can exist for longer).
123# since we can't reliably keep track of sessions in a cross-platform
124# manner, the current implementation should use a separate directory per
125# toplevel session (i.e. SHLVL=1). this should placate most applications,
126# though it is not expressly spec compliant.
127if [[ ! -v _sev_tmp ]] {
128 _sev_tmp=${_sev_home:-~}/.local/tmp
129 # NOTE: race condition/remove in use files
130 [[ -h $_sev_tmp ]] && unlink $_sev_tmp 2>/dev/null
131 t=${TMPDIR:-${TEMP:-${TMP:-/tmp}}}/.home-$LOGNAME
132 # create personal tmp dir under system tmp
133 [[ -e $t ]] || mkdir -m700 $t 2>/dev/null
134 if [[ ! -d $t ]] {
135 [[ -o interactive ]] &&
136 print -P "%F{orange}*** Can't create TMPDIR $t, using $_sev_tmp%f"
137 # fallback bare directory
138 [[ -e $_sev_tmp ]] || mkdir -m700 $_sev_tmp 2>/dev/null
139 if [[ ! -d $_sev_tmp ]] {
140 [[ -o interactive ]] &&
141 print -P "%F{red}!!! No usable TMPDIR%f"
142 unset _sev_tmp
143 } else {
144 t=$_sev_tmp
145 }
146 } elif [[ -e $_sev_tmp ]] {
147 [[ -o interactive ]] &&
148 print -P "%F{orange}*** $_sev_tmp occluded, can't link to TMPDIR $t%f"
149 _sev_tmp=$t
150 } else {
151 ln -s $t $_sev_tmp 2>/dev/null
152 }
153 if [[ -v _sev_tmp ]] {
154 # ensure dir is clean
155 _sev_zcleanup tmp
156 # finally create our subdir for this session
157 t=$_sev_tmp/.session.$$
158 if ! mkdir -m700 $t 2>/dev/null; then
159 [[ -o interactive ]] &&
160 print -P "%F{red}!!! Can't create session subdir $t, using $_sev_tmp%f"
161 t=$_sev_tmp
162 fi
163 export _sev_tmp TMPDIR=$t TEMP=$t TMP=$t
164 unset t
165 }
166}
167
168### xdg
169if [[ ! -v _sev_setup_xdg ]] {
170 ## merge with any existing dirs and remove duplicates using unique arrays
171 # NOTE: we are accepting whatever value might be set for CONFIG and DATA;
172 # if it wasn't set, we just use default and leave it unset
173 # NOTE: include and then remove CONFIG_HOME and DATA_HOME to ensure they
174 # are not present in the array if it was added before we got to it
175 typeset -UT XDG_DATA_DIRS xdg_data_dirs
176 if [[ -v XDG_DATA_HOME ]] {
177 export XDG_DATA_HOME
178 } elif [[ ! -e ~/.local/share ]] {
179 mkdir -m760 ~/.local/share
180 }
181 xdg_data_dirs=($XDG_DATA_HOME /{opt,usr/local,usr/pkg,usr}/share
182 "${XDG_DATA_DIRS:+${xdg_data_dirs[@]}}")
183 # XXX: if colons are not escaped, could remove unintended part of string
184 export XDG_DATA_DIRS=${XDG_DATA_DIRS#$XDG_DATA_HOME:}
185
186 typeset -UT XDG_CONFIG_DIRS xdg_config_dirs
187 if [[ -v XDG_CONFIG_HOME ]] {
188 export XDG_CONFIG_HOME
189 } elif [[ ! -e ~/.config ]] {
190 mkdir -m760 ~/.config
191 }
192 # I am of the belief .local should follow FHS /usr/local...
193 [[ -e ~/.local/etc ]] || ln -s ~/.config ~/.local/etc
194 xdg_config_dirs=($XDG_CONFIG_HOME ${XDG_CONFIG_DIRS:+"$xdg_config_dirs[@]"}
195 {/opt,/usr/local,/usr/pkg,}/etc/xdg)
196 # XXX: if colons are not escaped, could remove unintended part of string
197 export XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS#$XDG_CONFIG_HOME:}
198
199 if [[ -v XDG_STATE_HOME ]] {
200 export XDG_STATE_HOME
201 } elif [[ ! -e ~/.local/state ]] {
202 mkdir -m760 ~/.local/state
203 }
204
205 if [[ -v XDG_CACHE_HOME ]] {
206 export XDG_CACHE_HOME
207 } else {
208 if [[ -v _sev_tmp ]] {
209 export XDG_CACHE_HOME=$_sev_tmp/.xdg.cache
210 [[ -e $XDG_CACHE_HOME ]] || mkdir -m700 $XDG_CACHE_HOME
211 } elif [[ ! -e ~/.cache ]] {
212 mkdir -m700 ~/.cache
213 }
214 }
215
216 if [[ -v XDG_RUNTIME_DIR ]] {
217 export XDG_RUNTIME_DIR
218 } else {
219 # make runtime dir in our session-specific tmpdir
220 export XDG_RUNTIME_DIR=$TMPDIR/.xdg.runtime
221 # same as in tmpdir creation, ensure dir doesn't exist
222 if [[ -h $XDG_RUNTIME_DIR ]] {
223 unlink $XDG_RUNTIME_DIR 2>/dev/null
224 } elif [[ -e $XDG_RUNTIME_DIR ]] {
225 rm -rf $XDG_RUNTIME_DIR 2>/dev/null
226 }
227 mkdir -m700 $XDG_RUNTIME_DIR 2>/dev/null
228 }
229
230 # source user dirs after other vars
231 [[ -e $XDG_CONFIG_HOME/user-dirs.dirs ]] &&
232 emulate sh -c "source $XDG_CONFIG_HOME/user-dirs.dirs"
233 export _sev_setup_xdg=
234}
235
236### dbus
237if [[ ! -v DBUS_SESSION_BUS_ADDRESS && -v commands[dbus-launch] ]] {
238 eval $(dbus-launch)
239 export DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID
240}
241
242### gpg home
243if [[ ! -v GNUPGHOME ]] {
244 export GNUPGHOME=${XDG_CONFIG_HOME:-~/.config}/gnupg
245 if [[ -d ~/.gnupg ]] {
246 mv ~/.gnupg ${XDG_CONFIG_HOME:-~/.config}/gnupg
247 }
248}
249
250### gpg agent + forwarding
251# NOTE: while ssh manages its auth sock in its protocol when ForwardSsh is
252# enabled, GPG must be forwarded manually over Unix socket. to support
253# this, we forward the restricted gpg-agent extra socket to the remote
254# host with a RemoteForward rule in ~/.ssh/config that uses the
255# _GNUPG_SOCK_* env vars. to avoid conflicts with other ssh sessions
256# where the same user is connecting to the same host from different
257# machines, gpg in each environment should utilize its own forwarded
258# socket, rather than replace the sockets in GNUPGHOME which will be
259# overridden on the next connection. previously, you could provide a path
260# to the agent socket in GPG_AGENT_INFO, but that was deprecated in GPG
261# v2.1. instead, we must clone GNUPGHOME with links and replace the agent
262# sockets there with the forwarded one.
263# NOTE: since Unix sockets are not supported under Windows, this will not work
264# under msys, cygwin, mingw, etc., but may work under wsl2.
265# HACK: without SendEnv, which is disabled by default in most sshd configs,
266# there is no foolproof way to prevent race conditions via filename
267# collisions or to pass the desired forward path to the remote host
268# environment. we just have to guess the path we choose is good on the
269# desination, and assume the newest matching socket is the correct one
270# after connecting. in theory, we could occlude the ssh binary on PATH
271# with an alias or script that would allow us to communicate with the
272# remote host before opening a shell, so that we can have the host
273# communicate back to the client where it wants a socket created or ask
274# the host if the path the client wants to use is writable. however, this
275# would open up too many edge cases where it wouldn't work or be too
276# clunky (e.g. asking for password twice) to make it worth it.
277function _gpg_socketpath {
278 # dirs are percent-encoded: https://stackoverflow.com/a/64312099
279 echo ${1//(#b)%([[:xdigit:]](#c2))/${(#):-0x$match[1]}}
280}
281if [[ ! -v _sev_setup_gpg_forward && -v commands[gpg] ]] {
282 # XXX: assuming /tmo exists and is writable on destination
283 export _GNUPG_SOCK_DEST_BASE=/tmp/.gpg-agent-forward
284 export _GNUPG_SOCK_DEST_EXT=$(date +%s).$RANDOM
285 export _GNUPG_SOCK_DEST=$_GNUPG_SOCK_DEST_BASE.$_GNUPG_SOCK_DEST_EXT
286 export _sev_gpg_forward_dir=${GNUPGHOME:-~/.gnupg}/.ssh_forward
287 _sev_zcleanup gpg-forward
288
289 # find our forwarded socket
290 s=($_GNUPG_SOCK_DEST_BASE*(N=oc[1]))
291 if [[ -n $s && -v SSH_CLIENT ]] {
292 # create new forward dir
293 export _sev_setup_gpg_forward=
294 h=$_sev_gpg_forward_dir/$$
295 mkdir -pm700 $h
296 # XXX: is it safe to link scdaemon socket? can its name be changed?
297 for x (S.scdaemon gpg.conf gpg-agent.conf sshcontrol random_seed
298 pubring.kbx{,~} trustdb.gpg private-keys-v1.d crls.d) {
299 ln -s ${GNUPGHOME:-~/.gnupg}/$x $h
300 }
301 export GNUPGHOME=$h
302 unset h
303 for x in $(gpgconf --list-dirs | grep 'agent-.*-\?socket:'); do
304 x=$(_gpg_socketpath ${x/#agent-*socket:})
305 if [[ ! -v orig ]] {
306 # move forwarded socket to first valid agent socket path
307 # XXX: if tmp is on different filesystem this may not work
308 mv $s $x
309 orig=$x
310 } else {
311 # make links to forwarded socket for any others
312 ln -s $orig $x
313 }
314 done
315 unset x orig
316 }
317 unset s
318
319 # what we will forward if we start a new ssh connection
320 # NOTE: do this after setting up GNUPGHOME to pick up new socket path;
321 # if already connected over SSH, extra should be the remote one
322 export _GNUPG_SOCK_SRC=$(_gpg_socketpath \
323 $(gpgconf --list-dirs agent-extra-socket))
324} elif [[ ! -v _sev_setup_gpg_forward ]] {
325 # required for RemoteForward to not error out if the vars are unset
326 [[ ! -v _GNUPG_SOCK_SRC ]] && export _GNUPG_SOCK_SRC=/nonexistent
327 [[ ! -v _GNUPG_SOCK_DEST ]] && export _GNUPG_SOCK_DEST=/nonexistent
328}
329
330### gpg agent
331if [[ -v commands[gpg-connect-agent] &&
332 ( ! -v _sev_setup_gpgagent || -v _sev_refresh_gpgagent ) ]] {
333 # avoid printing if we have already set up tty before
334 [[ ! -v _sev_setup_gpgagent && -o interactive ]] && p=true || p=false
335 if {$p} {
336 print -nP '%F{blue}>>>%f GPG: '
337 if [[ -v _sev_setup_gpg_forward ]] {
338 print -nP '%F{yellow}Forwarded agent '
339 } else {
340 print -nP '%F{green}Agent '
341 }
342 }
343 gpg-connect-agent /bye >/dev/null 2>&1
344 if [[ $? -ne 0 ]] {
345 $p && print -P '%F{red}communication error'
346 } else {
347 if [[ ! -v _sev_setup_gpg_forward ]] {
348 if [[ ${+GPG_TTY} -eq 0 && -o interactive ]]
349 export GPG_TTY=$(tty)
350 if [[ ( -v DISPLAY || -v WAYLAND_DISPLAY ) &&
351 ${PINENTRY_USER_DATA/USE_TTY=0} == $PINENTRY_USER_DATA ]]
352 export PINENTRY_USER_DATA=USE_TTY=$((
353 ${+DISPLAY} + ${+WAYLAND_DISPLAY} == 0))
354 # XXX: don't know if gpg-agent supports comments after directives
355 # XXX: path could have #
356 # XXX: we are assuming this is our pinentry from .local/bin
357 sed -Ei 's#^([[:space:]]*pinentry-program[[:space:]]).*$#\1'${commands[pinentry]:-/dev/null}'#' \
358 ${GNUPGHOME:-~/.gnupg}/gpg-agent.conf 2>/dev/null
359 # XXX: could check for changes before doing this to save perf
360 gpg-connect-agent RELOADAGENT UPDATESTARTUPTTY /bye >/dev/null 2>&1
361 if {$p} {
362 gpg-connect-agent /subst /serverpid \
363 "/echo pid \${get serverpid} on $GPG_TTY" /bye 2>/dev/null
364 print -nP '%f'
365 }
366 } elif {$p} {
367 print -P '%f'
368 }
369 export _sev_setup_gpgagent=
370 }
371 unset p _sev_refresh_gpgagent
372}
373
374### ssh agent
375if [[ ! -v _sev_setup_ssh ]] {
376 # NOTE: preferred order of agents to check: okcagent, gnupg, openssh
377 # first block takes care of okcagent and openssh, second gnupg
378 # XXX: doesn't actually check if ssh is enabled in gpg
379 [[ -o interactive ]] && print -nP '%F{blue}>>>%f SSH: %F{green}'
380 if [[ ! -v SSH_AUTH_SOCK && ( -v commands[okc-ssh-agent] ||
381 ( -v commands[ssh-agent] && ! -v commands[gpg] ) ) ]] {
382 okc=${commands[okc-ssh-agent]:+okc-}
383 e=$_sev_tmp/${okc}ssh-agent-exports
384 typeset sock=
385 typeset -i pid=
386 if [[ -f $e ]] {
387 IFS=$'\0' read -r sock pid <$e
388 }
389 if [[ -S $sock && $pid > 0 ]] && kill -0 $pid; then
390 [[ -o interactive ]] && print -P "Reusing agent PID $pid%f"
391 export SSH_AUTH_SOCK=$sock
392 export SSH_AGENT_PID=$pid
393 else
394 # TODO: ensure ssh-agent path looks legit to avoid unsafe eval?
395 # XXX: doesn't appear to be any other way to handle redirection.
396 # because eval needs to write to current scope environment
397 # subshells can't be used to capture output and print.
398 c='TMPDIR=$_sev_tmp ${okc}ssh-agent'
399 if [[ -o interactive ]] {
400 eval $(eval $=c)
401 print -nP '%f'
402 } else {
403 eval $(eval $=c) >/dev/null 2>&1
404 }
405 echo -n $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$e
406 unset c
407 fi
408 unset okc e sock pid
409 } elif [[ ! -v SSH_AUTH_SOCK && -v commands[gpg] ]] {
410 # since gpg should have been started above, just export and notify
411 if [[ -o interactive ]] {
412 if [[ -v _sev_setup_gpg_forward ]] {
413 echo 'Forwarded GPG agent'
414 } else {
415 gpg-connect-agent /subst /serverpid \
416 '/echo GPG agent pid ${get serverpid}' /bye
417 }
418 print -nP '%f'
419 }
420 export SSH_AUTH_SOCK=$(_gpg_socketpath \
421 $(gpgconf --list-dirs agent-ssh-socket))
422 } elif [[ -v SSH_AUTH_SOCK ]] {
423 [[ -o interactive ]] && print -P 'Preconfigured agent%f'
424 } else {
425 [[ -o interactive ]] && print -P '%F{red}No agent available%f'
426 }
427
428 export _sev_setup_ssh=
429}
430unfunction _gpg_socketpath
431
432### perl local lib
433[[ -v commands[perl] && -d $XDG_DATA_HOME/perl5/lib/perl5 &&
434 ! -v PERL_LOCAL_LIB_ROOT ]] &&
435 eval $(perl -I$XDG_DATA_HOME/perl5/lib/perl5 \
436 -Mlocal::lib=$XDG_DATA_HOME/perl5 2>/dev/null)
437
438
439### load site-specific
440load-site-dotfile zprofile
This page took 0.035632 seconds and 4 git commands to generate.