1#compdef ssh slogin=ssh scp ssh-add ssh-agent ssh-copy-id ssh-keygen ssh-keyscan sftp
2
3# TODO: sshd, ssh-keysign
4
5_ssh () {
6  local curcontext="$curcontext" state line expl suf arg ret=1
7  local args sigargs common common_transfer algopt tmp p1 file cmn cmds sdesc tdesc
8  typeset -A opt_args
9
10  common=(
11    '(-6)-4[force ssh to use IPv4 addresses only]'
12    '(-4)-6[force ssh to use IPv6 addresses only]'
13    '-C[compress data]'
14    '-c+[select encryption cipher]:encryption cipher:->ciphers'
15    '-F+[specify alternate config file]:config file:_files'
16    '*-i+[select identity file]:SSH identity file:_files -g "*(-.^AR)"'
17    '*-o+[specify extra options]:option string:->option'
18  )
19  common_transfer=(
20    '-J+[connect via a jump host]: :->userhost'
21    '-l+[limit used bandwidth]:bandwidth (Kbit/s)'
22    '-P+[specify port on remote host]:port number on remote host'
23    '-p[preserve modification times, access times and modes]'
24    '-q[disable progress meter and warnings]'
25    '-r[recursively copy directories (follows symbolic links)]'
26    '-S+[specify ssh program]:path to ssh:_command_names -e' \
27    '-v[verbose mode]'
28  )
29  algopt='-E+[specify hash algorithm for fingerprints]:algorithm:(md5 sha256)'
30
31  case "$service" in
32  ssh)
33    (( $+words[(r)-[^-]#t*] )) && tdesc=' even if there is no controlling tty'
34    _arguments -C -s \
35      '(-a)-A[enable forwarding of the authentication agent connection]' \
36      '(-A)-a[disable forwarding of authentication agent connection]' \
37      '-B+[bind to specified interface before attempting to connect]:interface:_net_interfaces' \
38      '(-P)-b+[specify interface to transmit on]:bind address:_bind_addresses' \
39      '-D+[specify a dynamic port forwarding]:dynamic port forwarding:->dynforward' \
40      '-e+[set escape character]:escape character (or `none'\''):' \
41      '-E+[append log output to file instead of stderr]:_files' \
42      '(-n)-f[go to background]' \
43      '-g[allow remote hosts to connect to local forwarded ports]' \
44      '-G[output configuration and exit]' \
45      '-I+[specify smartcard device]:device:_files' \
46      '-J+[connect via a jump host]: :->userhost' \
47      '-K[enable GSSAPI-based authentication and forwarding]' \
48      '-k[disable forwarding of GSSAPI credentials]' \
49      '*-L+[specify local port forwarding]:local port forwarding:->forward' \
50      '-l+[specify login name]:login name:_ssh_users' \
51      '-M[master mode for connection sharing]' \
52      '-m+[specify mac algorithms]: :->macs' \
53      "-N[don't execute a remote command]" \
54      '-n[redirect stdin from /dev/null]' \
55      '-O+[control an active connection multiplexing master process]:multiplex control command:((check\:"check master process is running" exit\:"request the master to exit" forward\:"request forward without command execution" stop\:"request the master to stop accepting further multiplexing requests" cancel\:"cancel existing forwardings with -L and/or -R" proxy))' \
56      '-P[use non privileged port]' \
57      '-p+[specify port on remote host]:port number on remote host' \
58      '(-v)*-q[quiet operation]' \
59      '*-R+[specify remote port forwarding]:remote port forwarding:->forward' \
60      '-S+[specify location of control socket for connection sharing]:path to control socket:_files' \
61      '-Q+[query parameters]:query option:((cipher\:"supported symmetric ciphers" cipher-auth\:"supported symmetric ciphers that support authenticated encryption" mac\:"supported message integrity codes" kex\:"key exchange algorithms" key\:"key types" key-cert\:"certificate key types" key-plain\:"non-certificate key types" protocol-version\:"supported SSH protocol versions" sig\:"supported signature algorithms" help\:"show supported queries"))' \
62      '-s[invoke subsystem]' \
63      '(-t)-T[disable pseudo-tty allocation]' \
64      "(-T)*-t[force pseudo-tty allocation${tdesc}]" \
65      '-V[show version number]' \
66      '(-q)*-v[verbose mode (multiple increase verbosity, up to 3)]' \
67      '-W+[forward standard input and output to host]:stdinout forward:->hostport' \
68      '-w+[request tunnel device forwarding]:local_tun[\:remote_tun] (integer or "any"):' \
69      '(-x -Y)-X[enable (untrusted) X11 forwarding]' \
70      '(-X -Y)-x[disable X11 forwarding]' \
71      '(-x -X)-Y[enable trusted X11 forwarding]' \
72      '-y[send log info via syslog instead of stderr]' \
73      ':remote host name:->userhost' \
74      '*::args:->command' "$common[@]" && ret=0
75    ;;
76  scp)
77    _arguments -C -s \
78      '-3[copy through local host, not directly between the remote hosts]' \
79      '-B[batch mode (don'\''t ask for passphrases)]' \
80      '-T[disable strict filename checking]' \
81      '*:file:->file' "$common[@]" "$common_transfer[@]" && ret=0
82    ;;
83  ssh-add)
84    [[ $OSTYPE == darwin* ]] && args=(
85      '-A[add identities from keychain]'
86      '-K[update keychain when adding/removing identities]'
87    )
88    _arguments -s : $args \
89      '-c[identity is subject to confirmation via SSH_ASKPASS]' \
90      '-D[delete all identities]' \
91      '-d[remove identity]' \
92      $algopt \
93      '-e+[remove keys provided by the PKCS#11 shared library]:library:_files -g "*.(so|dylib)(|.<->)(-.)"' \
94      '-k[load plain private keys only and skip certificates]' \
95      '-L[list public key parameters of all identities in the agent]'\
96      '-l[list all identities]' \
97      '-m+[specify minimum remaining signatures before maximum is changed]:number' \
98      '-M+[specify maximum number of signatures]:number' \
99      '-s+[add keys provided by the PKCS#11 shared library]:library:_files -g "*.(so|dylib)(|.<->)(-.)"' \
100      '-t+[set maximum lifetime for identity]:maximum lifetime (in seconds or time format):' \
101      "-T[test usability of identity files' private keys]:*:public key file:_files -g '*.pub(-.)'" \
102      '-v[verbose mode]' \
103      '-q[be quiet after a successful operation]' \
104      '-X[unlock the agent]' \
105      '-x[lock the agent with a password]' \
106      '*:SSH identity file:_files'
107    return
108    ;;
109  ssh-agent)
110    _arguments -s \
111      '(-k)-a+[specify UNIX-domain socket to bind agent to]:UNIX-domain socket:_files' \
112      '(-k -s)-c[force csh-style shell]' \
113      '(-k)-d[debug mode]' \
114      '(-k)-D[foreground mode]' \
115      "(-k)$algopt" \
116      '-k[kill current agent]' \
117      '(-k)-P[specify PKCS#11 shared library whitelist]:PKCS#11 library whitelist pattern' \
118      '(-k -c)-s[force sh-style shell]' \
119      '-t[set default maximum lifetime for identities]:maximum lifetime (in seconds or time format):' \
120      '-v[verbose mode]' \
121      '*::command: _normal'
122    return
123    ;;
124  ssh-keygen)
125    # options can be in any order but use ! to limit those shown for the first argument
126    (( CURRENT == 2 )) && p1='!'
127    args=( '!-z:number' )
128    sdesc='certify keys with CA key'
129    (( $+words[(r)-I] )) && args=( '-z[specify serial number]:serial number' )
130    (( $+words[(r)-[ku]] )) && args=( '-z[specify version number]:version number' ) &&
131        sdesc='specify CA public key file'
132    file=key
133    (( $+words[(r)-[FHR]] )) && file=known_hosts
134    (( $+words[(r)-T] )) && file=input
135    (( $+words[(r)-A] )) && file='prefix for host key'
136    if (( $+words[(r)-[kIQ]] )); then
137      file=krl
138      args+=( '*:file:_files' )
139    fi
140    if (( arg = $words[(I)-Y*] )); then
141      [[ $words[arg] = -Y?* ]] || (( arg++ ))
142      case $words[arg] in
143	check*|verify)
144	  sigargs+=( "$p1-s+[specify signature file]:signature file:-files" )
145	;|
146	sign) sigargs+=( '*:file:_files' ) ;;
147	verify)
148	  args=()
149	  sigargs+=(
150	    '-I+[specify signer identity]:identity'
151	    '-r+[specify revocation file]:revocation file:_files'
152	  )
153	;;
154      esac
155    fi
156    cmds=( -p -i -e -y -c -l -B -D -F -H -R -r -G -T -s -L -A -k -Q -Y ) # basic commands
157    cmn=( -b -P -N -C -l -m -v ) # options common to many basic commands (except -f which is common to most)
158    cms=( -E -q -t -g -M -S -a -J -j -K -W -I -h -n -O -V -u -U ) # options specific to one basic command
159    _arguments -s $args \
160      "(${${(@)cmds:#-G}} -P ${${(@)cms:#-[MS]}})-b+[specify number of bits in key]:bits in key" \
161      "$p1(${${(@)cmds:#-[pc]}} -b $cms)-P+[provide old passphrase]:old passphrase" \
162      "(${${(@)cmds:#-p}} -v ${${(@)cms:#-[qt]}})-N+[provide new passphrase]:new passphrase" \
163      "(${${(@)cmds:#-c}} -v $cms)-C+[provide new comment]:new comment" \
164      "(-D -G -M -S -I -h -n -O -V -A)-f+[$file file]:$file file:_files" \
165      "$p1(${${(@)cmds:#-[FE]}} ${${(@)cmn:#-v}} ${${(@)cms:#-E}})-l[show fingerprint of key file]" \
166      "$p1(${${(@)cmds:#-[iep]}} $cms)-m+[specify conversion format]:format [RFC4716]:(PEM PKCS8 RFC4716)" \
167      "(${${(@)cmds:#-[lGT]}} ${${(@)cmn:#-[bv]}} -f)*-v[verbose mode]" \
168      - '(commands)' \
169      "(-b -l -C -v)-p[change passphrase of private key file]" \
170      '(-b -l -P -N -C -v)-i[import key to OpenSSH format]' \
171      '(-b -l -P -N -C -v)-e[export key to SECSH file format]' \
172      "($cmn)-y[get public key from private key]" \
173      '(-b -l -N -m -v)-c[change comment in private and public key files]' \
174      "($cmn)-B[show the bubblebabble digest of key]" \
175      "(-)-D+[download key stored in smartcard reader]:reader" \
176      "(${${(@)cmn:#-[lv]}})-F+[search for host in known_hosts file]:host:_ssh_hosts" \
177      "($cmn)-H[hash names in known_hosts file]" \
178      "($cmn)-R+[remove host from known_hosts file]:host:_ssh_hosts" \
179      "($cmn)-L[print the contents of a certificate]" \
180      "($cmn -l)-A[generate host keys for all key types]" \
181      "($cmn)-Q[test whether keys have been revoked in a KRL]" \
182      - finger \
183      "$p1($cmn)$algopt" \
184      - create \
185      '(-P -l)-q[silence ssh-keygen]' \
186      "(-P -l)-t+[specify the type of the key to create]:key type:(rsa dsa ecdsa ed25519)" \
187      - dns \
188      "($cmn)-r[print DNS resource record]:hostname:_hosts" \
189      "$p1($cmn)-g[use generic DNS format]" \
190      - primes \
191      "(-P -N -C -l -m -f)-G+[generate candidates for DH-GEX moduli]:output file:_files" \
192      "$p1(-P -N -C -l -m -f)-M+[specify amount of memory to use for generating DH-GEX moduli]:memory (MB)" \
193      "$p1(-P -N -C -l -m -f)-S+[specify start point]:start point (hex)" \
194      - screen \
195      "(${${(@)cmn:#-v}})-T+[screen candidates for DH-GEX moduli]:output file:_files" \
196      "${p1}(${${(@)cmn:#-v}})-a+[specify number of rounds]:rounds" \
197      "${p1}(${${(@)cmn:#-v}})-J[exit after screening specified number of lines]" \
198      "${p1}(${${(@)cmn:#-v}})-j+[start screening at the specified line number]:line number" \
199      "${p1}(${${(@)cmn:#-v}})-K+[write the last line processed to file]:file:_files" \
200      "${p1}(${${(@)cmn:#-v}})-W[specify desired generator]:generator" \
201      - certify \
202      "($cmn)-s[$sdesc]:CA key:_files" \
203      "$p1($cmn -f -k -u)-I+[specify key identifier to include in certificate]:key id" \
204      "$p1($cmn -f -k -u)-h[generate host certificate instead of a user certificate]" \
205      "$p1($cmn -f -k -u -D)-U[indicate that CA key is held by ssh-agent]" \
206      "$p1($cmn -f -k -u -U)-D+[indicate the CA key is stored in a PKCS#11 token]:PKCS11 shared library:_files -g '*.(so|dylib)(|.<->)(-.)'" \
207      "$p1($cmn -f -k -u)-n+[specify user/host principal names to include in certificate]:principals" \
208      "$p1($cmn -f -k -u)*-O+[specify a certificate option]: : _values 'option'
209        clear critical\:name extension\:name force-command\:command\:_cmdstring
210	no-agent-forwarding no-port-forwarding no-pty no-user-rc no-x11-forwarding
211	permit-agent-forwarding permit-port-forwarding permit-pty permit-user-rc
212	permit-x11-forwarding source-address\:source\ address" \
213      "$p1($cmn -f -u)-V+[specify certificate validity interval]:interval" \
214      "($cmn -I -h -n -D -O -U -V)-k[generate a KRL file]" \
215      "$p1($cmn -I -h -n -D -O -U -V)-u[update a KRL]" \
216      - signature \
217      "($cmn)-Y+[signature action]:action:((
218	sign\:sign\ a\ file\ using\ SSH\ key
219	verify\:verify\ a\ signature\ generated\ using\ the\ sign\ option
220	check-novalidate\:check\ signature\ structure
221      ))" \
222      "$p1-n+[specify namespace]:namespace" \
223      $sigargs
224    return
225  ;;
226  ssh-keyscan)
227    _arguments \
228      '(-6)-4[force ssh to use IPv4 addresses only]' \
229      '(-4)-6[force ssh to use IPv6 addresses only]' \
230      '-c[request certificates from target hosts instead of plain keys]' \
231      '-D[print keys found as SSHFP DNS records]' \
232      '*-f+[read hosts from file, one per line]:file:_files' \
233      '-H[hash all hostnames and addresses in the output]' \
234      '-p+[specify port on remote host]:port number on remote host' \
235      '-T+[specify timeout]:timeout (seconds) [5]' \
236      '-t+[specify key types to fetch from scanned hosts]:key type:_sequence compadd - rsa dsa ecdsa ed25519' \
237      '-v[verbose mode]'
238    return
239  ;;
240  sftp)
241    _arguments -C -s \
242      '-a[attempt to continue interrupted transfers]' \
243      '-B+[specify buffer size]:buffer size (bytes) [32768]' \
244      '-b+[specify batch file to read]:batch file:_files' \
245      '-D+[connect directly to a local sftp server]:sftp server path' \
246      '-f[request that files be flushed immediately after transfer]' \
247      '-R+[specify number of outstanding requests]:number of requests [64]' \
248      '-s+[specify SSH2 subsystem or path to sftp server on the remote host]:subsystem/path' \
249      '1:file:->rfile' '*:file:->file' "$common[@]" "$common_transfer[@]" && ret=0
250    ;;
251  ssh-copy-id)
252    _arguments \
253      '-i+[select identity file]:SSH identity file:_files -g "*(-.^AR)"' \
254      '-f[copy keys without trying to check if they are already installed]' \
255      '-n[dry run - no keys are actually copied]' \
256      '*-o+[specify ssh options]:option string:->option' \
257      '-p+[specify port on remote host]:port number on remote host' \
258      '(- 1)'{-h,-\?}'[display usage information]' \
259      ':remote host name:->userhost' && ret=0
260    ;;
261  esac
262
263  while [[ -n "$state" ]]; do
264    lstate="$state"
265    state=''
266
267    case "$lstate" in
268    option)
269      if compset -P 1 '*='; then
270        case "${IPREFIX#-o}" in
271          (#i)(ciphers|macs|kexalgorithms|hostkeyalgorithms|pubkeyacceptedkeytypes|hostbasedkeytypes)=)
272          if ! compset -P +; then
273            _wanted append expl 'append to default' compadd + && ret=0
274          fi
275          ;;
276        esac
277        case "${IPREFIX#-o}" in
278        (#i)(afstokenpassing|batchmode|canonicalizefallbacklocal|challengeresponseauthentication|checkhostip|clearallforwardings|compression|enablesshkeysign|exitonforwardfailure|fallbacktorsh|forward(agent|x11)|forwardx11trusted|gatewayports|gssapiauthentication|gssapidelegatecredentials|gssapikeyexchange|gssapirenewalforcesrekey|gssapitrustdns|hashknownhosts|hostbasedauthentication|identitiesonly|kbdinteractiveauthentication|(tcp|)keepalive|nohostauthenticationforlocalhost|passwordauthentication|permitlocalcommand|proxyusefdpass|pubkeyauthentication|rhosts(|rsa)authentication|rsaauthentication|streamlocalbindunlink|usersh|kerberos(authentication|tgtpassing)|useprivilegedport|visualhostkey)=*)
279          _wanted values expl 'truth value' compadd yes no && ret=0
280          ;;
281        (#i)addressfamily=*)
282          _wanted values expl 'address family' compadd any inet inet6 && ret=0
283          ;;
284        (#i)bindaddress=*)
285          _wanted bind-addresses expl 'bind address' _bind_addresses && ret=0
286          ;;
287        (#i)canonicaldomains=*)
288          _message -e 'canonical domains (space separated)' && ret=0
289          ;;
290        (#i)canonicalizehostname=*)
291          _wanted values expl 'truthish value' compadd yes no always && ret=0
292          ;;
293        (#i)canonicalizemaxdots=*)
294          _message -e 'number of dots' && ret=0
295          ;;
296        (#i)canonicalizepermittedcnames=*)
297          _message -e 'CNAME rule list (source_domain_list:target_domain_list, each pattern list comma separated)' && ret=0
298          ;;
299        (#i)ciphers=*)
300          state=ciphers
301          ;;
302        (#i)connectionattempts=*)
303          _message -e 'connection attempts' && ret=0
304          ;;
305        (#i)connecttimeout=*)
306          _message -e 'connection timeout' && ret=0
307          ;;
308        (#i)controlmaster=*)
309          _wanted values expl 'truthish value' compadd yes no auto autoask && ret=0
310          ;;
311        (#i)controlpath=*)
312          _description files expl 'path to control socket'
313          _files "$expl[@]" && ret=0
314          ;;
315        (#i)controlpersist=*)
316          _message -e 'timeout'
317          ret=0
318          _wanted values expl 'truth value' compadd yes no && ret=0
319          ;;
320        (#i)escapechar=*)
321          _message -e 'escape character (or `none'\'')'
322          ret=0
323          ;;
324        (#i)fingerprinthash=*)
325          _values 'fingerprint hash algorithm' \
326              md5 ripemd160 sha1 sha256 sha384 sha512 && ret=0
327          ;;
328        (#i)forwardx11timeout=*)
329          _message -e 'timeout'
330          ret=0
331          ;;
332        (#i)globalknownhostsfile=*)
333          _description files expl 'global file with known hosts'
334          _files "$expl[@]" && ret=0
335          ;;
336        (#i)hostname=*)
337          _wanted hosts expl 'real host name to log into' _ssh_hosts && ret=0
338          ;;
339        (#i)(hostbasedkeytypes|hostkeyalgorithms|pubkeyacceptedkeytypes)=*)
340	  _wanted key-types expl 'key type' _sequence compadd - $(_call_program key-types ssh -Q key) && ret=0
341          ;;
342        (#i)identityfile=*)
343          _description files expl 'SSH identity file'
344          _files "$expl[@]" && ret=0
345          ;;
346        (#i)ignoreunknown=*)
347          _message -e 'pattern list' && ret=0
348          ;;
349        (#i)ipqos=*)
350          local descr
351          if [[ $PREFIX = *\ *\ * ]]; then return 1; fi
352          if compset -P '* '; then
353            descr='QoS for non-interactive sessions'
354          else
355            descr='QoS [for interactive sessions if second value given, separated by white space]'
356          fi
357          _values $descr 'af11' 'af12' 'af13' 'af14' 'af22' \
358              'af23' 'af31' 'af32' 'af33' 'af41' 'af42' 'af43' \
359              'cs0' 'cs1' 'cs2' 'cs3' 'cs4' 'cs5' 'cs6' 'cs7' 'ef' \
360              'lowdelay' 'throughput' 'reliability' && ret=0
361          ;;
362        (#i)(local|remote)forward=*)
363          state=forward
364          ;;
365        (#i)dynamicforward=*)
366          state=dynforward
367          ;;
368        (#i)kbdinteractivedevices=*)
369          _values -s , 'keyboard-interactive authentication methods' \
370              'bsdauth' 'pam' 'skey' && ret=0
371          ;;
372        (#i)(kexalgorithms|gssapikexalgorithms)=*)
373          _wanted algorithms expl 'key exchange algorithm' _sequence compadd - \
374              $(_call_program algorithms ssh -Q kex) && ret=0
375          ;;
376        (#i)localcommand=*)
377          _description commands expl 'run command locally after connecting'
378          _command_names && ret=0
379          ;;
380        (#i)loglevel=*)
381          _values 'log level' QUIET FATAL ERROR INFO VERBOSE\
382              DEBUG DEBUG1 DEBUG2 DEBUG3 && ret=0
383          ;;
384        (#i)macs=*)
385          state=macs
386          ;;
387        (#i)numberofpasswordprompts=*)
388          _message -e 'number of password prompts'
389          ret=0
390          ;;
391        (#i)pkcs11provider=*)
392          _description files expl 'PKCS#11 shared library'
393          _files -g '*.(so|dylib)(|.<->)(-.)' "$expl[@]" && ret=0
394          ;;
395        (#i)port=*)
396          _message -e 'port number on remote host'
397          ret=0
398          ;;
399        (#i)preferredauthentications=*)
400          _values -s , 'authentication method' gssapi-with-mic \
401              hostbased publickey keyboard-interactive password && ret=0
402          ;;
403        (#i)protocol=*)
404          _values -s , 'protocol version' \
405              '1' \
406              '2' && ret=0
407          ;;
408        (#i)(proxy|remote)command=*)
409          _cmdstring && ret=0
410          ;;
411        (#i)rekeylimit=*)
412          _message -e 'maximum number of bytes transmitted before renegotiating session key'
413          ret=0
414          ;;
415        (#i)requesttty=*)
416          _values 'request a pseudo-tty' \
417              'no[never request a TTY]' \
418              'yes[always request a TTY when stdin is a TTY]' \
419              'force[always request a TTY]' \
420              'auto[request a TTY when opening a login session]' && ret=0
421          ;;
422        (#i)revokedhostkeys=*)
423          _description files expl 'revoked host keys file'
424          _files "$expl[@]" && ret=0
425          ;;
426        (#i)sendenv=*)
427          _wanted envs expl 'environment variable' _parameters -g 'scalar*export*' && ret=0
428          ;;
429        (#i)serveralivecountmax=*)
430          _message -e 'number of alive messages without replies before disconnecting'
431          ret=0
432          ;;
433        (#i)serveraliveinterval=*)
434          _message -e 'timeout in seconds since last data was received to send alive message'
435          ret=0
436          ;;
437        (#i)streamlocalbindmask=*)
438          _message -e 'octal mask' && ret=0
439          ;;
440        (#i)stricthostkeychecking=*)
441          _wanted values expl 'value' compadd yes no ask accept-new off && ret=0
442          ;;
443        (#i)syslogfacility=*)
444          _wanted facilities expl 'facility' compadd -M 'm:{a-z}={A-Z}' DAEMON USER AUTH LOCAL{0,1,2,3,4,5,6,7} && ret=0
445          ;;
446        (#i)(verifyhostkeydns|updatehostkeys)=*)
447          _wanted values expl 'truthish value' compadd yes no ask && ret=0
448          ;;
449        (#i)transport=*)
450          _values 'transport protocol' TCP SCTP && ret=0
451          ;;
452        (#i)tunnel=*)
453          _values 'request device forwarding' \
454              'yes' \
455              'point-to-point' \
456              'ethernet' \
457              'no' && ret=0
458          ;;
459        (#i)tunneldevice=*)
460          _message -e 'local_tun[:remote_tun] (integer or "any")'
461          ret=0
462          ;;
463        (#i)userknownhostsfile=*)
464          _description files expl 'user file with known hosts'
465          _files "$expl[@]" && ret=0
466          ;;
467        (#i)user=*)
468          _wanted users expl 'user to log in as' _ssh_users && ret=0
469          ;;
470        (#i)xauthlocation=*)
471          _description files expl 'xauth program'
472          _files "$expl[@]" -g '*(-*)' && ret=0
473          ;;
474        esac
475      else
476        # old options are after the empty "\"-line
477        _wanted values expl 'configure file option' \
478            compadd -M 'm:{a-z}={A-Z}' -q -S '=' - \
479                AddKeysToAgent \
480                AddressFamily \
481                BatchMode \
482                BindAddress \
483                CanonicalDomains \
484                CanonicalizeFallbackLocal \
485                CanonicalizeHostname \
486                CanonicalizeMaxDots \
487                CanonicalizePermittedCNAMEs \
488                CASignatureAlgorithms \
489                CertificateFile \
490                ChallengeResponseAuthentication \
491                CheckHostIP \
492                Ciphers \
493                ClearAllForwardings \
494                Compression \
495                ConnectionAttempts \
496                ConnectTimeout \
497                ControlMaster \
498                ControlPath \
499                ControlPersist \
500                DynamicForward \
501                EnableSSHKeysign \
502                EscapeChar \
503                ExitOnForwardFailure \
504                FingerprintHash \
505                ForwardAgent \
506                ForwardX11 \
507                ForwardX11Timeout \
508                ForwardX11Trusted \
509                GatewayPorts \
510                GlobalKnownHostsFile \
511                GSSAPIAuthentication \
512                GSSAPIClientIdentity \
513                GSSAPIDelegateCredentials \
514                GSSAPIKeyExchange \
515                GSSAPIRenewalForcesRekey \
516                GSSAPIServerIdentity \
517                GSSAPITrustDns \
518                GSSAPIKexAlgorithms \
519                HashKnownHosts \
520                HostbasedAuthentication \
521                HostbasedKeyTypes \
522                HostKeyAlgorithms \
523                HostKeyAlias \
524                HostName \
525                IdentitiesOnly \
526                IdentityAgent \
527                IdentityFile \
528                IgnoreUnknown \
529                IPQoS \
530                KbdInteractiveAuthentication \
531                KbdInteractiveDevices \
532                KexAlgorithms \
533                LocalCommand \
534                LocalForward \
535                LogLevel \
536                MACs \
537                NoHostAuthenticationForLocalhost \
538                NumberOfPasswordPrompts \
539                PasswordAuthentication \
540                PermitLocalCommand \
541                PKCS11Provider \
542                Port \
543                PreferredAuthentications \
544                ProxyCommand \
545                ProxyJump \
546                ProxyUseFdpass \
547                PubkeyAcceptedKeyTypes \
548                PubkeyAuthentication \
549                RekeyLimit \
550                RemoteCommand \
551                RemoteForward \
552                RequestTTY \
553                RevokedHostKeys \
554                RhostsRSAAuthentication \
555                RSAAuthentication \
556                SendEnv \
557                ServerAliveCountMax \
558                ServerAliveInterval \
559                SetEnv \
560                StreamLocalBindMask \
561                StreamLocalBindUnlink \
562                StrictHostKeyChecking \
563                SyslogFacility \
564                TCPKeepAlive \
565                Tunnel \
566                TunnelDevice \
567                UpdateHostKeys \
568                UsePrivilegedPort \
569                User \
570                UserKnownHostsFile \
571                VerifyHostKeyDNS \
572                VisualHostKey \
573                XAuthLocation \
574                \
575                AFSTokenPassing \
576                FallBackToRsh \
577                KeepAlive \
578                KerberosAuthentication \
579                KerberosTgtPassing \
580                PreferredAuthentications \
581                ProtocolKeepAlives \
582                RhostsAuthentication \
583                SetupTimeOut \
584                SmartcardDevice \
585                UseRsh \
586                && ret=0
587      fi
588      ;;
589    forward)
590      local port=false host=false listen=false bind=false
591      if compset -P 1 '*:'; then
592        if [[ $IPREFIX != (*=|)<-65535>: ]]; then
593          if compset -P 1 '*:'; then
594            if compset -P '*:'; then
595              port=true
596            else
597              host=true
598            fi
599          else
600            listen=true
601            ret=0
602          fi
603        else
604          if compset -P '*:'; then
605            port=true
606          else
607            host=true
608          fi
609        fi
610      else
611        listen=true
612        bind=true
613      fi
614      $port && { _message -e port-numbers 'port number'; ret=0 }
615      $listen && { _message -e port-numbers 'listen-port number'; ret=0 }
616      $host && { _wanted hosts expl host _ssh_hosts -S: && ret=0 }
617      $bind && { _wanted bind-addresses expl bind-address _bind_addresses -S: && ret=0 }
618      return ret
619      ;;
620    dynforward)
621      _message -e port-numbers 'listen-port number'
622      if ! compset -P '*:'; then
623        _wanted bind-addresses expl bind-address _bind_addresses -qS:
624      fi
625      return 0
626      ;;
627    hostport)
628      if compset -P '*:'; then
629        _message -e port-numbers 'port number'
630        ret=0
631      else
632        _wanted hosts expl host _ssh_hosts -S: && ret=0
633      fi
634      return ret
635      ;;
636    macs)
637      _wanted macs expl 'MAC algorithm' _sequence compadd - $(_call_program macs ssh -Q mac)
638      return
639      ;;
640    ciphers)
641      _wanted ciphers expl 'encryption cipher' _sequence compadd - $(_call_program ciphers ssh -Q cipher)
642      return
643      ;;
644    command)
645      if (( $+opt_args[-s] )); then
646	_wanted subsystems expl subsystem compadd sftp
647	return
648      fi
649      local -a _comp_priv_prefix
650      shift 1 words
651      (( CURRENT-- ))
652      _normal
653      return
654      ;;
655    userhost)
656      if compset -P '*@'; then
657        _wanted hosts expl 'remote host name' _ssh_hosts && ret=0
658      elif compset -S '@*'; then
659        _wanted users expl 'login name' _ssh_users -S '' && ret=0
660      else
661        if (( $+opt_args[-l] )); then
662          tmp=()
663        else
664          tmp=( 'users:login name:_ssh_users -qS@' )
665        fi
666        _alternative \
667            'hosts:remote host name:_ssh_hosts' \
668            "$tmp[@]" && ret=0
669      fi
670      ;;
671    file)
672      if compset -P 1 '[^./][^/]#:'; then
673        _remote_files -- ssh ${(kv)~opt_args[(I)-[FP1246]]/-P/-p} && ret=0
674      elif compset -P 1 '*@'; then
675        suf=( -S '' )
676        compset -S ':*' || suf=( -r: -S: )
677        _wanted hosts expl 'remote host name' _ssh_hosts $suf && ret=0
678      else
679        _alternative \
680            'files:: _files' \
681            'hosts:remote host name:_ssh_hosts -r: -S:' \
682            'users:user:_ssh_users -qS@' && ret=0
683      fi
684      ;;
685    rfile)
686      if compset -P 1 '*:'; then
687        _remote_files -- ssh && ret=0
688      elif compset -P 1 '*@'; then
689        _wanted hosts expl host _ssh_hosts -r: -S: && ret=0
690      else
691        _alternative \
692            'hosts:remote host name:_ssh_hosts -r: -S:' \
693            'users:user:_ssh_users -qS@' && ret=0
694      fi
695      ;;
696    esac
697  done
698
699  return ret
700}
701
702_ssh_users () {
703  _combination -s '[:@]' my-accounts users-hosts users "$@"
704}
705
706_ssh "$@"
707