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.
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.
22 [[ $OSTYPE =~ (cygwin|msys)* ]] && is_cygwin=
27 export LANG=en_US.UTF-8
31 if [[ -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=
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
51 if [[ ! -v _sev_setup_path || -o login ]] {
53 if [[ -v is_cygwin ]] {
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}
66 # add as many generic paths as possible to keep the order we want
67 # NOTE: /usr/{local,pkg,games} are unix/bsdisms
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)
72 [[ -v is_cygwin ]] && path=("$path[@]" "$winpath[@]")
74 path=("$path[@]" "$syspath[@]")
75 # remove nonexistent and duplicate paths
76 for (( i = 1; i <= $#path; i++ )) {
77 if [[ ! -e $path[$i] ]] {
79 ((i <= ulen)) && ((ulen--))
80 ((i <= wlen)) && ((wlen--))
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]}) ]] {
90 # NOTE: likelihood of our defined windows path being duplicate
91 # is low, but just in case
92 ((j <= wlen)) && ((wlen--))
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
104 typeset +U path fpath
105 export _sev_setup_path=
109 if [[ ! -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.$$
134 if [[ ! -v _sev_setup_tmp ]] {
135 t=${TMPDIR:-${TEMP:-${TMP:-/tmp}}}/.home-$LOGNAME
137 mkdir -m700 $t 2>/dev/null
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
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
152 # ensure proper tmp vars, e.g. msys2 does not set TMPDIR
153 : ${TMPDIR:=${TEMP:-${TMP:-/tmp}}}
158 export _sev_setup_tmp=
162 if [[ ! -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=
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.
202 if [[ ! -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)
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 |
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—
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
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/$$
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
255 for x in $(gpgconf --list-dirs | grep 'agent-.*-\?socket:'); do
256 x=$(_socketpath ${x/#agent-*socket:})
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))
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
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
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"
296 [[ -o interactive ]] &&
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
311 if [[ -f $agentfile ]] {
312 IFS=$'\0' read -r sock pid <$agentfile
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
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 ]] {
328 eval `$e` >/dev/null 2>&1
330 echo -n $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$agentfile
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'
339 gpg-connect-agent /subst /serverpid \
340 '/echo GPG agent PID ${get serverpid}' /bye
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'
349 [[ -o interactive ]] && print -P '%F{red}No agent available%f'
354 unfunction _socketpath
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)
365 if [[ -f ~/.zprofile.local ]] { source ~/.zprofile.local }
367 # vim: et sts=4 sw=4 ts=8 tw=79