]> git.sev.monster Git - dotfiles.git/blame - base/.zprofile
in development
[dotfiles.git] / base / .zprofile
CommitLineData
79d4a356 1# NOTE:
2# our .zprofile is expensive, so we keep track of what has been run already,
3# and only set up what is necessary. additionally, we want to ensure that our
4# environment is set up as early as possible, so we also source .zprofile in
5# .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.
15# * switching users without wiping the environment will result in paths and
16# variables intended for the old user being used for the new user. while
17# this may be considered an edge-case that should not be supported, there
18# are legitimate reasons to want to do this, and in any case the shell
19# should not choke or cause unexpected problems should it happen anyway.
20
21### detect cygwin
22[[ $OSTYPE =~ (cygwin|msys)* ]] && is_cygwin=
23
d569f3f7 24### exports
79d4a356 25## lang
26export CHARSET=UTF-8
27export LANG=en_US.UTF-8
28export LC_CTYPE=$LANG
29
30## msys2
31if [[ -v MSYSTEM && ! -v _sev_setup_msys2 ]] {
32 # path mangling exclusions for gpg-connect-agent
33 # https://www.gnupg.org/documentation/manuals/gnupg/Controlling-gpg_002dconnect_002dagent.html
34 export MSYS2_ARG_CONV_EXCL="${MSYS2_ARG_CONV_EXCL:+$MSYS2_ARG_CONV_EXCL;}\
35/echo;/let ;/definq;/datafile ;/showdef;/cleardev;/sendfd ;/recvfd;/open ;\
36/close ;/showopen;/serverpid;/sleep;/hex;/nohex;/decode;/nodecode;/subst;\
37/nosubst;/while ;/if ;/end;/run ;/bye;/help"
38 # ssh called from mingw64-git attempts to convert path to Windows, and
39 # causes it to choke. paths are converted to *nix before exporting and
40 # will work if cygwin ssh is installed (default).
41 export MSYS2_ENV_CONV_EXCL=_GNUPG_SOCK_
42 export _sev_setup_msys2=
43}
44
45
46## path
47# NOTE: we utilize the fact that unique arrays keep the first occurrence and
48# remove any further occurences to capture elements from the old PATH
49# that we did not anticipate and shift them to the front, since they are
50# probably important to the system
51if [[ ! -v _sev_setup_path || -o login ]] {
52 typeset -a winpath
53 if [[ -v is_cygwin ]] {
54 windir=$(cygpath -uW)
55 sysdir=$(cygpath -uS)
56 winpath=($sysdir $windir $sysdir/Wbem
57 $sysdir/WindowsPowerShell/v1.0
58 $sysdir/../SysWOW64 $sysdir/../SysWOW64/Wbem
59 $sysdir/../SysWOW64/WindowsPowerShell/v1.0)
60 for (( i = 1; i <= $#winpath; i++ )) {
61 winpath[$i]=${winpath[$i]:a}
62 }
63 unset windir sysdir
64 }
65 typeset -U path fpath
66 # add as many generic paths as possible to keep the order we want
67 # NOTE: /usr/{local,pkg,games} are unix/bsdisms
68 syspath=("$path[@]")
69 path=({~/,/,/usr/}sbin /opt/{s,}bin /usr/local/{s,}bin /usr/pkg/{s,}bin
70 /usr/X11R{7,6}/bin /usr/games {~/,/,/usr/}bin)
71 ((ulen=$#path))
72 [[ -v is_cygwin ]] && path=("$path[@]" "$winpath[@]")
73 ((wlen=$#path))
74 path=("$path[@]" "$syspath[@]")
75 # remove nonexistent and duplicate paths
76 for (( i = 1; i <= $#path; i++ )) {
77 if [[ ! -e $path[$i] ]] {
78 path[$i]=()
79 ((i <= ulen)) && ((ulen--))
80 ((i <= wlen)) && ((wlen--))
81 ((i--))
82 continue
83 }
84 if [[ ! -v is_cygwin ]] || (( i <= ulen )) { continue }
85 # Windows only: remove cygwin-ified duplicates case-insensitively
86 c=$(cygpath -u -- ${(L)path[$i]})
87 for (( j = i + 1; j <= $#path; j++ )) {
88 if [[ $c == $(cygpath -u -- ${(L)path[$j]}) ]] {
89 path[$j]=()
90 # NOTE: likelihood of our defined windows path being duplicate
91 # is low, but just in case
92 ((j <= wlen)) && ((wlen--))
93 ((j--))
94 }
95 }
96 unset c
97 }
98 (( wlen > 0 )) && path=("${(@)path[wlen + 1, -1]}" "${(@)path[1, wlen]}")
99 unset winpath syspath ulen wlen i j
100 # include our zsh dir in fpath. unlike above, we always prefer our paths
101 fpath=(${ZDOTDIR:-~/.zsh}/functions/{*,Completions/*}(N) "$fpath[@]")
102 # FPATH is not exported by default
103 export FPATH
104 typeset +U path fpath
105 export _sev_setup_path=
106}
107
108## xdg
109if [[ ! -v _sev_setup_xdg ]] {
110 # merge with any existing dirs and remove duplicates using unique arrays
111 # NOTE: include and then remove .config and .local/share to ensure it is
112 # not present in the array if it was added before we got to it
113 typeset -UT XDG_CONFIG_DIRS xdg_config_dirs
114 typeset -UT XDG_DATA_DIRS xdg_data_dirs
115 export XDG_CONFIG_HOME=$HOME/etc
116 xdg_config_dirs=($XDG_CONFIG_HOME $HOME/.config
117 {/opt,/usr/local,/usr/pkg,}/etc/xdg
118 "${XDG_CONFIG_DIRS:+${xdg_config_dirs[@]}}")
119 export XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS#$XDG_CONFIG_HOME}
120 export XDG_DATA_HOME=$HOME/share
121 xdg_data_dirs=($XDG_DATA_HOME $HOME/.local/share
122 /{opt,usr/local,usr/pkg,usr}/share
123 "${XDG_DATA_DIRS:+${xdg_data_dirs[@]}}")
124 export XDG_DATA_DIRS=${XDG_DATA_DIRS#$XDG_DATA_HOME}
125 # use our custom tmp for cache and runtime
126 export XDG_CACHE_HOME=~/tmp
127 # NOTE: it's intentional to keep the same runtime dir for the whole session
128 # and not create a new one if a new login shell is spawned, since the
129 # spec calls for the same dir to be utilized for each "session".
130 export XDG_RUNTIME_DIR=~/tmp/xdg.$$
131}
132
133## temp
134if [[ ! -v _sev_setup_tmp ]] {
135 t=${TMPDIR:-${TEMP:-${TMP:-/tmp}}}/.home-$LOGNAME
136 if [[ ! -e $t ]] {
137 mkdir -m700 $t 2>/dev/null
138 if [[ ! -d $t ]] {
139 [[ -o interactive ]] &&
140 print -P "%F{red}!!! Can't create temp folder $t%f"
141 # fallback bare directories
142 [[ -h $XDG_CACHE_HOME ]] && unlink $XDG_CACHE_HOME 2>/dev/null
143 [[ ! -e $XDG_CACHE_HOME ]] && mkdir -m700 $XDG_CACHE_HOME 2>/dev/null
144 }
145 }
146 if [[ -e $t ]] {
147 export TMPDIR=$t TEMP=$t TMP=$t
148 # [re-]create link to our tmp if safe
149 [[ -h $XDG_CACHE_HOME || ! -e $XDG_CACHE_HOME ]] &&
150 ln -sf $t $XDG_CACHE_HOME 2>/dev/null
151 } else {
152 # ensure proper tmp vars, e.g. msys2 does not set TMPDIR
153 : ${TMPDIR:=${TEMP:-${TMP:-/tmp}}}
154 : ${TEMP:=$TMPDIR}
155 : ${TMP:=$TMPDIR}
156 }
157 unset t
158 export _sev_setup_tmp=
159}
160
161## xdg
162if [[ ! -v _sev_setup_xdg ]] {
163 # create xdg runtime dir
164 # NOTE: spec says the dir should only exist for the lifetime of the
165 # session, so if there is already something there it is likely stale
166 # or something is very broken—assume the former.
167 [[ -e $XDG_RUNTIME_DIR ]] && rm -rf $XDG_RUNTIME_DIR 2>/dev/null &&
168 mkdir -m700 $XDG_RUNTIME_DIR 2>/dev/null
169 # source user dirs after other vars
170 [[ -e $XDG_CONFIG_HOME/user-dirs.dirs ]] &&
171 emulate sh -c "source $XDG_CONFIG_HOME/user-dirs.dirs"
172 export _sev_setup_xdg=
d569f3f7 173}
79d4a356 174
175## gpg forwarding
176# NOTE: while ssh manages its auth sock in its protocol when ForwardSsh is
177# enabled, GPG must be forwarded manually over Unix socket. to support
178# this, we forward the restricted gpg-agent extra socket to the remote
179# host with a RemoteForward rule in ~/.ssh/config that uses the
180# _GNUPG_SOCK_* env vars. to avoid conflicts with other ssh sessions
181# where the same user is connecting to the same host from different
182# machines, gpg in each environment should utilize its own forwarded
183# socket, rather than replace the sockets in GNUPGHOME which will be
184# overridden on the next connection. previously, you could provide a path
185# to the agent socket in GPG_AGENT_INFO, but that was deprecated in GPG
186# v2.1. instead, we must clone GNUPGHOME and replace the agent sockets
187# there with the forwarded one.
188# NOTE: since Unix sockets are not supported under Windows, this will not work
189# under msys, cygwin, mingw, etc.
190# HACK: without SendEnv, which is disabled by default in most sshd configs,
191# there is no foolproof way to prevent race conditions via filename
192# collisions or to pass the desired forward path to the remote host
193# environment. we just have to guess the path we choose is good on the
194# desination, and assume the newest matching socket is the correct one
195# after connecting. in theory, we could occlude the ssh binary on PATH
196# with an alias or script that would allow us to communicate with the
197# remote host before opening a shell, so that we can have the host
198# communicate back to the client where it wants a socket created or ask
199# the host if the path the client wants to use is writable. however, this
200# would open up too many edge cases where it wouldn't work or be clunky
201# (e.g. asking for password twice) to make it worth it.
202if [[ ! -v _sev_setup_gpg ]] {
203 # helper function for decoding gpgconf socket paths
204 function _socketpath {
205 # dirs are percent-encoded
206 # https://stackoverflow.com/a/64312099
207 local x=${1//(#b)%([[:xdigit:]](#c2))/${(#):-0x$match[1]}}
208 # remove \r from Windows paths
209 if [[ -v commands[cygpath] ]] {
210 x=$(cygpath -u -- ${x/%$'\r'} 2>/dev/null)
211 }
212 echo $x
213 }
214
215 if [[ ! -v _sev_gpg_forwarded && -v commands[gpg] ]] {
216 export _GNUPG_SOCK_DEST_BASE=/tmp/.gpg-agent-forward
217 export _GNUPG_SOCK_DEST_EXT=$(date +%s).$RANDOM
218 export _GNUPG_SOCK_DEST=$_GNUPG_SOCK_DEST_BASE.$_GNUPG_SOCK_DEST_EXT
219 export _sev_gpg_forward_dir=${GNUPGHOME:-~/.gnupg}/.ssh_forward
220 # clean up forwards if its session is dead or we ask for it
221 if [[ -d $_sev_gpg_forward_dir ]] {
222 find $_sev_gpg_forward_dir -type d -mindepth 1 -maxdepth 1 |
223 while read -r x; do
224 # NOTE: the only way we can get here is if we have not been
225 # forwarded before. if our own pid already has a dir, it
226 # is most likely stale, or something is very broken—
227 # assume the former.
228 p=$(basename $x)
229 if [[ -v _sev_gpg_forward_clean || $$ == $p ]] ||
230 ! kill -0 $p 2>/dev/null; then
231 find $x -mindepth 1 -maxdepth 1 | while read -r y; do
232 unlink $y
233 done
234 rmdir $x
235 fi
236 done
237 unset x p y
238 }
239
240 # find our forwarded socket
241 s=($_GNUPG_SOCK_DEST_BASE*(N=oc[1]))
242 if [[ -n $s && -v SSH_CLIENT ]] {
243 # create new forward dir
244 export _sev_gpg_forwarded=
245 mkdir -pm700 $_sev_gpg_forward_dir
246 h=$_sev_gpg_forward_dir/$$
247 mkdir -pm700 $h
248 # XXX: is it safe to link scdaemon socket? can its name be changed?
249 for x in S.scdaemon gpg.conf gpg-agent.conf sshcontrol \
250 pubring.kbx trustdb.gpg private-keys-v1.d crls.d; do
251 ln -s ${GNUPGHOME:-~/.gnupg}/$x $h
252 done
253 export GNUPGHOME=$h
254 unset h
255 for x in $(gpgconf --list-dirs | grep 'agent-.*-\?socket:'); do
256 x=$(_socketpath ${x/#agent-*socket:})
257 if [[ ! -v orig ]] {
258 mv $s $x
259 orig=$x
260 } else {
261 ln -s $orig $x
262 }
263 done
264 unset x orig
265 }
266 unset s
267
268 # what we will forward if we start a new ssh connection
269 # NOTE: do this after setting up GNUPGHOME to pick up new socket path;
270 # if already connected over SSH, extra should be the remote one
271 export _GNUPG_SOCK_SRC=$(_socketpath \
272 $(gpgconf --list-dirs agent-extra-socket))
273 } else {
274 # required for RemoteForward to not error out if the vars are unset
275 [[ ! -v _GNUPG_SOCK_SRC ]] && export _GNUPG_SOCK_SRC=/nonexistent
276 [[ ! -v _GNUPG_SOCK_DEST ]] && export _GNUPG_SOCK_DEST=/nonexistent
277 }
278
279 ## gpg agent
280 if [[ -v commands[gpg-connect-agent] ]] {
281 [[ -o interactive ]] && print -nP '%F{blue}>>>%f GPG agent: %F{green}'
282 gpg-connect-agent /bye >/dev/null 2>&1
283 if [[ $? -ne 0 ]] {
284 [[ -o interactive ]] &&
285 print -P '%F{red}Error communicating with GPG agent%f'
286 } elif [[ ! -v _sev_gpg_forward && ! -v GPG_TTY &&
287 ( -o interactive || -v DISPLAY ) ]] {
288 # if we aren't forwarded, set up tty if it isn't and we're
289 # in an interactive session
290 export GPG_TTY=$(tty)
291 export PINENTRY_USER_DATA=USE_TTY=$((!${+DISPLAY}))
292 gpg-connect-agent UPDATESTARTUPTTY /bye >/dev/null 2>&1
293 [[ -o interactive ]] &&
294 print -P "Updated TTY%f"
295 } else {
296 [[ -o interactive ]] &&
297 print -P 'Ready%f'
298 }
299 }
300
301 ## ssh agent
302 # NOTE: preferred order of agents to check: okcagent, gnupg, openssh
303 # first block takes care of okcagent and openssh, second gnupg
304 [[ -o interactive ]] && print -nP '%F{blue}>>>%f SSH: %F{green}'
305 if [[ ! -v SSH_AUTH_SOCK && ( -v commands[okc-ssh-agent] ||
306 ( -v commands[ssh-agent] && ! -v commands[gpg] ) ) ]] {
307 okc=${commands[okc-ssh-agent]:+okc-}
308 agentfile=~/tmp/${okc}ssh-agent-exports
309 typeset sock=
310 typeset -i pid=
311 if [[ -f $agentfile ]] {
312 IFS=$'\0' read -r sock pid <$agentfile
313 }
314 if [[ -S $sock && $pid > 0 ]] && kill -0 $pid; then
315 [[ -o interactive ]] && print -P "Reusing agent PID $pid%f"
316 export SSH_AUTH_SOCK=$sock
317 export SSH_AGENT_PID=$pid
318 else
319 e=${okc}ssh-agent
320 # TODO: ensure ssh-agent path looks legit to avoid unsafe eval?
321 # XXX: doesn't appear to be any other way to handle redirection.
322 # because eval needs to write to current scope environment
323 # subshells can't be used to capture output and print.
324 if [[ -o interactive ]] {
325 eval `$e`
326 print -nP '%f'
327 } else {
328 eval `$e` >/dev/null 2>&1
329 }
330 echo -n $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$agentfile
331 fi
332 unset okc agentfile sock pid
333 } elif [[ ! -v SSH_AUTH_SOCK && -v commands[gpg] ]] {
334 # since gpg agent was started above, we just have to export and notify
335 if [[ -o interactive ]] {
336 if [[ -v _sev_gpg_forwarded ]] {
337 echo 'Remote GPG agent'
338 } else {
339 gpg-connect-agent /subst /serverpid \
340 '/echo GPG agent PID ${get serverpid}' /bye
341 }
342 print -nP '%f'
343 }
344 export SSH_AUTH_SOCK=$(_socketpath \
345 $(gpgconf --list-dirs agent-ssh-socket))
346 } elif [[ -v SSH_AUTH_SOCK ]] {
347 [[ -o interactive ]] && print -P 'Preconfigured agent%f'
348 } else {
349 [[ -o interactive ]] && print -P '%F{red}No agent available%f'
350 }
351
352 ## cleanup
353 # unset gpg helper
354 unfunction _socketpath
355
356 ## perl local lib
357 [[ -v commands[perl] && -d $XDG_DATA_HOME/perl5/lib/perl5 ]] &&
358 eval $(perl -I$XDG_DATA_HOME/perl5/lib/perl5
359 -Mlocal::lib=$XDG_DATA_HOME/perl5 2>/dev/null)
360}
361
362unset is_cygwin
363
364# load site-specific
8eb81f95 365if [[ -f ~/.zprofile.local ]] { source ~/.zprofile.local }
366
79d4a356 367# vim: et sts=4 sw=4 ts=8 tw=79
This page took 0.076692 seconds and 4 git commands to generate.