Browse Source

can now tail multiple nginx logs in parallel

Tobias von Dewitz 3 years ago
parent
commit
cf55772092
100 changed files with 6518 additions and 502 deletions
  1. 16 0
      Dockerfile
  2. 1 3
      main.go
  3. 1 1
      vendor/github.com/google/gopacket/pcap/pcap_unix.go
  4. 3 0
      vendor/github.com/nats-io/nats.go/.gitignore
  5. 19 0
      vendor/github.com/nats-io/nats.go/.travis.yml
  6. 3 0
      vendor/github.com/nats-io/nats.go/CODE-OF-CONDUCT.md
  7. 0 0
      vendor/github.com/nats-io/nats.go/GOVERNANCE.md
  8. 201 0
      vendor/github.com/nats-io/nats.go/LICENSE
  9. 2 4
      vendor/github.com/nats-io/nats.go/MAINTAINERS.md
  10. 142 17
      vendor/github.com/nats-io/nats.go/README.md
  11. 0 0
      vendor/github.com/nats-io/nats.go/TODO.md
  12. 53 51
      vendor/github.com/nats-io/nats.go/context.go
  13. 13 0
      vendor/github.com/nats-io/nats.go/dependencies.md
  14. 8 8
      vendor/github.com/nats-io/nats.go/enc.go
  15. 117 0
      vendor/github.com/nats-io/nats.go/encoders/builtin/default_enc.go
  16. 45 0
      vendor/github.com/nats-io/nats.go/encoders/builtin/gob_enc.go
  17. 56 0
      vendor/github.com/nats-io/nats.go/encoders/builtin/json_enc.go
  18. 8 0
      vendor/github.com/nats-io/nats.go/go.mod
  19. 11 0
      vendor/github.com/nats-io/nats.go/go.sum
  20. 11 0
      vendor/github.com/nats-io/nats.go/go_test.mod
  21. 99 0
      vendor/github.com/nats-io/nats.go/go_test.sum
  22. 2345 0
      vendor/github.com/nats-io/nats.go/js.go
  23. 1077 0
      vendor/github.com/nats-io/nats.go/jsm.go
  24. 576 131
      vendor/github.com/nats-io/nats.go/nats.go
  25. 1 1
      vendor/github.com/nats-io/nats.go/netchan.go
  26. 75 4
      vendor/github.com/nats-io/nats.go/parser.go
  27. 0 0
      vendor/github.com/nats-io/nats.go/timer.go
  28. 27 0
      vendor/github.com/nats-io/nats.go/util/tls.go
  29. 49 0
      vendor/github.com/nats-io/nats.go/util/tls_go17.go
  30. 700 0
      vendor/github.com/nats-io/nats.go/ws.go
  31. 0 21
      vendor/github.com/nats-io/nats/.travis.yml
  32. 0 4
      vendor/github.com/nats-io/nats/staticcheck.ignore
  33. 9 6
      vendor/github.com/nats-io/nkeys/.travis.yml
  34. 4 2
      vendor/github.com/nats-io/nkeys/MAINTAINERS.md
  35. 2 5
      vendor/github.com/nats-io/nkeys/README.md
  36. 78 0
      vendor/github.com/nats-io/nkeys/creds_utils.go
  37. 3 1
      vendor/github.com/nats-io/nkeys/go.mod
  38. 7 2
      vendor/github.com/nats-io/nkeys/go.sum
  39. 5 4
      vendor/github.com/nats-io/nkeys/main.go
  40. 21 5
      vendor/github.com/nats-io/nkeys/strkey.go
  41. 6 0
      vendor/golang.org/x/crypto/ed25519/ed25519.go
  42. 74 0
      vendor/golang.org/x/crypto/ed25519/ed25519_go113.go
  43. 30 0
      vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go
  44. 13 2
      vendor/golang.org/x/sys/unix/README.md
  45. 1 1
      vendor/golang.org/x/sys/unix/asm_aix_ppc64.s
  46. 1 1
      vendor/golang.org/x/sys/unix/asm_darwin_386.s
  47. 1 1
      vendor/golang.org/x/sys/unix/asm_darwin_amd64.s
  48. 1 1
      vendor/golang.org/x/sys/unix/asm_darwin_arm.s
  49. 1 1
      vendor/golang.org/x/sys/unix/asm_darwin_arm64.s
  50. 1 1
      vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s
  51. 1 1
      vendor/golang.org/x/sys/unix/asm_freebsd_386.s
  52. 1 1
      vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
  53. 1 1
      vendor/golang.org/x/sys/unix/asm_freebsd_arm.s
  54. 1 1
      vendor/golang.org/x/sys/unix/asm_freebsd_arm64.s
  55. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_386.s
  56. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_amd64.s
  57. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_arm.s
  58. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_arm64.s
  59. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
  60. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_mipsx.s
  61. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
  62. 1 8
      vendor/golang.org/x/sys/unix/asm_linux_riscv64.s
  63. 1 1
      vendor/golang.org/x/sys/unix/asm_linux_s390x.s
  64. 1 1
      vendor/golang.org/x/sys/unix/asm_netbsd_386.s
  65. 1 1
      vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s
  66. 1 1
      vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
  67. 1 1
      vendor/golang.org/x/sys/unix/asm_netbsd_arm64.s
  68. 1 1
      vendor/golang.org/x/sys/unix/asm_openbsd_386.s
  69. 1 1
      vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s
  70. 1 1
      vendor/golang.org/x/sys/unix/asm_openbsd_arm.s
  71. 1 1
      vendor/golang.org/x/sys/unix/asm_openbsd_arm64.s
  72. 29 0
      vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s
  73. 1 1
      vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
  74. 1 0
      vendor/golang.org/x/sys/unix/bluetooth_linux.go
  75. 1 1
      vendor/golang.org/x/sys/unix/endian_big.go
  76. 1 1
      vendor/golang.org/x/sys/unix/endian_little.go
  77. 6 0
      vendor/golang.org/x/sys/unix/errors_freebsd_386.go
  78. 6 0
      vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go
  79. 17 0
      vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go
  80. 8 4
      vendor/golang.org/x/sys/unix/fcntl.go
  81. 6 0
      vendor/golang.org/x/sys/unix/fcntl_darwin.go
  82. 2 2
      vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go
  83. 29 0
      vendor/golang.org/x/sys/unix/fdset.go
  84. 0 2
      vendor/golang.org/x/sys/unix/gccgo.go
  85. 6 0
      vendor/golang.org/x/sys/unix/gccgo_c.c
  86. 9 0
      vendor/golang.org/x/sys/unix/ioctl.go
  87. 24 8
      vendor/golang.org/x/sys/unix/mkall.sh
  88. 44 5
      vendor/golang.org/x/sys/unix/mkerrors.sh
  89. 16 0
      vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go
  90. 1 1
      vendor/golang.org/x/sys/unix/sockcmsg_linux.go
  91. 4 32
      vendor/golang.org/x/sys/unix/sockcmsg_unix.go
  92. 42 0
      vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go
  93. 42 1
      vendor/golang.org/x/sys/unix/syscall.go
  94. 16 0
      vendor/golang.org/x/sys/unix/syscall_aix.go
  95. 52 5
      vendor/golang.org/x/sys/unix/syscall_bsd.go
  96. 31 0
      vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go
  97. 108 0
      vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go
  98. 74 89
      vendor/golang.org/x/sys/unix/syscall_darwin.go
  99. 2 22
      vendor/golang.org/x/sys/unix/syscall_darwin_386.go
  100. 2 22
      vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go

+ 16 - 0
Dockerfile

@@ -0,0 +1,16 @@
+FROM golang:alpine
+
+COPY . /src
+
+WORKDIR /src
+
+RUN apk add build-base libpcap-dev
+RUN make compile
+
+FROM alpine:latest
+
+RUN apk update && apk add libpcap
+COPY --from=0 /src/munchclient /usr/bin/
+
+CMD /usr/bin/munchclient -config /etc/munchclient/munchclient.toml
+

+ 1 - 3
main.go

@@ -147,7 +147,7 @@ func (c Config) print() {
 	fmt.Printf("Nginx Log Format:      %s\n", c.NginxLogFormat)
 	fmt.Printf("Nginx Log Files:\n")
 	for _, logfile := range c.NginxLogFiles {
-		fmt.Printf("                       %s (%s)\n", logfile.File, logfile.Host)
+		fmt.Printf("                       %s (%s) (%s)\n", logfile.File, logfile.Host, logfile.Format)
 	}
 	fmt.Printf("NginxReplay:           %s\n", c.NginxReplay)
 	fmt.Printf("HostName:              %s\n", c.HostName)
@@ -811,8 +811,6 @@ func loadConfig() {
 	if !config.Quiet {
 		config.print()
 	}
-
-	os.Exit(0)
 }
 
 // version outputs build information...

+ 1 - 1
vendor/github.com/google/gopacket/pcap/pcap_unix.go

@@ -24,7 +24,7 @@ import (
 
 /*
 #cgo solaris LDFLAGS: -L /opt/local/lib -lpcap
-#cgo linux LDFLAGS: -Wl,-Bstatic -lpcap -Wl,-Bdynamic
+#cgo linux LDFLAGS: -lpcap
 #cgo dragonfly LDFLAGS: -lpcap
 #cgo freebsd LDFLAGS: -lpcap
 #cgo openbsd LDFLAGS: -lpcap

+ 3 - 0
vendor/github.com/nats-io/nats/.gitignore → vendor/github.com/nats-io/nats.go/.gitignore

@@ -37,3 +37,6 @@ _testmain.go
 .settings/
 
 # bin
+
+# Goland
+.idea

+ 19 - 0
vendor/github.com/nats-io/nats.go/.travis.yml

@@ -0,0 +1,19 @@
+language: go
+go:
+- 1.16.x
+- 1.15.x
+go_import_path: github.com/nats-io/nats.go
+install:
+- go get -t ./...
+- go get github.com/mattn/goveralls
+- go get github.com/wadey/gocovmerge
+- go get -u honnef.co/go/tools/cmd/staticcheck
+- go get -u github.com/client9/misspell/cmd/misspell
+before_script:
+- $(exit $(go fmt ./... | wc -l))
+- go vet -modfile=go_test.mod ./...
+- find . -type f -name "*.go" | xargs misspell -error -locale US
+- staticcheck ./...
+script:
+- go test -modfile=go_test.mod -v -run=TestNoRace -p=1 ./... --failfast
+- if [[ "$TRAVIS_GO_VERSION" =~ 1.16 ]]; then ./scripts/cov.sh TRAVIS; else go test -modfile=go_test.mod -race -v -p=1 ./... --failfast; fi

+ 3 - 0
vendor/github.com/nats-io/nats.go/CODE-OF-CONDUCT.md

@@ -0,0 +1,3 @@
+## Community Code of Conduct
+
+NATS follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).

+ 0 - 0
vendor/github.com/nats-io/nats/GOVERNANCE.md → vendor/github.com/nats-io/nats.go/GOVERNANCE.md


+ 201 - 0
vendor/github.com/nats-io/nats.go/LICENSE

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 2 - 4
vendor/github.com/nats-io/nats/MAINTAINERS.md → vendor/github.com/nats-io/nats.go/MAINTAINERS.md

@@ -2,9 +2,7 @@
 
 Maintainership is on a per project basis.
 
-### Core-maintainers
+### Maintainers
   - Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)
   - Ivan Kozlovic <ivan@nats.io> [@kozlovic](https://github.com/kozlovic)
-  
-### Maintainers
-  - Waldemar Quevedo <wally@nats.io> [@wallyqs](https://github.com/wallyqs)
+  - Waldemar Quevedo <wally@nats.io> [@wallyqs](https://github.com/wallyqs)

+ 142 - 17
vendor/github.com/nats-io/nats/README.md → vendor/github.com/nats-io/nats.go/README.md

@@ -3,22 +3,37 @@ A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io
 
 [![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
 [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats?ref=badge_shield)
-[![Go Report Card](https://goreportcard.com/badge/github.com/nats-io/go-nats)](https://goreportcard.com/report/github.com/nats-io/go-nats) [![Build Status](https://travis-ci.org/nats-io/go-nats.svg?branch=master)](http://travis-ci.org/nats-io/go-nats) [![GoDoc](https://godoc.org/github.com/nats-io/go-nats?status.svg)](http://godoc.org/github.com/nats-io/go-nats) [![Coverage Status](https://coveralls.io/repos/nats-io/go-nats/badge.svg?branch=master)](https://coveralls.io/r/nats-io/go-nats?branch=master)
+[![Go Report Card](https://goreportcard.com/badge/github.com/nats-io/nats.go)](https://goreportcard.com/report/github.com/nats-io/nats.go) [![Build Status](https://travis-ci.com/nats-io/nats.go.svg?branch=master)](http://travis-ci.com/nats-io/nats.go) [![GoDoc](https://img.shields.io/badge/GoDoc-reference-007d9c)](https://pkg.go.dev/github.com/nats-io/nats.go)
+ [![Coverage Status](https://coveralls.io/repos/nats-io/nats.go/badge.svg?branch=master)](https://coveralls.io/r/nats-io/nats.go?branch=master)
 
 ## Installation
 
 ```bash
 # Go client
-go get github.com/nats-io/go-nats
+go get github.com/nats-io/nats.go/
 
 # Server
-go get github.com/nats-io/gnatsd
+go get github.com/nats-io/nats-server
+```
+
+When using or transitioning to Go modules support:
+
+```bash
+# Go client latest or explicit version
+go get github.com/nats-io/nats.go/@latest
+go get github.com/nats-io/nats.go/@v1.11.0
+
+# For latest NATS Server, add /v2 at the end
+go get github.com/nats-io/nats-server/v2
+
+# NATS Server v1 is installed otherwise
+# go get github.com/nats-io/nats-server
 ```
 
 ## Basic Usage
 
 ```go
-import nats "github.com/nats-io/go-nats"
+import "github.com/nats-io/nats.go"
 
 // Connect to a server
 nc, _ := nats.Connect(nats.DefaultURL)
@@ -31,6 +46,11 @@ nc.Subscribe("foo", func(m *nats.Msg) {
     fmt.Printf("Received a message: %s\n", string(m.Data))
 })
 
+// Responding to a request message
+nc.Subscribe("request", func(m *nats.Msg) {
+    m.Respond([]byte("answer is 42"))
+})
+
 // Simple Sync Subscriber
 sub, err := nc.SubscribeSync("foo")
 m, err := sub.NextMsg(timeout)
@@ -50,7 +70,7 @@ sub.Drain()
 msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond)
 
 // Replies
-nc.Subscribe("help", func(m *Msg) {
+nc.Subscribe("help", func(m *nats.Msg) {
     nc.Publish(m.Reply, []byte("I can help!"))
 })
 
@@ -62,6 +82,85 @@ nc.Drain()
 nc.Close()
 ```
 
+## JetStream Basic Usage
+
+```go
+import "github.com/nats-io/nats.go"
+
+// Connect to NATS
+nc, _ := nats.Connect(nats.DefaultURL)
+
+// Create JetStream Context
+js, _ := nc.JetStream(nats.PublishAsyncMaxPending(256))
+
+// Simple Stream Publisher
+js.Publish("ORDERS.scratch", []byte("hello"))
+
+// Simple Async Stream Publisher
+for i := 0; i < 500; i++ {
+	js.PublishAsync("ORDERS.scratch", []byte("hello"))
+}
+select {
+case <-js.PublishAsyncComplete():
+case <-time.After(5 * time.Second):
+	fmt.Println("Did not resolve in time")
+}
+
+// Simple Async Ephemeral Consumer
+js.Subscribe("ORDERS.*", func(m *nats.Msg) {
+	fmt.Printf("Received a JetStream message: %s\n", string(m.Data))
+})
+
+// Simple Sync Durable Consumer (optional SubOpts at the end)
+sub, err := js.SubscribeSync("ORDERS.*", nats.Durable("MONITOR"), nats.MaxDeliver(3))
+m, err := sub.NextMsg(timeout)
+
+// Simple Pull Consumer
+sub, err := js.PullSubscribe("ORDERS.*", "MONITOR")
+msgs, err := sub.Fetch(10)
+
+// Unsubscribe
+sub.Unsubscribe()
+
+// Drain
+sub.Drain()
+```
+
+## JetStream Basic Management
+
+```go
+import "github.com/nats-io/nats.go"
+
+// Connect to NATS
+nc, _ := nats.Connect(nats.DefaultURL)
+
+// Create JetStream Context
+js, _ := nc.JetStream()
+
+// Create a Stream
+js.AddStream(&nats.StreamConfig{
+	Name:     "ORDERS",
+	Subjects: []string{"ORDERS.*"},
+})
+
+// Update a Stream
+js.UpdateStream(&nats.StreamConfig{
+	Name:     "ORDERS",
+	MaxBytes: 8,
+})
+
+// Create a Consumer
+js.AddConsumer("ORDERS", &nats.ConsumerConfig{
+	Durable: "MONITOR",
+})
+
+// Delete Consumer
+js.DeleteConsumer("ORDERS", "MONITOR")
+
+// Delete Stream
+js.DeleteStream("ORDERS")
+```
+
 ## Encoded Connections
 
 ```go
@@ -97,12 +196,12 @@ c.Publish("hello", me)
 
 // Unsubscribe
 sub, err := c.Subscribe("foo", nil)
-...
+// ...
 sub.Unsubscribe()
 
 // Requests
 var response string
-err := c.Request("help", "help me", &response, 10*time.Millisecond)
+err = c.Request("help", "help me", &response, 10*time.Millisecond)
 if err != nil {
     fmt.Printf("Request failed: %v\n", err)
 }
@@ -122,21 +221,21 @@ This requires server with version >= 2.0.0
 NATS servers have a new security and authentication mechanism to authenticate with user credentials and Nkeys.
 The simplest form is to use the helper method UserCredentials(credsFilepath).
 ```go
-nc, err := nats.Connect(url, UserCredentials("user.creds"))
+nc, err := nats.Connect(url, nats.UserCredentials("user.creds"))
 ```
 
-The helper methos creates two callback handlers to present the user JWT and sign the nonce challenge from the server.
+The helper methods creates two callback handlers to present the user JWT and sign the nonce challenge from the server.
 The core client library never has direct access to your private key and simply performs the callback for signing the server challenge.
 The helper will load and wipe and erase memory it uses for each connect or reconnect.
 
 The helper also can take two entries, one for the JWT and one for the NKey seed file.
 ```go
-nc, err := nats.Connect(url, UserCredentials("user.jwt", "user.nk"))
+nc, err := nats.Connect(url, nats.UserCredentials("user.jwt", "user.nk"))
 ```
 
 You can also set the callback handlers directly and manage challenge signing directly.
 ```go
-nc, err := nats.Connect(url, UserJWT(jwtCB, sigCB))
+nc, err := nats.Connect(url, nats.UserJWT(jwtCB, sigCB))
 ```
 
 Bare Nkeys are also supported. The nkey seed should be in a read only file, e.g. seed.txt
@@ -155,7 +254,7 @@ opt, err := nats.NkeyOptionFromSeed("seed.txt")
 nc, err := nats.Connect(serverUrl, opt)
 
 // Direct
-nc, err := nats.Connect(serverUrl, Nkey(pubNkey, sigCB))
+nc, err := nats.Connect(serverUrl, nats.Nkey(pubNkey, sigCB))
 ```
 
 ## TLS
@@ -258,13 +357,27 @@ nc.Publish("foo.bar.baz", []byte("Hello World"))
 nc.QueueSubscribe("foo", "job_workers", func(_ *Msg) {
   received += 1;
 })
-
 ```
 
 ## Advanced Usage
 
 ```go
 
+// Normally, the library will return an error when trying to connect and
+// there is no server running. The RetryOnFailedConnect option will set
+// the connection in reconnecting state if it failed to connect right away.
+nc, err := nats.Connect(nats.DefaultURL,
+    nats.RetryOnFailedConnect(true),
+    nats.MaxReconnects(10),
+    nats.ReconnectWait(time.Second),
+    nats.ReconnectHandler(func(_ *nats.Conn) {
+        // Note that this will be invoked for the first asynchronous connect.
+    }))
+if err != nil {
+    // Should not return an error even if it can't connect, but you still
+    // need to check in case there are some configuration errors.
+}
+
 // Flush connection to server, returns when all messages have been processed.
 nc.Flush()
 fmt.Println("All clear!")
@@ -306,13 +419,25 @@ nc, err := nats.Connect(servers)
 // This example means 10 seconds total per backend.
 nc, err = nats.Connect(servers, nats.MaxReconnects(5), nats.ReconnectWait(2 * time.Second))
 
+// You can also add some jitter for the reconnection.
+// This call will add up to 500 milliseconds for non TLS connections and 2 seconds for TLS connections.
+// If not specified, the library defaults to 100 milliseconds and 1 second, respectively.
+nc, err = nats.Connect(servers, nats.ReconnectJitter(500*time.Millisecond, 2*time.Second))
+
+// You can also specify a custom reconnect delay handler. If set, the library will invoke it when it has tried
+// all URLs in its list. The value returned will be used as the total sleep time, so add your own jitter.
+// The library will pass the number of times it went through the whole list.
+nc, err = nats.Connect(servers, nats.CustomReconnectDelay(func(attempts int) time.Duration {
+    return someBackoffFunction(attempts)
+}))
+
 // Optionally disable randomization of the server pool
 nc, err = nats.Connect(servers, nats.DontRandomize())
 
 // Setup callbacks to be notified on disconnects, reconnects and connection closed.
 nc, err = nats.Connect(servers,
-	nats.DisconnectHandler(func(nc *nats.Conn) {
-		fmt.Printf("Got disconnected!\n")
+	nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
+		fmt.Printf("Got disconnected! Reason: %q\n", err)
 	}),
 	nats.ReconnectHandler(func(nc *nats.Conn) {
 		fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl())
@@ -339,9 +464,9 @@ nc, err = nats.Connect("nats://localhost:4222",
     nats.Token("S3cretT0ken"))
 
 // Note that if credentials are specified in the initial URLs, they take
-// precedence on the credentials specfied through the options.
+// precedence on the credentials specified through the options.
 // For instance, in the connect call below, the client library will use
-// the user "my" and password "pwd" to connect to locahost:4222, however,
+// the user "my" and password "pwd" to connect to localhost:4222, however,
 // it will use username "foo" and password "bar" when (re)connecting to
 // a different server URL that it got as part of the auto-discovery.
 nc, err = nats.Connect("nats://my:pwd@localhost:4222", nats.UserInfo("foo", "bar"))

+ 0 - 0
vendor/github.com/nats-io/nats/TODO.md → vendor/github.com/nats-io/nats.go/TODO.md


+ 53 - 51
vendor/github.com/nats-io/nats/context.go → vendor/github.com/nats-io/nats.go/context.go

@@ -11,9 +11,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// +build go1.7
-
-// A Go client for the NATS messaging system (https://nats.io).
 package nats
 
 import (
@@ -21,9 +18,33 @@ import (
 	"reflect"
 )
 
+// RequestMsgWithContext takes a context, a subject and payload
+// in bytes and request expecting a single response.
+func (nc *Conn) RequestMsgWithContext(ctx context.Context, msg *Msg) (*Msg, error) {
+	var hdr []byte
+	var err error
+
+	if len(msg.Header) > 0 {
+		if !nc.info.Headers {
+			return nil, ErrHeadersNotSupported
+		}
+
+		hdr, err = msg.headerBytes()
+		if err != nil {
+			return nil, err
+		}
+	}
+
+	return nc.requestWithContext(ctx, msg.Subject, hdr, msg.Data)
+}
+
 // RequestWithContext takes a context, a subject and payload
 // in bytes and request expecting a single response.
 func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
+	return nc.requestWithContext(ctx, subj, nil, data)
+}
+
+func (nc *Conn) requestWithContext(ctx context.Context, subj string, hdr, data []byte) (*Msg, error) {
 	if ctx == nil {
 		return nil, ErrInvalidContext
 	}
@@ -36,71 +57,52 @@ func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte
 		return nil, ctx.Err()
 	}
 
-	nc.mu.Lock()
-	// If user wants the old style.
-	if nc.Opts.UseOldRequestStyle {
-		nc.mu.Unlock()
-		return nc.oldRequestWithContext(ctx, subj, data)
-	}
-
-	// Do setup for the new style.
-	if nc.respMap == nil {
-		nc.initNewResp()
-	}
-	// Create literal Inbox and map to a chan msg.
-	mch := make(chan *Msg, RequestChanLen)
-	respInbox := nc.newRespInbox()
-	token := respToken(respInbox)
-	nc.respMap[token] = mch
-	createSub := nc.respMux == nil
-	ginbox := nc.respSub
-	nc.mu.Unlock()
+	var m *Msg
+	var err error
 
-	if createSub {
-		// Make sure scoped subscription is setup only once.
-		var err error
-		nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
+	// If user wants the old style.
+	if nc.useOldRequestStyle() {
+		m, err = nc.oldRequestWithContext(ctx, subj, hdr, data)
+	} else {
+		mch, token, err := nc.createNewRequestAndSend(subj, hdr, data)
 		if err != nil {
 			return nil, err
 		}
-	}
 
-	err := nc.PublishRequest(subj, respInbox, data)
-	if err != nil {
-		return nil, err
-	}
-
-	var ok bool
-	var msg *Msg
-
-	select {
-	case msg, ok = <-mch:
-		if !ok {
-			return nil, ErrConnectionClosed
+		var ok bool
+
+		select {
+		case m, ok = <-mch:
+			if !ok {
+				return nil, ErrConnectionClosed
+			}
+		case <-ctx.Done():
+			nc.mu.Lock()
+			delete(nc.respMap, token)
+			nc.mu.Unlock()
+			return nil, ctx.Err()
 		}
-	case <-ctx.Done():
-		nc.mu.Lock()
-		delete(nc.respMap, token)
-		nc.mu.Unlock()
-		return nil, ctx.Err()
 	}
-
-	return msg, nil
+	// Check for no responder status.
+	if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
+		m, err = nil, ErrNoResponders
+	}
+	return m, err
 }
 
 // oldRequestWithContext utilizes inbox and subscription per request.
-func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
+func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, hdr, data []byte) (*Msg, error) {
 	inbox := NewInbox()
 	ch := make(chan *Msg, RequestChanLen)
 
-	s, err := nc.subscribe(inbox, _EMPTY_, nil, ch)
+	s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true, nil)
 	if err != nil {
 		return nil, err
 	}
 	s.AutoUnsubscribe(1)
 	defer s.Unsubscribe()
 
-	err = nc.PublishRequest(subj, inbox, data)
+	err = nc.publish(subj, inbox, hdr, data)
 	if err != nil {
 		return nil, err
 	}
@@ -140,7 +142,7 @@ func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
 	select {
 	case msg, ok = <-mch:
 		if !ok {
-			return nil, ErrConnectionClosed
+			return nil, s.getNextMsgErr()
 		}
 		if err := s.processNextMsgDelivered(msg); err != nil {
 			return nil, err
@@ -153,7 +155,7 @@ func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
 	select {
 	case msg, ok = <-mch:
 		if !ok {
-			return nil, ErrConnectionClosed
+			return nil, s.getNextMsgErr()
 		}
 		if err := s.processNextMsgDelivered(msg); err != nil {
 			return nil, err

+ 13 - 0
vendor/github.com/nats-io/nats.go/dependencies.md

@@ -0,0 +1,13 @@
+# External Dependencies
+
+This file lists the dependencies used in this repository.
+
+| Dependency | License |
+|-|-|
+| Go | BSD 3-Clause "New" or "Revised" License |
+| github.com/nats-io/nats.go | Apache License 2.0 |
+| github.com/golang/protobuf v1.4.2 | BSD 3-Clause "New" or "Revised" License |
+| github.com/nats-io/nats-server/v2 v2.1.8-0.20201115145023-f61fa8529a0f | Apache License 2.0 |
+| github.com/nats-io/nkeys v0.2.0 | Apache License 2.0 |
+| github.com/nats-io/nuid v1.0.1 | Apache License 2.0 |
+| google.golang.org/protobuf v1.23.0 | BSD 3-Clause License |

+ 8 - 8
vendor/github.com/nats-io/nats/enc.go → vendor/github.com/nats-io/nats.go/enc.go

@@ -1,4 +1,4 @@
-// Copyright 2012-2018 The NATS Authors
+// Copyright 2012-2019 The NATS Authors
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
@@ -21,7 +21,7 @@ import (
 	"time"
 
 	// Default Encoders
-	"github.com/nats-io/go-nats/encoders/builtin"
+	"github.com/nats-io/nats.go/encoders/builtin"
 )
 
 // Encoder interface is for all register encoders
@@ -33,7 +33,7 @@ type Encoder interface {
 var encMap map[string]Encoder
 var encLock sync.Mutex
 
-// Indexe names into the Registered Encoders.
+// Indexed names into the Registered Encoders.
 const (
 	JSON_ENCODER    = "json"
 	GOB_ENCODER     = "gob"
@@ -93,7 +93,7 @@ func (c *EncodedConn) Publish(subject string, v interface{}) error {
 	if err != nil {
 		return err
 	}
-	return c.Conn.publish(subject, _EMPTY_, b)
+	return c.Conn.publish(subject, _EMPTY_, nil, b)
 }
 
 // PublishRequest will perform a Publish() expecting a response on the
@@ -104,12 +104,12 @@ func (c *EncodedConn) PublishRequest(subject, reply string, v interface{}) error
 	if err != nil {
 		return err
 	}
-	return c.Conn.publish(subject, reply, b)
+	return c.Conn.publish(subject, reply, nil, b)
 }
 
 // Request will create an Inbox and perform a Request() call
 // with the Inbox reply for the data v. A response will be
-// decoded into the vPtrResponse.
+// decoded into the vPtr Response.
 func (c *EncodedConn) Request(subject string, v interface{}, vPtr interface{}, timeout time.Duration) error {
 	b, err := c.Enc.Encode(subject, v)
 	if err != nil {
@@ -130,7 +130,7 @@ func (c *EncodedConn) Request(subject string, v interface{}, vPtr interface{}, t
 
 // Handler is a specific callback used for Subscribe. It is generalized to
 // an interface{}, but we will discover its format and arguments at runtime
-// and perform the correct callback, including de-marshaling JSON strings
+// and perform the correct callback, including de-marshaling encoded data
 // back into the appropriate struct based on the signature of the Handler.
 //
 // Handlers are expected to have one of four signatures.
@@ -234,7 +234,7 @@ func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscriptio
 		cbValue.Call(oV)
 	}
 
-	return c.Conn.subscribe(subject, queue, natsCB, nil)
+	return c.Conn.subscribe(subject, queue, natsCB, nil, false, nil)
 }
 
 // FlushTimeout allows a Flush operation to have an associated timeout.

+ 117 - 0
vendor/github.com/nats-io/nats.go/encoders/builtin/default_enc.go

@@ -0,0 +1,117 @@
+// Copyright 2012-2018 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package builtin
+
+import (
+	"bytes"
+	"fmt"
+	"reflect"
+	"strconv"
+	"unsafe"
+)
+
+// DefaultEncoder implementation for EncodedConn.
+// This encoder will leave []byte and string untouched, but will attempt to
+// turn numbers into appropriate strings that can be decoded. It will also
+// propely encoded and decode bools. If will encode a struct, but if you want
+// to properly handle structures you should use JsonEncoder.
+type DefaultEncoder struct {
+	// Empty
+}
+
+var trueB = []byte("true")
+var falseB = []byte("false")
+var nilB = []byte("")
+
+// Encode
+func (je *DefaultEncoder) Encode(subject string, v interface{}) ([]byte, error) {
+	switch arg := v.(type) {
+	case string:
+		bytes := *(*[]byte)(unsafe.Pointer(&arg))
+		return bytes, nil
+	case []byte:
+		return arg, nil
+	case bool:
+		if arg {
+			return trueB, nil
+		} else {
+			return falseB, nil
+		}
+	case nil:
+		return nilB, nil
+	default:
+		var buf bytes.Buffer
+		fmt.Fprintf(&buf, "%+v", arg)
+		return buf.Bytes(), nil
+	}
+}
+
+// Decode
+func (je *DefaultEncoder) Decode(subject string, data []byte, vPtr interface{}) error {
+	// Figure out what it's pointing to...
+	sData := *(*string)(unsafe.Pointer(&data))
+	switch arg := vPtr.(type) {
+	case *string:
+		*arg = sData
+		return nil
+	case *[]byte:
+		*arg = data
+		return nil
+	case *int:
+		n, err := strconv.ParseInt(sData, 10, 64)
+		if err != nil {
+			return err
+		}
+		*arg = int(n)
+		return nil
+	case *int32:
+		n, err := strconv.ParseInt(sData, 10, 64)
+		if err != nil {
+			return err
+		}
+		*arg = int32(n)
+		return nil
+	case *int64:
+		n, err := strconv.ParseInt(sData, 10, 64)
+		if err != nil {
+			return err
+		}
+		*arg = int64(n)
+		return nil
+	case *float32:
+		n, err := strconv.ParseFloat(sData, 32)
+		if err != nil {
+			return err
+		}
+		*arg = float32(n)
+		return nil
+	case *float64:
+		n, err := strconv.ParseFloat(sData, 64)
+		if err != nil {
+			return err
+		}
+		*arg = float64(n)
+		return nil
+	case *bool:
+		b, err := strconv.ParseBool(sData)
+		if err != nil {
+			return err
+		}
+		*arg = b
+		return nil
+	default:
+		vt := reflect.TypeOf(arg).Elem()
+		return fmt.Errorf("nats: Default Encoder can't decode to type %s", vt)
+	}
+}

+ 45 - 0
vendor/github.com/nats-io/nats.go/encoders/builtin/gob_enc.go

@@ -0,0 +1,45 @@
+// Copyright 2013-2018 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package builtin
+
+import (
+	"bytes"
+	"encoding/gob"
+)
+
+// GobEncoder is a Go specific GOB Encoder implementation for EncodedConn.
+// This encoder will use the builtin encoding/gob to Marshal
+// and Unmarshal most types, including structs.
+type GobEncoder struct {
+	// Empty
+}
+
+// FIXME(dlc) - This could probably be more efficient.
+
+// Encode
+func (ge *GobEncoder) Encode(subject string, v interface{}) ([]byte, error) {
+	b := new(bytes.Buffer)
+	enc := gob.NewEncoder(b)
+	if err := enc.Encode(v); err != nil {
+		return nil, err
+	}
+	return b.Bytes(), nil
+}
+
+// Decode
+func (ge *GobEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error) {
+	dec := gob.NewDecoder(bytes.NewBuffer(data))
+	err = dec.Decode(vPtr)
+	return
+}

+ 56 - 0
vendor/github.com/nats-io/nats.go/encoders/builtin/json_enc.go

@@ -0,0 +1,56 @@
+// Copyright 2012-2018 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package builtin
+
+import (
+	"encoding/json"
+	"strings"
+)
+
+// JsonEncoder is a JSON Encoder implementation for EncodedConn.
+// This encoder will use the builtin encoding/json to Marshal
+// and Unmarshal most types, including structs.
+type JsonEncoder struct {
+	// Empty
+}
+
+// Encode
+func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error) {
+	b, err := json.Marshal(v)
+	if err != nil {
+		return nil, err
+	}
+	return b, nil
+}
+
+// Decode
+func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error) {
+	switch arg := vPtr.(type) {
+	case *string:
+		// If they want a string and it is a JSON string, strip quotes
+		// This allows someone to send a struct but receive as a plain string
+		// This cast should be efficient for Go 1.3 and beyond.
+		str := string(data)
+		if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) {
+			*arg = str[1 : len(str)-1]
+		} else {
+			*arg = str
+		}
+	case *[]byte:
+		*arg = data
+	default:
+		err = json.Unmarshal(data, arg)
+	}
+	return
+}

+ 8 - 0
vendor/github.com/nats-io/nats.go/go.mod

@@ -0,0 +1,8 @@
+module github.com/nats-io/nats.go
+
+go 1.16
+
+require (
+	github.com/nats-io/nkeys v0.3.0
+	github.com/nats-io/nuid v1.0.1
+)

+ 11 - 0
vendor/github.com/nats-io/nats.go/go.sum

@@ -0,0 +1,11 @@
+github.com/nats-io/nkeys v0.3.0 h1:cgM5tL53EvYRU+2YLXIK0G2mJtK12Ft9oeooSZMA2G8=
+github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4=
+github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
+github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
+golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b h1:wSOdpTq0/eI46Ez/LkDwIsAKA71YP2SRKBODiRWM0as=
+golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

+ 11 - 0
vendor/github.com/nats-io/nats.go/go_test.mod

@@ -0,0 +1,11 @@
+module github.com/nats-io/nats.go
+
+go 1.15
+
+require (
+	github.com/golang/protobuf v1.4.2
+	github.com/nats-io/nats-server/v2 v2.2.3-0.20210501163444-670f44f1e82e
+	github.com/nats-io/nkeys v0.3.0
+	github.com/nats-io/nuid v1.0.1
+	google.golang.org/protobuf v1.23.0
+)

+ 99 - 0
vendor/github.com/nats-io/nats.go/go_test.sum

@@ -0,0 +1,99 @@
+github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
+github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
+github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
+github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
+github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
+github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
+github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
+github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
+github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
+github.com/klauspost/compress v1.11.12 h1:famVnQVu7QwryBN4jNseQdUKES71ZAOnB6UQQJPZvqk=
+github.com/klauspost/compress v1.11.12/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
+github.com/minio/highwayhash v1.0.0/go.mod h1:xQboMTeM9nY9v/LlAOxFctujiv5+Aq2hR5dxBpaMbdc=
+github.com/minio/highwayhash v1.0.1 h1:dZ6IIu8Z14VlC0VpfKofAhCy74wu/Qb5gcn52yWoz/0=
+github.com/minio/highwayhash v1.0.1/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY=
+github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU=
+github.com/nats-io/jwt v0.3.3-0.20200519195258-f2bf5ce574c7/go.mod h1:n3cvmLfBfnpV4JJRN7lRYCyZnw48ksGsbThGXEk4w9M=
+github.com/nats-io/jwt v1.1.0/go.mod h1:n3cvmLfBfnpV4JJRN7lRYCyZnw48ksGsbThGXEk4w9M=
+github.com/nats-io/jwt v1.2.2 h1:w3GMTO969dFg+UOKTmmyuu7IGdusK+7Ytlt//OYH/uU=
+github.com/nats-io/jwt v1.2.2/go.mod h1:/xX356yQA6LuXI9xWW7mZNpxgF2mBmGecH+Fj34sP5Q=
+github.com/nats-io/jwt/v2 v2.0.0-20200916203241-1f8ce17dff02/go.mod h1:vs+ZEjP+XKy8szkBmQwCB7RjYdIlMaPsFPs4VdS4bTQ=
+github.com/nats-io/jwt/v2 v2.0.0-20201015190852-e11ce317263c/go.mod h1:vs+ZEjP+XKy8szkBmQwCB7RjYdIlMaPsFPs4VdS4bTQ=
+github.com/nats-io/jwt/v2 v2.0.0-20210125223648-1c24d462becc/go.mod h1:PuO5FToRL31ecdFqVjc794vK0Bj0CwzveQEDvkb7MoQ=
+github.com/nats-io/jwt/v2 v2.0.0-20210208203759-ff814ca5f813/go.mod h1:PuO5FToRL31ecdFqVjc794vK0Bj0CwzveQEDvkb7MoQ=
+github.com/nats-io/jwt/v2 v2.0.1 h1:SycklijeduR742i/1Y3nRhURYM7imDzZZ3+tuAQqhQA=
+github.com/nats-io/jwt/v2 v2.0.1/go.mod h1:VRP+deawSXyhNjXmxPCHskrR6Mq50BqpEI5SEcNiGlY=
+github.com/nats-io/nats-server/v2 v2.1.8-0.20200524125952-51ebd92a9093/go.mod h1:rQnBf2Rv4P9adtAs/Ti6LfFmVtFG6HLhl/H7cVshcJU=
+github.com/nats-io/nats-server/v2 v2.1.8-0.20200601203034-f8d6dd992b71/go.mod h1:Nan/1L5Sa1JRW+Thm4HNYcIDcVRFc5zK9OpSZeI2kk4=
+github.com/nats-io/nats-server/v2 v2.1.8-0.20200929001935-7f44d075f7ad/go.mod h1:TkHpUIDETmTI7mrHN40D1pzxfzHZuGmtMbtb83TGVQw=
+github.com/nats-io/nats-server/v2 v2.1.8-0.20201129161730-ebe63db3e3ed/go.mod h1:XD0zHR/jTXdZvWaQfS5mQgsXj6x12kMjKLyAk/cOGgY=
+github.com/nats-io/nats-server/v2 v2.1.8-0.20210205154825-f7ab27f7dad4/go.mod h1:kauGd7hB5517KeSqspW2U1Mz/jhPbTrE8eOXzUPk1m0=
+github.com/nats-io/nats-server/v2 v2.1.8-0.20210227190344-51550e242af8/go.mod h1:/QQ/dpqFavkNhVnjvMILSQ3cj5hlmhB66adlgNbjuoA=
+github.com/nats-io/nats-server/v2 v2.2.1-0.20210330155036-61cbd74e213d/go.mod h1:eKlAaGmSQHZMFQA6x56AaP5/Bl9N3mWF4awyT2TTpzc=
+github.com/nats-io/nats-server/v2 v2.2.1 h1:QaWKih9qAa1kod7xXy0G1ry0AEUGmDEaptaiqzuO1e8=
+github.com/nats-io/nats-server/v2 v2.2.1/go.mod h1:A+5EOqdnhH7FvLxtAK6SEDx6hyHriVOwf+FT/eEV99c=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421001316-7ac0ff667439 h1:wbm+DoCrBx3XUkfgfnzSGKGKXSSnR8z0EzaH8iEsYT4=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421001316-7ac0ff667439/go.mod h1:A+5EOqdnhH7FvLxtAK6SEDx6hyHriVOwf+FT/eEV99c=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421031524-a3f66508dd3a h1:Ihh+7S9hHb3zn4nibE9EV8P3Ed7OrH4TlGXHqIUYDfk=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421031524-a3f66508dd3a/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421135834-a9607573b30c h1:URcPI+y2OIGWM1pKzHhHTvRItB0Czlv3dzuJA0rklvk=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421135834-a9607573b30c/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421164150-3d928c847a0c h1:cbbxAcABuk2WdXKRm9VezFcGsceRhls4VCmQ/2aRJjQ=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421164150-3d928c847a0c/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421195432-ea21e86996f7 h1:wcd++VZMdwDpQ7P1VXJ7NpAwtgdlxcjFLZ12Y/pL8Nw=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421195432-ea21e86996f7/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421215445-a48a39251636 h1:iy6c/tV66xi5DT9WLUu9rJ8uQj8Kf7kmwHAqlYfczP4=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421215445-a48a39251636/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421232642-f2d3f5fb81d0 h1:e2MoeAShQE/oOSjkkV6J6R+l5ugbfkXI5spxgQykgoM=
+github.com/nats-io/nats-server/v2 v2.2.2-0.20210421232642-f2d3f5fb81d0/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats-server/v2 v2.2.3-0.20210501163444-670f44f1e82e h1:Hvpz1/Epth4q7LnaU0U9SqMFd8grUMFTL8LMO5HFVok=
+github.com/nats-io/nats-server/v2 v2.2.3-0.20210501163444-670f44f1e82e/go.mod h1:aF2IwMZdYktJswITm41c/k66uCHjTvpTxGQ7+d4cPeg=
+github.com/nats-io/nats.go v1.10.0/go.mod h1:AjGArbfyR50+afOUotNX2Xs5SYHf+CoOa5HH1eEl2HE=
+github.com/nats-io/nats.go v1.10.1-0.20200531124210-96f2130e4d55/go.mod h1:ARiFsjW9DVxk48WJbO3OSZ2DG8fjkMi7ecLmXoY/n9I=
+github.com/nats-io/nats.go v1.10.1-0.20200606002146-fc6fed82929a/go.mod h1:8eAIv96Mo9QW6Or40jUHejS7e4VwZ3VRYD6Sf0BTDp4=
+github.com/nats-io/nats.go v1.10.1-0.20201021145452-94be476ad6e0/go.mod h1:VU2zERjp8xmF+Lw2NH4u2t5qWZxwc7jB3+7HVMWQXPI=
+github.com/nats-io/nats.go v1.10.1-0.20210127212649-5b4924938a9a/go.mod h1:Sa3kLIonafChP5IF0b55i9uvGR10I3hPETFbi4+9kOI=
+github.com/nats-io/nats.go v1.10.1-0.20210211000709-75ded9c77585/go.mod h1:uBWnCKg9luW1g7hgzPxUjHFRI40EuTSX7RCzgnc74Jk=
+github.com/nats-io/nats.go v1.10.1-0.20210228004050-ed743748acac/go.mod h1:hxFvLNbNmT6UppX5B5Tr/r3g+XSwGjJzFn6mxPNJEHc=
+github.com/nats-io/nats.go v1.10.1-0.20210330225420-a0b1f60162f8/go.mod h1:Zq9IEHy7zurF0kFbU5aLIknnFI7guh8ijHk+2v+Vf5g=
+github.com/nats-io/nats.go v1.10.1-0.20210419223411-20527524c393/go.mod h1:BPko4oXsySz4aSWeFgOHLZs3G4Jq4ZAyE6/zMCxRT6w=
+github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
+github.com/nats-io/nkeys v0.1.4/go.mod h1:XdZpAbhgyyODYqjTawOnIOI7VlbKSarI9Gfy1tqEu/s=
+github.com/nats-io/nkeys v0.2.0/go.mod h1:XdZpAbhgyyODYqjTawOnIOI7VlbKSarI9Gfy1tqEu/s=
+github.com/nats-io/nkeys v0.3.0 h1:cgM5tL53EvYRU+2YLXIK0G2mJtK12Ft9oeooSZMA2G8=
+github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4=
+github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
+github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b h1:wSOdpTq0/eI46Ez/LkDwIsAKA71YP2SRKBODiRWM0as=
+golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 h1:NusfzzA6yGQ+ua51ck7E3omNUX/JuqbFSaRGqU8CcLI=
+golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
+google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
+google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
+google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=

+ 2345 - 0
vendor/github.com/nats-io/nats.go/js.go

@@ -0,0 +1,2345 @@
+// Copyright 2020-2021 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package nats
+
+import (
+	"bytes"
+	"context"
+	"crypto/sha256"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"math/rand"
+	"strconv"
+	"strings"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"github.com/nats-io/nuid"
+)
+
+// Request API subjects for JetStream.
+const (
+	// defaultAPIPrefix is the default prefix for the JetStream API.
+	defaultAPIPrefix = "$JS.API."
+
+	// apiAccountInfo is for obtaining general information about JetStream.
+	apiAccountInfo = "INFO"
+
+	// apiConsumerCreateT is used to create consumers.
+	apiConsumerCreateT = "CONSUMER.CREATE.%s"
+
+	// apiDurableCreateT is used to create durable consumers.
+	apiDurableCreateT = "CONSUMER.DURABLE.CREATE.%s.%s"
+
+	// apiConsumerInfoT is used to create consumers.
+	apiConsumerInfoT = "CONSUMER.INFO.%s.%s"
+
+	// apiRequestNextT is the prefix for the request next message(s) for a consumer in worker/pull mode.
+	apiRequestNextT = "CONSUMER.MSG.NEXT.%s.%s"
+
+	// apiDeleteConsumerT is used to delete consumers.
+	apiConsumerDeleteT = "CONSUMER.DELETE.%s.%s"
+
+	// apiConsumerListT is used to return all detailed consumer information
+	apiConsumerListT = "CONSUMER.LIST.%s"
+
+	// apiConsumerNamesT is used to return a list with all consumer names for the stream.
+	apiConsumerNamesT = "CONSUMER.NAMES.%s"
+
+	// apiStreams can lookup a stream by subject.
+	apiStreams = "STREAM.NAMES"
+
+	// apiStreamCreateT is the endpoint to create new streams.
+	apiStreamCreateT = "STREAM.CREATE.%s"
+
+	// apiStreamInfoT is the endpoint to get information on a stream.
+	apiStreamInfoT = "STREAM.INFO.%s"
+
+	// apiStreamUpdate is the endpoint to update existing streams.
+	apiStreamUpdateT = "STREAM.UPDATE.%s"
+
+	// apiStreamDeleteT is the endpoint to delete streams.
+	apiStreamDeleteT = "STREAM.DELETE.%s"
+
+	// apiPurgeStreamT is the endpoint to purge streams.
+	apiStreamPurgeT = "STREAM.PURGE.%s"
+
+	// apiStreamListT is the endpoint that will return all detailed stream information
+	apiStreamList = "STREAM.LIST"
+
+	// apiMsgGetT is the endpoint to get a message.
+	apiMsgGetT = "STREAM.MSG.GET.%s"
+
+	// apiMsgDeleteT is the endpoint to remove a message.
+	apiMsgDeleteT = "STREAM.MSG.DELETE.%s"
+)
+
+// JetStream allows persistent messaging through JetStream.
+type JetStream interface {
+	// Publish publishes a message to JetStream.
+	Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error)
+
+	// PublishMsg publishes a Msg to JetStream.
+	PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error)
+
+	// PublishAsync publishes a message to JetStream and returns a PubAckFuture.
+	// The data should not be changed until the PubAckFuture has been processed.
+	PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error)
+
+	// PublishMsgAsync publishes a Msg to JetStream and returms a PubAckFuture.
+	// The message should not be changed until the PubAckFuture has been processed.
+	PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error)
+
+	// PublishAsyncPending returns the number of async publishes outstanding for this context.
+	PublishAsyncPending() int
+
+	// PublishAsyncComplete returns a channel that will be closed when all outstanding messages are ack'd.
+	PublishAsyncComplete() <-chan struct{}
+
+	// Subscribe creates an async Subscription for JetStream.
+	Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error)
+
+	// SubscribeSync creates a Subscription that can be used to process messages synchronously.
+	SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error)
+
+	// ChanSubscribe creates channel based Subscription.
+	ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error)
+
+	// QueueSubscribe creates a Subscription with a queue group.
+	QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error)
+
+	// QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously.
+	QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error)
+
+	// PullSubscribe creates a Subscription that can fetch messages.
+	PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error)
+}
+
+// JetStreamContext allows JetStream messaging and stream management.
+type JetStreamContext interface {
+	JetStream
+	JetStreamManager
+}
+
+// js is an internal struct from a JetStreamContext.
+type js struct {
+	nc   *Conn
+	opts *jsOpts
+
+	// For async publish context.
+	mu   sync.RWMutex
+	rpre string
+	rsub *Subscription
+	pafs map[string]*pubAckFuture
+	stc  chan struct{}
+	dch  chan struct{}
+	rr   *rand.Rand
+}
+
+type jsOpts struct {
+	ctx context.Context
+	// For importing JetStream from other accounts.
+	pre string
+	// Amount of time to wait for API requests.
+	wait time.Duration
+	// For async publish error handling.
+	aecb MsgErrHandler
+	// Maximum in flight.
+	maxap int
+}
+
+const (
+	defaultRequestWait  = 5 * time.Second
+	defaultAccountCheck = 20 * time.Second
+)
+
+// JetStream returns a JetStreamContext for messaging and stream management.
+func (nc *Conn) JetStream(opts ...JSOpt) (JetStreamContext, error) {
+	js := &js{
+		nc: nc,
+		opts: &jsOpts{
+			pre:  defaultAPIPrefix,
+			wait: defaultRequestWait,
+		},
+	}
+
+	for _, opt := range opts {
+		if err := opt.configureJSContext(js.opts); err != nil {
+			return nil, err
+		}
+	}
+
+	// If we have check recently we can avoid another account lookup here.
+	// We want these to be lighweight and created at will.
+	nc.mu.Lock()
+	now := time.Now()
+	checkAccount := now.Sub(nc.jsLastCheck) > defaultAccountCheck
+	if checkAccount {
+		nc.jsLastCheck = now
+	}
+	nc.mu.Unlock()
+
+	if checkAccount {
+		if _, err := js.AccountInfo(); err != nil {
+			if err == ErrNoResponders {
+				err = ErrJetStreamNotEnabled
+			}
+			return nil, err
+		}
+	}
+
+	return js, nil
+}
+
+// JSOpt configures a JetStreamContext.
+type JSOpt interface {
+	configureJSContext(opts *jsOpts) error
+}
+
+// jsOptFn configures an option for the JetStreamContext.
+type jsOptFn func(opts *jsOpts) error
+
+func (opt jsOptFn) configureJSContext(opts *jsOpts) error {
+	return opt(opts)
+}
+
+// APIPrefix changes the default prefix used for the JetStream API.
+func APIPrefix(pre string) JSOpt {
+	return jsOptFn(func(js *jsOpts) error {
+		js.pre = pre
+		if !strings.HasSuffix(js.pre, ".") {
+			js.pre = js.pre + "."
+		}
+		return nil
+	})
+}
+
+func (js *js) apiSubj(subj string) string {
+	if js.opts.pre == _EMPTY_ {
+		return subj
+	}
+	var b strings.Builder
+	b.WriteString(js.opts.pre)
+	b.WriteString(subj)
+	return b.String()
+}
+
+// PubOpt configures options for publishing JetStream messages.
+type PubOpt interface {
+	configurePublish(opts *pubOpts) error
+}
+
+// pubOptFn is a function option used to configure JetStream Publish.
+type pubOptFn func(opts *pubOpts) error
+
+func (opt pubOptFn) configurePublish(opts *pubOpts) error {
+	return opt(opts)
+}
+
+type pubOpts struct {
+	ctx context.Context
+	ttl time.Duration
+	id  string
+	lid string // Expected last msgId
+	str string // Expected stream name
+	seq uint64 // Expected last sequence
+}
+
+// pubAckResponse is the ack response from the JetStream API when publishing a message.
+type pubAckResponse struct {
+	apiResponse
+	*PubAck
+}
+
+// PubAck is an ack received after successfully publishing a message.
+type PubAck struct {
+	Stream    string `json:"stream"`
+	Sequence  uint64 `json:"seq"`
+	Duplicate bool   `json:"duplicate,omitempty"`
+}
+
+// Headers for published messages.
+const (
+	MsgIdHdr             = "Nats-Msg-Id"
+	ExpectedStreamHdr    = "Nats-Expected-Stream"
+	ExpectedLastSeqHdr   = "Nats-Expected-Last-Sequence"
+	ExpectedLastMsgIdHdr = "Nats-Expected-Last-Msg-Id"
+)
+
+// PublishMsg publishes a Msg to a stream from JetStream.
+func (js *js) PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error) {
+	var o pubOpts
+	if len(opts) > 0 {
+		if m.Header == nil {
+			m.Header = Header{}
+		}
+		for _, opt := range opts {
+			if err := opt.configurePublish(&o); err != nil {
+				return nil, err
+			}
+		}
+	}
+	// Check for option collisions. Right now just timeout and context.
+	if o.ctx != nil && o.ttl != 0 {
+		return nil, ErrContextAndTimeout
+	}
+	if o.ttl == 0 && o.ctx == nil {
+		o.ttl = js.opts.wait
+	}
+
+	if o.id != _EMPTY_ {
+		m.Header.Set(MsgIdHdr, o.id)
+	}
+	if o.lid != _EMPTY_ {
+		m.Header.Set(ExpectedLastMsgIdHdr, o.lid)
+	}
+	if o.str != _EMPTY_ {
+		m.Header.Set(ExpectedStreamHdr, o.str)
+	}
+	if o.seq > 0 {
+		m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(o.seq, 10))
+	}
+
+	var resp *Msg
+	var err error
+
+	if o.ttl > 0 {
+		resp, err = js.nc.RequestMsg(m, time.Duration(o.ttl))
+	} else {
+		resp, err = js.nc.RequestMsgWithContext(o.ctx, m)
+	}
+
+	if err != nil {
+		if err == ErrNoResponders {
+			err = ErrNoStreamResponse
+		}
+		return nil, err
+	}
+	var pa pubAckResponse
+	if err := json.Unmarshal(resp.Data, &pa); err != nil {
+		return nil, ErrInvalidJSAck
+	}
+	if pa.Error != nil {
+		return nil, fmt.Errorf("nats: %s", pa.Error.Description)
+	}
+	if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ {
+		return nil, ErrInvalidJSAck
+	}
+	return pa.PubAck, nil
+}
+
+// Publish publishes a message to a stream from JetStream.
+func (js *js) Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error) {
+	return js.PublishMsg(&Msg{Subject: subj, Data: data}, opts...)
+}
+
+// PubAckFuture is a future for a PubAck.
+type PubAckFuture interface {
+	// Ok returns a receive only channel that can be used to get a PubAck.
+	Ok() <-chan *PubAck
+
+	// Err returns a receive only channel that can be used to get the error from an async publish.
+	Err() <-chan error
+
+	// Msg returns the message that was sent to the server.
+	Msg() *Msg
+}
+
+type pubAckFuture struct {
+	js     *js
+	msg    *Msg
+	pa     *PubAck
+	st     time.Time
+	err    error
+	errCh  chan error
+	doneCh chan *PubAck
+}
+
+func (paf *pubAckFuture) Ok() <-chan *PubAck {
+	paf.js.mu.Lock()
+	defer paf.js.mu.Unlock()
+
+	if paf.doneCh == nil {
+		paf.doneCh = make(chan *PubAck, 1)
+		if paf.pa != nil {
+			paf.doneCh <- paf.pa
+		}
+	}
+
+	return paf.doneCh
+}
+
+func (paf *pubAckFuture) Err() <-chan error {
+	paf.js.mu.Lock()
+	defer paf.js.mu.Unlock()
+
+	if paf.errCh == nil {
+		paf.errCh = make(chan error, 1)
+		if paf.err != nil {
+			paf.errCh <- paf.err
+		}
+	}
+
+	return paf.errCh
+}
+
+func (paf *pubAckFuture) Msg() *Msg {
+	paf.js.mu.RLock()
+	defer paf.js.mu.RUnlock()
+	return paf.msg
+}
+
+// pullSubscribe creates the wildcard subscription used per pull subscriber
+// to make fetch requests.
+func (js *js) pullSubscribe(subj string) (*Subscription, error) {
+	jsi := &jsSub{js: js, pull: true}
+
+	// Similar to async request handler we create a wildcard subscription for making requests,
+	// though we do not use the token based approach since we cannot match the response to
+	// the requestor due to JS subject being remapped on delivery.  Instead, we just use an array
+	// of channels similar to how ping/pong interval is handled and send the message to the first
+	// available requestor via a channel.
+	jsi.rr = rand.New(rand.NewSource(time.Now().UnixNano()))
+	jsi.rpre = fmt.Sprintf("%s.", NewInbox())
+	sub, err := js.nc.Subscribe(fmt.Sprintf("%s*", jsi.rpre), jsi.handleFetch)
+	if err != nil {
+		return nil, err
+	}
+	jsi.psub = sub
+
+	return &Subscription{Subject: subj, conn: js.nc, typ: PullSubscription, jsi: jsi}, nil
+}
+
+// For quick token lookup etc.
+const aReplyPreLen = 14
+const aReplyTokensize = 6
+
+func (js *js) newAsyncReply() string {
+	js.mu.Lock()
+	if js.rsub == nil {
+		// Create our wildcard reply subject.
+		sha := sha256.New()
+		sha.Write([]byte(nuid.Next()))
+		b := sha.Sum(nil)
+		for i := 0; i < aReplyTokensize; i++ {
+			b[i] = rdigits[int(b[i]%base)]
+		}
+		js.rpre = fmt.Sprintf("%s%s.", InboxPrefix, b[:aReplyTokensize])
+		sub, err := js.nc.Subscribe(fmt.Sprintf("%s*", js.rpre), js.handleAsyncReply)
+		if err != nil {
+			js.mu.Unlock()
+			return _EMPTY_
+		}
+		js.rsub = sub
+		js.rr = rand.New(rand.NewSource(time.Now().UnixNano()))
+	}
+	var sb strings.Builder
+	sb.WriteString(js.rpre)
+	rn := js.rr.Int63()
+	var b [aReplyTokensize]byte
+	for i, l := 0, rn; i < len(b); i++ {
+		b[i] = rdigits[l%base]
+		l /= base
+	}
+	sb.Write(b[:])
+	js.mu.Unlock()
+	return sb.String()
+}
+
+// registerPAF will register for a PubAckFuture.
+func (js *js) registerPAF(id string, paf *pubAckFuture) (int, int) {
+	js.mu.Lock()
+	if js.pafs == nil {
+		js.pafs = make(map[string]*pubAckFuture)
+	}
+	paf.js = js
+	js.pafs[id] = paf
+	np := len(js.pafs)
+	maxap := js.opts.maxap
+	js.mu.Unlock()
+	return np, maxap
+}
+
+// Lock should be held.
+func (js *js) getPAF(id string) *pubAckFuture {
+	if js.pafs == nil {
+		return nil
+	}
+	return js.pafs[id]
+}
+
+// clearPAF will remove a PubAckFuture that was registered.
+func (js *js) clearPAF(id string) {
+	js.mu.Lock()
+	delete(js.pafs, id)
+	js.mu.Unlock()
+}
+
+// PublishAsyncPending returns how many PubAckFutures are pending.
+func (js *js) PublishAsyncPending() int {
+	js.mu.RLock()
+	defer js.mu.RUnlock()
+	return len(js.pafs)
+}
+
+func (js *js) asyncStall() <-chan struct{} {
+	js.mu.Lock()
+	if js.stc == nil {
+		js.stc = make(chan struct{})
+	}
+	stc := js.stc
+	js.mu.Unlock()
+	return stc
+}
+
+// Handle an async reply from PublishAsync.
+func (js *js) handleAsyncReply(m *Msg) {
+	if len(m.Subject) <= aReplyPreLen {
+		return
+	}
+	id := m.Subject[aReplyPreLen:]
+
+	js.mu.Lock()
+	paf := js.getPAF(id)
+	if paf == nil {
+		js.mu.Unlock()
+		return
+	}
+	// Remove
+	delete(js.pafs, id)
+
+	// Check on anyone stalled and waiting.
+	if js.stc != nil && len(js.pafs) < js.opts.maxap {
+		close(js.stc)
+		js.stc = nil
+	}
+	// Check on anyone one waiting on done status.
+	if js.dch != nil && len(js.pafs) == 0 {
+		dch := js.dch
+		js.dch = nil
+		// Defer here so error is processed and can be checked.
+		defer close(dch)
+	}
+
+	doErr := func(err error) {
+		paf.err = err
+		if paf.errCh != nil {
+			paf.errCh <- paf.err
+		}
+		cb := js.opts.aecb
+		js.mu.Unlock()
+		if cb != nil {
+			cb(paf.js, paf.msg, err)
+		}
+	}
+
+	// Process no responders etc.
+	if len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
+		doErr(ErrNoResponders)
+		return
+	}
+
+	var pa pubAckResponse
+	if err := json.Unmarshal(m.Data, &pa); err != nil {
+		doErr(ErrInvalidJSAck)
+		return
+	}
+	if pa.Error != nil {
+		doErr(fmt.Errorf("nats: %s", pa.Error.Description))
+		return
+	}
+	if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ {
+		doErr(ErrInvalidJSAck)
+		return
+	}
+
+	// So here we have received a proper puback.
+	paf.pa = pa.PubAck
+	if paf.doneCh != nil {
+		paf.doneCh <- paf.pa
+	}
+	js.mu.Unlock()
+}
+
+// MsgErrHandler is used to process asynchronous errors from
+// JetStream PublishAsync and PublishAsynMsg. It will return the original
+// message sent to the server for possible retransmitting and the error encountered.
+type MsgErrHandler func(JetStream, *Msg, error)
+
+// PublishAsyncErrHandler sets the error handler for async publishes in JetStream.
+func PublishAsyncErrHandler(cb MsgErrHandler) JSOpt {
+	return jsOptFn(func(js *jsOpts) error {
+		js.aecb = cb
+		return nil
+	})
+}
+
+// PublishAsyncMaxPending sets the maximum outstanding async publishes that can be inflight at one time.
+func PublishAsyncMaxPending(max int) JSOpt {
+	return jsOptFn(func(js *jsOpts) error {
+		if max < 1 {
+			return errors.New("nats: max ack pending should be >= 1")
+		}
+		js.maxap = max
+		return nil
+	})
+}
+
+// PublishAsync publishes a message to JetStream and returns a PubAckFuture
+func (js *js) PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error) {
+	return js.PublishMsgAsync(&Msg{Subject: subj, Data: data}, opts...)
+}
+
+func (js *js) PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error) {
+	var o pubOpts
+	if len(opts) > 0 {
+		if m.Header == nil {
+			m.Header = Header{}
+		}
+		for _, opt := range opts {
+			if err := opt.configurePublish(&o); err != nil {
+				return nil, err
+			}
+		}
+	}
+
+	// Timeouts and contexts do not make sense for these.
+	if o.ttl != 0 || o.ctx != nil {
+		return nil, ErrContextAndTimeout
+	}
+
+	// FIXME(dlc) - Make common.
+	if o.id != _EMPTY_ {
+		m.Header.Set(MsgIdHdr, o.id)
+	}
+	if o.lid != _EMPTY_ {
+		m.Header.Set(ExpectedLastMsgIdHdr, o.lid)
+	}
+	if o.str != _EMPTY_ {
+		m.Header.Set(ExpectedStreamHdr, o.str)
+	}
+	if o.seq > 0 {
+		m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(o.seq, 10))
+	}
+
+	// Reply
+	if m.Reply != _EMPTY_ {
+		return nil, errors.New("nats: reply subject should be empty")
+	}
+	m.Reply = js.newAsyncReply()
+	if m.Reply == _EMPTY_ {
+		return nil, errors.New("nats: error creating async reply handler")
+	}
+	id := m.Reply[aReplyPreLen:]
+	paf := &pubAckFuture{msg: m, st: time.Now()}
+	numPending, maxPending := js.registerPAF(id, paf)
+
+	if maxPending > 0 && numPending >= maxPending {
+		select {
+		case <-js.asyncStall():
+		case <-time.After(200 * time.Millisecond):
+			js.clearPAF(id)
+			return nil, errors.New("nats: stalled with too many outstanding async published messages")
+		}
+	}
+
+	if err := js.nc.PublishMsg(m); err != nil {
+		js.clearPAF(id)
+		return nil, err
+	}
+
+	return paf, nil
+}
+
+// PublishAsyncComplete returns a channel that will be closed when all outstanding messages have been ack'd.
+func (js *js) PublishAsyncComplete() <-chan struct{} {
+	js.mu.Lock()
+	defer js.mu.Unlock()
+	if js.dch == nil {
+		js.dch = make(chan struct{})
+	}
+	dch := js.dch
+	if len(js.pafs) == 0 {
+		close(js.dch)
+		js.dch = nil
+	}
+	return dch
+}
+
+// MsgId sets the message ID used for de-duplication.
+func MsgId(id string) PubOpt {
+	return pubOptFn(func(opts *pubOpts) error {
+		opts.id = id
+		return nil
+	})
+}
+
+// ExpectStream sets the expected stream to respond from the publish.
+func ExpectStream(stream string) PubOpt {
+	return pubOptFn(func(opts *pubOpts) error {
+		opts.str = stream
+		return nil
+	})
+}
+
+// ExpectLastSequence sets the expected sequence in the response from the publish.
+func ExpectLastSequence(seq uint64) PubOpt {
+	return pubOptFn(func(opts *pubOpts) error {
+		opts.seq = seq
+		return nil
+	})
+}
+
+// ExpectLastSequence sets the expected sequence in the response from the publish.
+func ExpectLastMsgId(id string) PubOpt {
+	return pubOptFn(func(opts *pubOpts) error {
+		opts.lid = id
+		return nil
+	})
+}
+
+type ackOpts struct {
+	ttl time.Duration
+	ctx context.Context
+}
+
+// AckOpt are the options that can be passed when acknowledge a message.
+type AckOpt interface {
+	configureAck(opts *ackOpts) error
+}
+
+// MaxWait sets the maximum amount of time we will wait for a response.
+type MaxWait time.Duration
+
+func (ttl MaxWait) configureJSContext(js *jsOpts) error {
+	js.wait = time.Duration(ttl)
+	return nil
+}
+
+func (ttl MaxWait) configurePull(opts *pullOpts) error {
+	opts.ttl = time.Duration(ttl)
+	return nil
+}
+
+// AckWait sets the maximum amount of time we will wait for an ack.
+type AckWait time.Duration
+
+func (ttl AckWait) configurePublish(opts *pubOpts) error {
+	opts.ttl = time.Duration(ttl)
+	return nil
+}
+
+func (ttl AckWait) configureSubscribe(opts *subOpts) error {
+	opts.cfg.AckWait = time.Duration(ttl)
+	return nil
+}
+
+func (ttl AckWait) configureAck(opts *ackOpts) error {
+	opts.ttl = time.Duration(ttl)
+	return nil
+}
+
+// ContextOpt is an option used to set a context.Context.
+type ContextOpt struct {
+	context.Context
+}
+
+func (ctx ContextOpt) configureJSContext(opts *jsOpts) error {
+	opts.ctx = ctx
+	return nil
+}
+
+func (ctx ContextOpt) configurePublish(opts *pubOpts) error {
+	opts.ctx = ctx
+	return nil
+}
+
+func (ctx ContextOpt) configurePull(opts *pullOpts) error {
+	opts.ctx = ctx
+	return nil
+}
+
+func (ctx ContextOpt) configureAck(opts *ackOpts) error {
+	opts.ctx = ctx
+	return nil
+}
+
+// Context returns an option that can be used to configure a context for APIs
+// that are context aware such as those part of the JetStream interface.
+func Context(ctx context.Context) ContextOpt {
+	return ContextOpt{ctx}
+}
+
+// Subscribe
+
+// ConsumerConfig is the configuration of a JetStream consumer.
+type ConsumerConfig struct {
+	Durable         string        `json:"durable_name,omitempty"`
+	DeliverSubject  string        `json:"deliver_subject,omitempty"`
+	DeliverPolicy   DeliverPolicy `json:"deliver_policy"`
+	OptStartSeq     uint64        `json:"opt_start_seq,omitempty"`
+	OptStartTime    *time.Time    `json:"opt_start_time,omitempty"`
+	AckPolicy       AckPolicy     `json:"ack_policy"`
+	AckWait         time.Duration `json:"ack_wait,omitempty"`
+	MaxDeliver      int           `json:"max_deliver,omitempty"`
+	FilterSubject   string        `json:"filter_subject,omitempty"`
+	ReplayPolicy    ReplayPolicy  `json:"replay_policy"`
+	RateLimit       uint64        `json:"rate_limit_bps,omitempty"` // Bits per sec
+	SampleFrequency string        `json:"sample_freq,omitempty"`
+	MaxWaiting      int           `json:"max_waiting,omitempty"`
+	MaxAckPending   int           `json:"max_ack_pending,omitempty"`
+	FlowControl     bool          `json:"flow_control,omitempty"`
+	Heartbeat       time.Duration `json:"idle_heartbeat,omitempty"`
+}
+
+// ConsumerInfo is the info from a JetStream consumer.
+type ConsumerInfo struct {
+	Stream         string         `json:"stream_name"`
+	Name           string         `json:"name"`
+	Created        time.Time      `json:"created"`
+	Config         ConsumerConfig `json:"config"`
+	Delivered      SequencePair   `json:"delivered"`
+	AckFloor       SequencePair   `json:"ack_floor"`
+	NumAckPending  int            `json:"num_ack_pending"`
+	NumRedelivered int            `json:"num_redelivered"`
+	NumWaiting     int            `json:"num_waiting"`
+	NumPending     uint64         `json:"num_pending"`
+	Cluster        *ClusterInfo   `json:"cluster,omitempty"`
+}
+
+// SequencePair includes the consumer and stream sequence info from a JetStream consumer.
+type SequencePair struct {
+	Consumer uint64 `json:"consumer_seq"`
+	Stream   uint64 `json:"stream_seq"`
+}
+
+// nextRequest is for getting next messages for pull based consumers from JetStream.
+type nextRequest struct {
+	Expires time.Duration `json:"expires,omitempty"`
+	Batch   int           `json:"batch,omitempty"`
+	NoWait  bool          `json:"no_wait,omitempty"`
+}
+
+// jsSub includes JetStream subscription info.
+type jsSub struct {
+	js *js
+
+	// To setup request mux handler for pull subscribers.
+	mu    sync.RWMutex
+	psub  *Subscription
+	rpre  string
+	rr    *rand.Rand
+	freqs []chan *Msg
+
+	consumer string
+	stream   string
+	deliver  string
+	pull     bool
+	durable  bool
+	attached bool
+
+	// Heartbeats and Flow Control handling from push consumers.
+	hbs   bool
+	fc    bool
+	cmeta string
+	fcs   map[uint64]string
+}
+
+// newFetchReply generates a unique inbox used for a fetch request.
+func (jsi *jsSub) newFetchReply() string {
+	jsi.mu.Lock()
+	rpre := jsi.rpre
+	rn := jsi.rr.Int63()
+	jsi.mu.Unlock()
+	var sb strings.Builder
+	sb.WriteString(rpre)
+	var b [aReplyTokensize]byte
+	for i, l := 0, rn; i < len(b); i++ {
+		b[i] = rdigits[l%base]
+		l /= base
+	}
+	sb.Write(b[:])
+	return sb.String()
+}
+
+// handleFetch is delivered a message requested by pull subscribers
+// when calling Fetch.
+func (jsi *jsSub) handleFetch(m *Msg) {
+	jsi.mu.Lock()
+	if len(jsi.freqs) == 0 {
+		nc := jsi.js.nc
+		sub := jsi.psub
+		nc.mu.Lock()
+		errCB := nc.Opts.AsyncErrorCB
+		err := fmt.Errorf("nats: fetch response delivered but requestor has gone away")
+		if errCB != nil {
+			nc.ach.push(func() { errCB(nc, sub, err) })
+		}
+		nc.mu.Unlock()
+		jsi.mu.Unlock()
+		return
+	}
+	mch := jsi.freqs[0]
+	if len(jsi.freqs) > 1 {
+		jsi.freqs = append(jsi.freqs[:0], jsi.freqs[1:]...)
+	} else {
+		jsi.freqs = jsi.freqs[:0]
+	}
+	jsi.mu.Unlock()
+	mch <- m
+}
+
+// fetchNoWait makes a request to get a single message using no wait.
+func (jsi *jsSub) fetchNoWait(ctx context.Context, subj string, payload []byte) (*Msg, error) {
+	nc := jsi.js.nc
+	m := NewMsg(subj)
+	m.Reply = jsi.newFetchReply()
+	m.Data = payload
+
+	mch := make(chan *Msg, 1)
+	jsi.mu.Lock()
+	jsi.freqs = append(jsi.freqs, mch)
+	jsi.mu.Unlock()
+	if err := nc.PublishMsg(m); err != nil {
+		return nil, err
+	}
+
+	var ok bool
+	var msg *Msg
+
+	select {
+	case msg, ok = <-mch:
+		if !ok {
+			return nil, ErrConnectionClosed
+		}
+	case <-ctx.Done():
+		return nil, ctx.Err()
+	}
+
+	return msg, nil
+}
+
+func (jsi *jsSub) unsubscribe(drainMode bool) error {
+	if drainMode && (jsi.durable || jsi.attached) {
+		// Skip deleting consumer for durables/attached
+		// consumers when using drain mode.
+		return nil
+	}
+	// Clear the extra async pull subscription used for fetch requests.
+	if jsi.psub != nil {
+		jsi.psub.Drain()
+	}
+
+	js := jsi.js
+	return js.DeleteConsumer(jsi.stream, jsi.consumer)
+}
+
+// SubOpt configures options for subscribing to JetStream consumers.
+type SubOpt interface {
+	configureSubscribe(opts *subOpts) error
+}
+
+// subOptFn is a function option used to configure a JetStream Subscribe.
+type subOptFn func(opts *subOpts) error
+
+func (opt subOptFn) configureSubscribe(opts *subOpts) error {
+	return opt(opts)
+}
+
+// Subscribe will create a subscription to the appropriate stream and consumer.
+func (js *js) Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) {
+	if cb == nil {
+		return nil, ErrBadSubscription
+	}
+	return js.subscribe(subj, _EMPTY_, cb, nil, false, opts)
+}
+
+// SubscribeSync will create a sync subscription to the appropriate stream and consumer.
+func (js *js) SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error) {
+	mch := make(chan *Msg, js.nc.Opts.SubChanLen)
+	return js.subscribe(subj, _EMPTY_, nil, mch, true, opts)
+}
+
+// QueueSubscribe will create a subscription to the appropriate stream and consumer with queue semantics.
+func (js *js) QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) {
+	if cb == nil {
+		return nil, ErrBadSubscription
+	}
+	return js.subscribe(subj, queue, cb, nil, false, opts)
+}
+
+// QueueSubscribeSync will create a sync subscription to the appropriate stream and consumer with queue semantics.
+func (js *js) QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error) {
+	mch := make(chan *Msg, js.nc.Opts.SubChanLen)
+	return js.subscribe(subj, queue, nil, mch, true, opts)
+}
+
+// Subscribe will create a subscription to the appropriate stream and consumer.
+func (js *js) ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) {
+	return js.subscribe(subj, _EMPTY_, nil, ch, false, opts)
+}
+
+// PullSubscribe creates a pull subscriber.
+func (js *js) PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error) {
+	return js.subscribe(subj, _EMPTY_, nil, nil, false, append(opts, Durable(durable)))
+}
+
+func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, opts []SubOpt) (*Subscription, error) {
+	cfg := ConsumerConfig{AckPolicy: ackPolicyNotSet}
+	o := subOpts{cfg: &cfg}
+	if len(opts) > 0 {
+		for _, opt := range opts {
+			if err := opt.configureSubscribe(&o); err != nil {
+				return nil, err
+			}
+		}
+	}
+
+	isPullMode := ch == nil && cb == nil
+	badPullAck := o.cfg.AckPolicy == AckNonePolicy || o.cfg.AckPolicy == AckAllPolicy
+	hasHeartbeats := o.cfg.Heartbeat > 0
+	hasFC := o.cfg.FlowControl
+	if isPullMode && badPullAck {
+		return nil, fmt.Errorf("nats: invalid ack mode for pull consumers: %s", o.cfg.AckPolicy)
+	}
+
+	var (
+		err          error
+		shouldCreate bool
+		ccfg         *ConsumerConfig
+		info         *ConsumerInfo
+		deliver      string
+		attached     bool
+		stream       = o.stream
+		consumer     = o.consumer
+		isDurable    = o.cfg.Durable != _EMPTY_
+	)
+
+	// Find the stream mapped to the subject if not bound to a stream already.
+	if o.stream == _EMPTY_ {
+		stream, err = js.lookupStreamBySubject(subj)
+		if err != nil {
+			return nil, err
+		}
+	} else {
+		stream = o.stream
+	}
+
+	// With an explicit durable name, then can lookup
+	// the consumer to which it should be attaching to.
+	consumer = o.cfg.Durable
+	if consumer != _EMPTY_ {
+		// Only create in case there is no consumer already.
+		info, err = js.ConsumerInfo(stream, consumer)
+		if err != nil && err.Error() != "nats: consumer not found" {
+			return nil, err
+		}
+	}
+
+	if info != nil {
+		// Attach using the found consumer config.
+		ccfg = &info.Config
+		attached = true
+
+		// Make sure this new subject matches or is a subset.
+		if ccfg.FilterSubject != _EMPTY_ && subj != ccfg.FilterSubject {
+			return nil, ErrSubjectMismatch
+		}
+
+		if ccfg.DeliverSubject != _EMPTY_ {
+			deliver = ccfg.DeliverSubject
+		} else {
+			deliver = NewInbox()
+		}
+	} else {
+		shouldCreate = true
+		deliver = NewInbox()
+		if !isPullMode {
+			cfg.DeliverSubject = deliver
+		}
+		// Do filtering always, server will clear as needed.
+		cfg.FilterSubject = subj
+	}
+
+	var sub *Subscription
+
+	// Check if we are manual ack.
+	if cb != nil && !o.mack {
+		ocb := cb
+		cb = func(m *Msg) { ocb(m); m.Ack() }
+	}
+
+	if isPullMode {
+		sub, err = js.pullSubscribe(subj)
+	} else {
+		sub, err = js.nc.subscribe(deliver, queue, cb, ch, isSync, &jsSub{js: js, hbs: hasHeartbeats, fc: hasFC})
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	// With flow control enabled async subscriptions we will disable msgs
+	// limits, and set a larger pending bytes limit by default.
+	if !isPullMode && cb != nil && hasFC {
+		sub.SetPendingLimits(DefaultSubPendingMsgsLimit*16, DefaultSubPendingBytesLimit)
+	}
+
+	// If we are creating or updating let's process that request.
+	if shouldCreate {
+		// If not set default to ack explicit.
+		if cfg.AckPolicy == ackPolicyNotSet {
+			cfg.AckPolicy = AckExplicitPolicy
+		}
+		// If we have acks at all and the MaxAckPending is not set go ahead
+		// and set to the internal max.
+		// TODO(dlc) - We should be able to update this if client updates PendingLimits.
+		if cfg.MaxAckPending == 0 && cfg.AckPolicy != AckNonePolicy {
+			maxMsgs, _, _ := sub.PendingLimits()
+			cfg.MaxAckPending = maxMsgs
+		}
+
+		req := &createConsumerRequest{
+			Stream: stream,
+			Config: &cfg,
+		}
+
+		j, err := json.Marshal(req)
+		if err != nil {
+			return nil, err
+		}
+
+		var ccSubj string
+		if isDurable {
+			ccSubj = fmt.Sprintf(apiDurableCreateT, stream, cfg.Durable)
+		} else {
+			ccSubj = fmt.Sprintf(apiConsumerCreateT, stream)
+		}
+
+		resp, err := js.nc.Request(js.apiSubj(ccSubj), j, js.opts.wait)
+		if err != nil {
+			sub.Drain()
+			if err == ErrNoResponders {
+				err = ErrJetStreamNotEnabled
+			}
+			return nil, err
+		}
+		var cinfo consumerResponse
+		err = json.Unmarshal(resp.Data, &cinfo)
+		if err != nil {
+			sub.Drain()
+			return nil, err
+		}
+		info = cinfo.ConsumerInfo
+		if cinfo.Error != nil {
+			// Remove interest from previous subscribe since it
+			// may have an incorrect delivery subject.
+			sub.Drain()
+
+			// Multiple subscribers could compete in creating the first consumer
+			// that will be shared using the same durable name. If this happens, then
+			// do a lookup of the consumer info and resubscribe using the latest info.
+			if consumer != _EMPTY_ && (strings.Contains(cinfo.Error.Description, `consumer already exists`) || strings.Contains(cinfo.Error.Description, `consumer name already in use`)) {
+				info, err = js.ConsumerInfo(stream, consumer)
+				if err != nil {
+					return nil, err
+				}
+				ccfg = &info.Config
+
+				// Validate that the original subject does still match.
+				if ccfg.FilterSubject != _EMPTY_ && subj != ccfg.FilterSubject {
+					return nil, ErrSubjectMismatch
+				}
+
+				// Use the deliver subject from latest consumer config to attach.
+				if ccfg.DeliverSubject != _EMPTY_ {
+					// We can't reuse the channel, so if one was passed, we need to create a new one.
+					if ch != nil {
+						ch = make(chan *Msg, cap(ch))
+					}
+					sub, err = js.nc.subscribe(ccfg.DeliverSubject, queue, cb, ch, isSync,
+						&jsSub{js: js, hbs: hasHeartbeats, fc: hasFC})
+					if err != nil {
+						return nil, err
+					}
+				}
+				attached = true
+			} else {
+				return nil, fmt.Errorf("nats: %s", cinfo.Error.Description)
+			}
+		}
+		stream = info.Stream
+		consumer = info.Name
+		deliver = info.Config.DeliverSubject
+	}
+	sub.mu.Lock()
+	sub.jsi.stream = stream
+	sub.jsi.consumer = consumer
+	sub.jsi.durable = isDurable
+	sub.jsi.attached = attached
+	sub.jsi.deliver = deliver
+	sub.mu.Unlock()
+
+	return sub, nil
+}
+
+// ErrConsumerSequenceMismatch represents an error from a consumer
+// that received a Heartbeat including sequence different to the
+// one expected from the view of the client.
+type ErrConsumerSequenceMismatch struct {
+	// StreamResumeSequence is the stream sequence from where the consumer
+	// should resume consuming from the stream.
+	StreamResumeSequence uint64
+
+	// ConsumerSequence is the sequence of the consumer that is behind.
+	ConsumerSequence uint64
+
+	// LastConsumerSequence is the sequence of the consumer when the heartbeat
+	// was received.
+	LastConsumerSequence uint64
+}
+
+func (ecs *ErrConsumerSequenceMismatch) Error() string {
+	return fmt.Sprintf("nats: sequence mismatch for consumer at sequence %d (%d sequences behind), should restart consumer from stream sequence %d",
+		ecs.ConsumerSequence,
+		ecs.LastConsumerSequence-ecs.ConsumerSequence,
+		ecs.StreamResumeSequence,
+	)
+}
+
+// isControlMessage will return true if this is an empty control status message.
+func isControlMessage(msg *Msg) bool {
+	return len(msg.Data) == 0 && msg.Header.Get(statusHdr) == controlMsg
+}
+
+func (jsi *jsSub) trackSequences(reply string) {
+	jsi.mu.Lock()
+	jsi.cmeta = reply
+	jsi.mu.Unlock()
+}
+
+// checkForFlowControlResponse will check to see if we should send a flow control response
+// based on the delivered index.
+// Lock should be held.
+func (sub *Subscription) checkForFlowControlResponse(delivered uint64) {
+	jsi, nc := sub.jsi, sub.conn
+	if jsi == nil {
+		return
+	}
+
+	jsi.mu.Lock()
+	defer jsi.mu.Unlock()
+
+	if len(jsi.fcs) == 0 {
+		return
+	}
+
+	if reply := jsi.fcs[delivered]; reply != _EMPTY_ {
+		delete(jsi.fcs, delivered)
+		nc.Publish(reply, nil)
+	}
+}
+
+// Record an inbound flow control message.
+func (jsi *jsSub) scheduleFlowControlResponse(dfuture uint64, reply string) {
+	jsi.mu.Lock()
+	if jsi.fcs == nil {
+		jsi.fcs = make(map[uint64]string)
+	}
+	jsi.fcs[dfuture] = reply
+	jsi.mu.Unlock()
+}
+
+// handleConsumerSequenceMismatch will send an async error that can be used to restart a push based consumer.
+func (nc *Conn) handleConsumerSequenceMismatch(sub *Subscription, err error) {
+	nc.mu.Lock()
+	errCB := nc.Opts.AsyncErrorCB
+	if errCB != nil {
+		nc.ach.push(func() { errCB(nc, sub, err) })
+	}
+	nc.mu.Unlock()
+}
+
+// processControlFlow will automatically respond to control messages sent by the server.
+func (nc *Conn) processSequenceMismatch(msg *Msg, s *Subscription, jsi *jsSub) {
+	// Process heartbeat received, get latest control metadata if present.
+	jsi.mu.RLock()
+	ctrl := jsi.cmeta
+	jsi.mu.RUnlock()
+
+	if ctrl == _EMPTY_ {
+		return
+	}
+
+	tokens, err := getMetadataFields(ctrl)
+	if err != nil {
+		return
+	}
+
+	// Consumer sequence.
+	var ldseq string
+	dseq := tokens[6]
+	hdr := msg.Header[lastConsumerSeqHdr]
+	if len(hdr) == 1 {
+		ldseq = hdr[0]
+	}
+
+	// Detect consumer sequence mismatch and whether
+	// should restart the consumer.
+	if ldseq != dseq {
+		// Dispatch async error including details such as
+		// from where the consumer could be restarted.
+		sseq := parseNum(tokens[5])
+		ecs := &ErrConsumerSequenceMismatch{
+			StreamResumeSequence: uint64(sseq),
+			ConsumerSequence:     uint64(parseNum(dseq)),
+			LastConsumerSequence: uint64(parseNum(ldseq)),
+		}
+		nc.handleConsumerSequenceMismatch(s, ecs)
+	}
+}
+
+type streamRequest struct {
+	Subject string `json:"subject,omitempty"`
+}
+
+type streamNamesResponse struct {
+	apiResponse
+	apiPaged
+	Streams []string `json:"streams"`
+}
+
+func (js *js) lookupStreamBySubject(subj string) (string, error) {
+	var slr streamNamesResponse
+	req := &streamRequest{subj}
+	j, err := json.Marshal(req)
+	if err != nil {
+		return _EMPTY_, err
+	}
+	resp, err := js.nc.Request(js.apiSubj(apiStreams), j, js.opts.wait)
+	if err != nil {
+		if err == ErrNoResponders {
+			err = ErrJetStreamNotEnabled
+		}
+		return _EMPTY_, err
+	}
+	if err := json.Unmarshal(resp.Data, &slr); err != nil {
+		return _EMPTY_, err
+	}
+	if slr.Error != nil || len(slr.Streams) != 1 {
+		return _EMPTY_, ErrNoMatchingStream
+	}
+	return slr.Streams[0], nil
+}
+
+type subOpts struct {
+	// For attaching.
+	stream, consumer string
+	// For manual ack
+	mack bool
+	// For creating or updating.
+	cfg *ConsumerConfig
+}
+
+// ManualAck disables auto ack functionality for async subscriptions.
+func ManualAck() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.mack = true
+		return nil
+	})
+}
+
+// Durable defines the consumer name for JetStream durable subscribers.
+func Durable(name string) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		if opts.cfg.Durable != "" {
+			return fmt.Errorf("nats: option Durable set more than once")
+		}
+		if strings.Contains(name, ".") {
+			return ErrInvalidDurableName
+		}
+
+		opts.cfg.Durable = name
+		return nil
+	})
+}
+
+// DeliverAll will configure a Consumer to receive all the
+// messages from a Stream.
+func DeliverAll() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.DeliverPolicy = DeliverAllPolicy
+		return nil
+	})
+}
+
+// DeliverLast configures a Consumer to receive messages
+// starting with the latest one.
+func DeliverLast() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.DeliverPolicy = DeliverLastPolicy
+		return nil
+	})
+}
+
+// DeliverNew configures a Consumer to receive messages
+// published after the subscription.
+func DeliverNew() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.DeliverPolicy = DeliverNewPolicy
+		return nil
+	})
+}
+
+// StartSequence configures a Consumer to receive
+// messages from a start sequence.
+func StartSequence(seq uint64) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.DeliverPolicy = DeliverByStartSequencePolicy
+		opts.cfg.OptStartSeq = seq
+		return nil
+	})
+}
+
+// StartTime configures a Consumer to receive
+// messages from a start time.
+func StartTime(startTime time.Time) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.DeliverPolicy = DeliverByStartTimePolicy
+		opts.cfg.OptStartTime = &startTime
+		return nil
+	})
+}
+
+// AckNone requires no acks for delivered messages.
+func AckNone() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.AckPolicy = AckNonePolicy
+		return nil
+	})
+}
+
+// AckAll when acking a sequence number, this implicitly acks all sequences
+// below this one as well.
+func AckAll() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.AckPolicy = AckAllPolicy
+		return nil
+	})
+}
+
+// AckExplicit requires ack or nack for all messages.
+func AckExplicit() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.AckPolicy = AckExplicitPolicy
+		return nil
+	})
+}
+
+// MaxDeliver sets the number of redeliveries for a message.
+func MaxDeliver(n int) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.MaxDeliver = n
+		return nil
+	})
+}
+
+// MaxAckPending sets the number of outstanding acks that are allowed before
+// message delivery is halted.
+func MaxAckPending(n int) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.MaxAckPending = n
+		return nil
+	})
+}
+
+// ReplayOriginal replays the messages at the original speed.
+func ReplayOriginal() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.ReplayPolicy = ReplayOriginalPolicy
+		return nil
+	})
+}
+
+// RateLimit is the Bits per sec rate limit applied to a push consumer.
+func RateLimit(n uint64) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.RateLimit = n
+		return nil
+	})
+}
+
+// BindStream binds a consumer to a stream explicitly based on a name.
+func BindStream(name string) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.stream = name
+		return nil
+	})
+}
+
+// EnableFlowControl enables flow control for a push based consumer.
+func EnableFlowControl() SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.FlowControl = true
+		return nil
+	})
+}
+
+// IdleHeartbeat enables push based consumers to have idle heartbeats delivered.
+func IdleHeartbeat(duration time.Duration) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.Heartbeat = duration
+		return nil
+	})
+}
+
+func (sub *Subscription) ConsumerInfo() (*ConsumerInfo, error) {
+	sub.mu.Lock()
+	// TODO(dlc) - Better way to mark especially if we attach.
+	if sub.jsi.consumer == _EMPTY_ {
+		sub.mu.Unlock()
+		return nil, ErrTypeSubscription
+	}
+
+	// Consumer info lookup should fail if in direct mode.
+	js := sub.jsi.js
+	stream, consumer := sub.jsi.stream, sub.jsi.consumer
+	sub.mu.Unlock()
+
+	return js.getConsumerInfo(stream, consumer)
+}
+
+type pullOpts struct {
+	ttl time.Duration
+	ctx context.Context
+}
+
+// PullOpt are the options that can be passed when pulling a batch of messages.
+type PullOpt interface {
+	configurePull(opts *pullOpts) error
+}
+
+// PullMaxWaiting defines the max inflight pull requests.
+func PullMaxWaiting(n int) SubOpt {
+	return subOptFn(func(opts *subOpts) error {
+		opts.cfg.MaxWaiting = n
+		return nil
+	})
+}
+
+var errNoMessages = errors.New("nats: no messages")
+
+// Fetch pulls a batch of messages from a stream for a pull consumer.
+func (sub *Subscription) Fetch(batch int, opts ...PullOpt) ([]*Msg, error) {
+	if sub == nil {
+		return nil, ErrBadSubscription
+	}
+
+	var o pullOpts
+	for _, opt := range opts {
+		if err := opt.configurePull(&o); err != nil {
+			return nil, err
+		}
+	}
+	if o.ctx != nil && o.ttl != 0 {
+		return nil, ErrContextAndTimeout
+	}
+
+	sub.mu.Lock()
+	jsi := sub.jsi
+	if jsi == nil || sub.typ != PullSubscription {
+		sub.mu.Unlock()
+		return nil, ErrTypeSubscription
+	}
+
+	nc, _ := sub.conn, sub.Subject
+	stream, consumer := sub.jsi.stream, sub.jsi.consumer
+	js := sub.jsi.js
+
+	ttl := o.ttl
+	if ttl == 0 {
+		ttl = js.opts.wait
+	}
+	sub.mu.Unlock()
+
+	// Use the given context or setup a default one for the span
+	// of the pull batch request.
+	var (
+		ctx    = o.ctx
+		err    error
+		cancel context.CancelFunc
+	)
+	if o.ctx == nil {
+		ctx, cancel = context.WithTimeout(context.Background(), ttl)
+		defer cancel()
+	}
+
+	// Check if context not done already before making the request.
+	select {
+	case <-ctx.Done():
+		if ctx.Err() == context.Canceled {
+			err = ctx.Err()
+		} else {
+			err = ErrTimeout
+		}
+	default:
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	// Check for empty payload message and process synchronously
+	// any status messages.
+	checkMsg := func(msg *Msg) error {
+		if len(msg.Data) == 0 {
+			switch msg.Header.Get(statusHdr) {
+			case noResponders:
+				return ErrNoResponders
+			case noMessages:
+				return errNoMessages
+			case "400", "408", "409":
+				return fmt.Errorf("nats: %s", msg.Header.Get(descrHdr))
+			}
+		}
+		return nil
+	}
+
+	checkCtxErr := func(err error) error {
+		if o.ctx == nil && err == context.DeadlineExceeded {
+			return ErrTimeout
+		}
+		return err
+	}
+
+	var (
+		gotNoMessages bool
+		nr            = &nextRequest{Batch: batch, NoWait: true}
+		req, _        = json.Marshal(nr)
+		reqNext       = js.apiSubj(fmt.Sprintf(apiRequestNextT, stream, consumer))
+		expires       = ttl - 10*time.Millisecond
+		msgs          = make([]*Msg, 0)
+	)
+
+	if batch == 1 {
+		// To optimize single message no wait fetch, we use a shared wildcard
+		// subscription per pull subscriber to wait for the response.
+		resp, err := jsi.fetchNoWait(ctx, reqNext, req)
+		if err != nil {
+			return nil, checkCtxErr(err)
+		}
+
+		// In case of a no messages instant error, then fallback
+		// into longer version of pull batch request.
+		err = checkMsg(resp)
+		if err != nil {
+			if err == errNoMessages {
+				// Use old request style for the retry of the pull request
+				// in order to use auto UNSUB 1 to prevent the server
+				// from delivering a message when there is no more interest.
+				nr.NoWait = false
+				nr.Expires = expires
+				req, _ = json.Marshal(nr)
+				resp, err = nc.oldRequestWithContext(ctx, reqNext, nil, req)
+				if err != nil {
+					return nil, checkCtxErr(err)
+				}
+
+				// This next message, could also be an error
+				// (e.g. 408 due to request timeout).
+				err = checkMsg(resp)
+				if err != nil {
+					return nil, err
+				}
+				return []*Msg{resp}, nil
+			} else {
+				// Hard error
+				return nil, checkCtxErr(err)
+			}
+		}
+		return []*Msg{resp}, nil
+	}
+
+	// Setup a request where we will wait for the first response
+	// in case of errors, then dispatch the rest of the replies
+	// to the channel.
+	inbox := NewInbox()
+
+	mch := make(chan *Msg, batch)
+	s, err := nc.subscribe(inbox, _EMPTY_, nil, mch, true, nil)
+	if err != nil {
+		return nil, err
+	}
+
+	// Remove interest in the subscription at the end so that the
+	// this inbox does not get delivered the results intended
+	// for another request.
+	defer s.Unsubscribe()
+
+	// Make a publish request to get results of the pull.
+	err = nc.publish(reqNext, inbox, nil, req)
+	if err != nil {
+		s.Unsubscribe()
+		return nil, err
+	}
+
+	// Try to get the first message or error with NoWait.
+	var (
+		firstMsg *Msg
+		ok       bool
+	)
+	select {
+	case firstMsg, ok = <-mch:
+		if !ok {
+			err = s.getNextMsgErr()
+		} else {
+			err = s.processNextMsgDelivered(firstMsg)
+			if err == nil {
+				err = checkMsg(firstMsg)
+			}
+		}
+	case <-ctx.Done():
+		err = checkCtxErr(ctx.Err())
+	}
+
+	// If the first error is 'no more messages', then switch into
+	// longer form version of the request that waits for messages.
+	if err == errNoMessages {
+		gotNoMessages = true
+	} else if err != nil {
+		// We should be getting the response from the server
+		// in case we got a poll error, so stop and cleanup.
+		s.Unsubscribe()
+		return nil, err
+	}
+
+	if gotNoMessages {
+		// We started with a 404 response right away, so fallback into
+		// second request that waits longer for messages to delivered.
+		nr.NoWait = false
+		nr.Expires = expires
+		req, _ = json.Marshal(nr)
+
+		// Since first message was an error we UNSUB (batch+1)
+		// since we are counting it as the first message.
+		err = s.AutoUnsubscribe(batch + 1)
+		if err != nil {
+			return nil, err
+		}
+
+		// Make another request and wait for the messages...
+		err = nc.publish(reqNext, inbox, nil, req)
+		if err != nil {
+			s.Unsubscribe()
+			return nil, err
+		}
+
+		// Try to get the first result again or return the error.
+		select {
+		case firstMsg, ok = <-mch:
+			if !ok {
+				err = s.getNextMsgErr()
+			} else {
+				err = s.processNextMsgDelivered(firstMsg)
+				if err == nil {
+					err = checkMsg(firstMsg)
+				}
+			}
+		case <-ctx.Done():
+			err = checkCtxErr(ctx.Err())
+		}
+		if err != nil {
+			s.Unsubscribe()
+			return nil, err
+		}
+		// Check again if the delivered next message is a status error.
+		err = checkMsg(firstMsg)
+		if err != nil {
+			s.Unsubscribe()
+			return nil, err
+		}
+	} else {
+		// We are receiving messages at this point. Send UNSUB to let
+		// the server clear interest once enough replies are delivered.
+		err = s.AutoUnsubscribe(batch)
+		if err != nil {
+			return nil, err
+		}
+	}
+
+	msgs = append(msgs, firstMsg)
+	for {
+		var (
+			msg *Msg
+			ok  bool
+		)
+		select {
+		case msg, ok = <-mch:
+			if !ok {
+				err = s.getNextMsgErr()
+			} else {
+				err = s.processNextMsgDelivered(msg)
+				if err == nil {
+					err = checkMsg(msg)
+				}
+			}
+		case <-ctx.Done():
+			return msgs, checkCtxErr(err)
+		}
+		if err != nil {
+			// Discard the error which may have been a timeout
+			// or 408 request timeout status from the server,
+			// and just the return delivered messages.
+			break
+		}
+		if msg != nil {
+			msgs = append(msgs, msg)
+		}
+
+		if len(msgs) == batch {
+			// Done!
+			break
+		}
+	}
+
+	return msgs, nil
+}
+
+func (js *js) getConsumerInfo(stream, consumer string) (*ConsumerInfo, error) {
+	ctx, cancel := context.WithTimeout(context.Background(), js.opts.wait)
+	defer cancel()
+	return js.getConsumerInfoContext(ctx, stream, consumer)
+}
+
+func (js *js) getConsumerInfoContext(ctx context.Context, stream, consumer string) (*ConsumerInfo, error) {
+	ccInfoSubj := fmt.Sprintf(apiConsumerInfoT, stream, consumer)
+	resp, err := js.nc.RequestWithContext(ctx, js.apiSubj(ccInfoSubj), nil)
+	if err != nil {
+		if err == ErrNoResponders {
+			err = ErrJetStreamNotEnabled
+		}
+		return nil, err
+	}
+
+	var info consumerResponse
+	if err := json.Unmarshal(resp.Data, &info); err != nil {
+		return nil, err
+	}
+	if info.Error != nil {
+		return nil, fmt.Errorf("nats: %s", info.Error.Description)
+	}
+	return info.ConsumerInfo, nil
+}
+
+func (m *Msg) checkReply() (*js, *jsSub, error) {
+	if m == nil || m.Sub == nil {
+		return nil, nil, ErrMsgNotBound
+	}
+	if m.Reply == "" {
+		return nil, nil, ErrMsgNoReply
+	}
+	sub := m.Sub
+	sub.mu.Lock()
+	if sub.jsi == nil {
+		sub.mu.Unlock()
+
+		// Not using a JS context.
+		return nil, nil, nil
+	}
+	js := sub.jsi.js
+	jsi := sub.jsi
+	sub.mu.Unlock()
+
+	return js, jsi, nil
+}
+
+// ackReply handles all acks. Will do the right thing for pull and sync mode.
+// It ensures that an ack is only sent a single time, regardless of
+// how many times it is being called to avoid duplicated acks.
+func (m *Msg) ackReply(ackType []byte, sync bool, opts ...AckOpt) error {
+	var o ackOpts
+	for _, opt := range opts {
+		if err := opt.configureAck(&o); err != nil {
+			return err
+		}
+	}
+
+	js, _, err := m.checkReply()
+	if err != nil {
+		return err
+	}
+
+	// Skip if already acked.
+	if atomic.LoadUint32(&m.ackd) == 1 {
+		return ErrInvalidJSAck
+	}
+
+	m.Sub.mu.Lock()
+	nc := m.Sub.conn
+	m.Sub.mu.Unlock()
+
+	usesCtx := o.ctx != nil
+	usesWait := o.ttl > 0
+	sync = sync || usesCtx || usesWait
+	ctx := o.ctx
+	wait := defaultRequestWait
+	if usesWait {
+		wait = o.ttl
+	} else if js != nil {
+		wait = js.opts.wait
+	}
+
+	if sync {
+		if usesCtx {
+			_, err = nc.RequestWithContext(ctx, m.Reply, ackType)
+		} else {
+			_, err = nc.Request(m.Reply, ackType, wait)
+		}
+	} else {
+		err = nc.Publish(m.Reply, ackType)
+	}
+
+	// Mark that the message has been acked unless it is AckProgress
+	// which can be sent many times.
+	if err == nil && !bytes.Equal(ackType, ackProgress) {
+		atomic.StoreUint32(&m.ackd, 1)
+	}
+
+	return err
+}
+
+// Ack acknowledges a message. This tells the server that the message was
+// successfully processed and it can move on to the next message.
+func (m *Msg) Ack(opts ...AckOpt) error {
+	return m.ackReply(ackAck, false, opts...)
+}
+
+// Ack is the synchronous version of Ack. This indicates successful message
+// processing.
+func (m *Msg) AckSync(opts ...AckOpt) error {
+	return m.ackReply(ackAck, true, opts...)
+}
+
+// Nak negatively acknowledges a message. This tells the server to redeliver
+// the message. You can configure the number of redeliveries by passing
+// nats.MaxDeliver when you Subscribe. The default is infinite redeliveries.
+func (m *Msg) Nak(opts ...AckOpt) error {
+	return m.ackReply(ackNak, false, opts...)
+}
+
+// Term tells the server to not redeliver this message, regardless of the value
+// of nats.MaxDeliver.
+func (m *Msg) Term(opts ...AckOpt) error {
+	return m.ackReply(ackTerm, false, opts...)
+}
+
+// InProgress tells the server that this message is being worked on. It resets
+// the redelivery timer on the server.
+func (m *Msg) InProgress(opts ...AckOpt) error {
+	return m.ackReply(ackProgress, false, opts...)
+}
+
+// MsgMetadata is the JetStream metadata associated with received messages.
+type MsgMetadata struct {
+	Sequence     SequencePair
+	NumDelivered uint64
+	NumPending   uint64
+	Timestamp    time.Time
+	Stream       string
+	Consumer     string
+}
+
+func getMetadataFields(subject string) ([]string, error) {
+	const expectedTokens = 9
+	const btsep = '.'
+
+	tsa := [expectedTokens]string{}
+	start, tokens := 0, tsa[:0]
+	for i := 0; i < len(subject); i++ {
+		if subject[i] == btsep {
+			tokens = append(tokens, subject[start:i])
+			start = i + 1
+		}
+	}
+	tokens = append(tokens, subject[start:])
+	if len(tokens) != expectedTokens || tokens[0] != "$JS" || tokens[1] != "ACK" {
+		return nil, ErrNotJSMessage
+	}
+	return tokens, nil
+}
+
+// Metadata retrieves the metadata from a JetStream message. This method will
+// return an error for non-JetStream Msgs.
+func (m *Msg) Metadata() (*MsgMetadata, error) {
+	if _, _, err := m.checkReply(); err != nil {
+		return nil, err
+	}
+
+	tokens, err := getMetadataFields(m.Reply)
+	if err != nil {
+		return nil, err
+	}
+
+	meta := &MsgMetadata{
+		NumDelivered: uint64(parseNum(tokens[4])),
+		NumPending:   uint64(parseNum(tokens[8])),
+		Timestamp:    time.Unix(0, parseNum(tokens[7])),
+		Stream:       tokens[2],
+		Consumer:     tokens[3],
+	}
+	meta.Sequence.Stream = uint64(parseNum(tokens[5]))
+	meta.Sequence.Consumer = uint64(parseNum(tokens[6]))
+	return meta, nil
+}
+
+// Quick parser for positive numbers in ack reply encoding.
+func parseNum(d string) (n int64) {
+	if len(d) == 0 {
+		return -1
+	}
+
+	// Ascii numbers 0-9
+	const (
+		asciiZero = 48
+		asciiNine = 57
+	)
+
+	for _, dec := range d {
+		if dec < asciiZero || dec > asciiNine {
+			return -1
+		}
+		n = n*10 + (int64(dec) - asciiZero)
+	}
+	return n
+}
+
+// AckPolicy determines how the consumer should acknowledge delivered messages.
+type AckPolicy int
+
+const (
+	// AckNonePolicy requires no acks for delivered messages.
+	AckNonePolicy AckPolicy = iota
+
+	// AckAllPolicy when acking a sequence number, this implicitly acks all
+	// sequences below this one as well.
+	AckAllPolicy
+
+	// AckExplicitPolicy requires ack or nack for all messages.
+	AckExplicitPolicy
+
+	// For setting
+	ackPolicyNotSet = 99
+)
+
+func jsonString(s string) string {
+	return "\"" + s + "\""
+}
+
+func (p *AckPolicy) UnmarshalJSON(data []byte) error {
+	switch string(data) {
+	case jsonString("none"):
+		*p = AckNonePolicy
+	case jsonString("all"):
+		*p = AckAllPolicy
+	case jsonString("explicit"):
+		*p = AckExplicitPolicy
+	default:
+		return fmt.Errorf("nats: can not unmarshal %q", data)
+	}
+
+	return nil
+}
+
+func (p AckPolicy) MarshalJSON() ([]byte, error) {
+	switch p {
+	case AckNonePolicy:
+		return json.Marshal("none")
+	case AckAllPolicy:
+		return json.Marshal("all")
+	case AckExplicitPolicy:
+		return json.Marshal("explicit")
+	default:
+		return nil, fmt.Errorf("nats: unknown acknowlegement policy %v", p)
+	}
+}
+
+func (p AckPolicy) String() string {
+	switch p {
+	case AckNonePolicy:
+		return "AckNone"
+	case AckAllPolicy:
+		return "AckAll"
+	case AckExplicitPolicy:
+		return "AckExplicit"
+	case ackPolicyNotSet:
+		return "Not Initialized"
+	default:
+		return "Unknown AckPolicy"
+	}
+}
+
+// ReplayPolicy determines how the consumer should replay messages it already has queued in the stream.
+type ReplayPolicy int
+
+const (
+	// ReplayInstantPolicy will replay messages as fast as possible.
+	ReplayInstantPolicy ReplayPolicy = iota
+
+	// ReplayOriginalPolicy will maintain the same timing as the messages were received.
+	ReplayOriginalPolicy
+)
+
+func (p *ReplayPolicy) UnmarshalJSON(data []byte) error {
+	switch string(data) {
+	case jsonString("instant"):
+		*p = ReplayInstantPolicy
+	case jsonString("original"):
+		*p = ReplayOriginalPolicy
+	default:
+		return fmt.Errorf("nats: can not unmarshal %q", data)
+	}
+
+	return nil
+}
+
+func (p ReplayPolicy) MarshalJSON() ([]byte, error) {
+	switch p {
+	case ReplayOriginalPolicy:
+		return json.Marshal("original")
+	case ReplayInstantPolicy:
+		return json.Marshal("instant")
+	default:
+		return nil, fmt.Errorf("nats: unknown replay policy %v", p)
+	}
+}
+
+var (
+	ackAck      = []byte("+ACK")
+	ackNak      = []byte("-NAK")
+	ackProgress = []byte("+WPI")
+	ackTerm     = []byte("+TERM")
+)
+
+// DeliverPolicy determines how the consumer should select the first message to deliver.
+type DeliverPolicy int
+
+const (
+	// DeliverAllPolicy starts delivering messages from the very beginning of a
+	// stream. This is the default.
+	DeliverAllPolicy DeliverPolicy = iota
+
+	// DeliverLastPolicy will start the consumer with the last sequence
+	// received.
+	DeliverLastPolicy
+
+	// DeliverNewPolicy will only deliver new messages that are sent after the
+	// consumer is created.
+	DeliverNewPolicy
+
+	// DeliverByStartTimePolicy will deliver messages starting from a given
+	// sequence.
+	DeliverByStartSequencePolicy
+
+	// DeliverByStartTimePolicy will deliver messages starting from a given
+	// time.
+	DeliverByStartTimePolicy
+)
+
+func (p *DeliverPolicy) UnmarshalJSON(data []byte) error {
+	switch string(data) {
+	case jsonString("all"), jsonString("undefined"):
+		*p = DeliverAllPolicy
+	case jsonString("last"):
+		*p = DeliverLastPolicy
+	case jsonString("new"):
+		*p = DeliverNewPolicy
+	case jsonString("by_start_sequence"):
+		*p = DeliverByStartSequencePolicy
+	case jsonString("by_start_time"):
+		*p = DeliverByStartTimePolicy
+	}
+
+	return nil
+}
+
+func (p DeliverPolicy) MarshalJSON() ([]byte, error) {
+	switch p {
+	case DeliverAllPolicy:
+		return json.Marshal("all")
+	case DeliverLastPolicy:
+		return json.Marshal("last")
+	case DeliverNewPolicy:
+		return json.Marshal("new")
+	case DeliverByStartSequencePolicy:
+		return json.Marshal("by_start_sequence")
+	case DeliverByStartTimePolicy:
+		return json.Marshal("by_start_time")
+	default:
+		return nil, fmt.Errorf("nats: unknown deliver policy %v", p)
+	}
+}
+
+// RetentionPolicy determines how messages in a set are retained.
+type RetentionPolicy int
+
+const (
+	// LimitsPolicy (default) means that messages are retained until any given limit is reached.
+	// This could be one of MaxMsgs, MaxBytes, or MaxAge.
+	LimitsPolicy RetentionPolicy = iota
+	// InterestPolicy specifies that when all known observables have acknowledged a message it can be removed.
+	InterestPolicy
+	// WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed.
+	WorkQueuePolicy
+)
+
+// DiscardPolicy determines how to proceed when limits of messages or bytes are
+// reached.
+type DiscardPolicy int
+
+const (
+	// DiscardOld will remove older messages to return to the limits. This is
+	// the default.
+	DiscardOld DiscardPolicy = iota
+	//DiscardNew will fail to store new messages.
+	DiscardNew
+)
+
+const (
+	limitsPolicyString    = "limits"
+	interestPolicyString  = "interest"
+	workQueuePolicyString = "workqueue"
+)
+
+func (rp RetentionPolicy) String() string {
+	switch rp {
+	case LimitsPolicy:
+		return "Limits"
+	case InterestPolicy:
+		return "Interest"
+	case WorkQueuePolicy:
+		return "WorkQueue"
+	default:
+		return "Unknown Retention Policy"
+	}
+}
+
+func (rp RetentionPolicy) MarshalJSON() ([]byte, error) {
+	switch rp {
+	case LimitsPolicy:
+		return json.Marshal(limitsPolicyString)
+	case InterestPolicy:
+		return json.Marshal(interestPolicyString)
+	case WorkQueuePolicy:
+		return json.Marshal(workQueuePolicyString)
+	default:
+		return nil, fmt.Errorf("nats: can not marshal %v", rp)
+	}
+}
+
+func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error {
+	switch string(data) {
+	case jsonString(limitsPolicyString):
+		*rp = LimitsPolicy
+	case jsonString(interestPolicyString):
+		*rp = InterestPolicy
+	case jsonString(workQueuePolicyString):
+		*rp = WorkQueuePolicy
+	default:
+		return fmt.Errorf("nats: can not unmarshal %q", data)
+	}
+	return nil
+}
+
+func (dp DiscardPolicy) String() string {
+	switch dp {
+	case DiscardOld:
+		return "DiscardOld"
+	case DiscardNew:
+		return "DiscardNew"
+	default:
+		return "Unknown Discard Policy"
+	}
+}
+
+func (dp DiscardPolicy) MarshalJSON() ([]byte, error) {
+	switch dp {
+	case DiscardOld:
+		return json.Marshal("old")
+	case DiscardNew:
+		return json.Marshal("new")
+	default:
+		return nil, fmt.Errorf("nats: can not marshal %v", dp)
+	}
+}
+
+func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error {
+	switch strings.ToLower(string(data)) {
+	case jsonString("old"):
+		*dp = DiscardOld
+	case jsonString("new"):
+		*dp = DiscardNew
+	default:
+		return fmt.Errorf("nats: can not unmarshal %q", data)
+	}
+	return nil
+}
+
+// StorageType determines how messages are stored for retention.
+type StorageType int
+
+const (
+	// FileStorage specifies on disk storage. It's the default.
+	FileStorage StorageType = iota
+	// MemoryStorage specifies in memory only.
+	MemoryStorage
+)
+
+const (
+	memoryStorageString = "memory"
+	fileStorageString   = "file"
+)
+
+func (st StorageType) String() string {
+	switch st {
+	case MemoryStorage:
+		return strings.Title(memoryStorageString)
+	case FileStorage:
+		return strings.Title(fileStorageString)
+	default:
+		return "Unknown Storage Type"
+	}
+}
+
+func (st StorageType) MarshalJSON() ([]byte, error) {
+	switch st {
+	case MemoryStorage:
+		return json.Marshal(memoryStorageString)
+	case FileStorage:
+		return json.Marshal(fileStorageString)
+	default:
+		return nil, fmt.Errorf("nats: can not marshal %v", st)
+	}
+}
+
+func (st *StorageType) UnmarshalJSON(data []byte) error {
+	switch string(data) {
+	case jsonString(memoryStorageString):
+		*st = MemoryStorage
+	case jsonString(fileStorageString):
+		*st = FileStorage
+	default:
+		return fmt.Errorf("nats: can not unmarshal %q", data)
+	}
+	return nil
+}

+ 1077 - 0
vendor/github.com/nats-io/nats.go/jsm.go

@@ -0,0 +1,1077 @@
+// Copyright 2021 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package nats
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"strings"
+	"time"
+)
+
+// JetStreamManager manages JetStream Streams and Consumers.
+type JetStreamManager interface {
+	// AddStream creates a stream.
+	AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error)
+
+	// UpdateStream updates a stream.
+	UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error)
+
+	// DeleteStream deletes a stream.
+	DeleteStream(name string, opts ...JSOpt) error
+
+	// StreamInfo retrieves information from a stream.
+	StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error)
+
+	// PurgeStream purges a stream messages.
+	PurgeStream(name string, opts ...JSOpt) error
+
+	// StreamsInfo can be used to retrieve a list of StreamInfo objects.
+	StreamsInfo(opts ...JSOpt) <-chan *StreamInfo
+
+	// StreamNames is used to retrieve a list of Stream names.
+	StreamNames(opts ...JSOpt) <-chan string
+
+	// GetMsg retrieves a raw stream message stored in JetStream by sequence number.
+	GetMsg(name string, seq uint64, opts ...JSOpt) (*RawStreamMsg, error)
+
+	// DeleteMsg erases a message from a stream.
+	DeleteMsg(name string, seq uint64, opts ...JSOpt) error
+
+	// AddConsumer adds a consumer to a stream.
+	AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error)
+
+	// DeleteConsumer deletes a consumer.
+	DeleteConsumer(stream, consumer string, opts ...JSOpt) error
+
+	// ConsumerInfo retrieves information of a consumer from a stream.
+	ConsumerInfo(stream, name string, opts ...JSOpt) (*ConsumerInfo, error)
+
+	// ConsumersInfo is used to retrieve a list of ConsumerInfo objects.
+	ConsumersInfo(stream string, opts ...JSOpt) <-chan *ConsumerInfo
+
+	// ConsumerNames is used to retrieve a list of Consumer names.
+	ConsumerNames(stream string, opts ...JSOpt) <-chan string
+
+	// AccountInfo retrieves info about the JetStream usage from an account.
+	AccountInfo(opts ...JSOpt) (*AccountInfo, error)
+}
+
+// StreamConfig will determine the properties for a stream.
+// There are sensible defaults for most. If no subjects are
+// given the name will be used as the only subject.
+type StreamConfig struct {
+	Name         string          `json:"name"`
+	Subjects     []string        `json:"subjects,omitempty"`
+	Retention    RetentionPolicy `json:"retention"`
+	MaxConsumers int             `json:"max_consumers"`
+	MaxMsgs      int64           `json:"max_msgs"`
+	MaxBytes     int64           `json:"max_bytes"`
+	Discard      DiscardPolicy   `json:"discard"`
+	MaxAge       time.Duration   `json:"max_age"`
+	MaxMsgSize   int32           `json:"max_msg_size,omitempty"`
+	Storage      StorageType     `json:"storage"`
+	Replicas     int             `json:"num_replicas"`
+	NoAck        bool            `json:"no_ack,omitempty"`
+	Template     string          `json:"template_owner,omitempty"`
+	Duplicates   time.Duration   `json:"duplicate_window,omitempty"`
+	Placement    *Placement      `json:"placement,omitempty"`
+	Mirror       *StreamSource   `json:"mirror,omitempty"`
+	Sources      []*StreamSource `json:"sources,omitempty"`
+}
+
+// Placement is used to guide placement of streams in clustered JetStream.
+type Placement struct {
+	Cluster string   `json:"cluster"`
+	Tags    []string `json:"tags,omitempty"`
+}
+
+// StreamSource dictates how streams can source from other streams.
+type StreamSource struct {
+	Name          string          `json:"name"`
+	OptStartSeq   uint64          `json:"opt_start_seq,omitempty"`
+	OptStartTime  *time.Time      `json:"opt_start_time,omitempty"`
+	FilterSubject string          `json:"filter_subject,omitempty"`
+	External      *ExternalStream `json:"external,omitempty"`
+}
+
+// ExternalStream allows you to qualify access to a stream source in another
+// account.
+type ExternalStream struct {
+	APIPrefix     string `json:"api"`
+	DeliverPrefix string `json:"deliver"`
+}
+
+// apiError is included in all API responses if there was an error.
+type apiError struct {
+	Code        int    `json:"code"`
+	Description string `json:"description,omitempty"`
+}
+
+// apiResponse is a standard response from the JetStream JSON API
+type apiResponse struct {
+	Type  string    `json:"type"`
+	Error *apiError `json:"error,omitempty"`
+}
+
+// apiPaged includes variables used to create paged responses from the JSON API
+type apiPaged struct {
+	Total  int `json:"total"`
+	Offset int `json:"offset"`
+	Limit  int `json:"limit"`
+}
+
+// apiPagedRequest includes parameters allowing specific pages to be requested
+// from APIs responding with apiPaged.
+type apiPagedRequest struct {
+	Offset int `json:"offset"`
+}
+
+// AccountInfo contains info about the JetStream usage from the current account.
+type AccountInfo struct {
+	Memory    uint64        `json:"memory"`
+	Store     uint64        `json:"storage"`
+	Streams   int           `json:"streams"`
+	Consumers int           `json:"consumers"`
+	API       APIStats      `json:"api"`
+	Limits    AccountLimits `json:"limits"`
+}
+
+// APIStats reports on API calls to JetStream for this account.
+type APIStats struct {
+	Total  uint64 `json:"total"`
+	Errors uint64 `json:"errors"`
+}
+
+// AccountLimits includes the JetStream limits of the current account.
+type AccountLimits struct {
+	MaxMemory    int64 `json:"max_memory"`
+	MaxStore     int64 `json:"max_storage"`
+	MaxStreams   int   `json:"max_streams"`
+	MaxConsumers int   `json:"max_consumers"`
+}
+
+type accountInfoResponse struct {
+	apiResponse
+	AccountInfo
+}
+
+// AccountInfo retrieves info about the JetStream usage from the current account.
+func (js *js) AccountInfo(opts ...JSOpt) (*AccountInfo, error) {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	resp, err := js.nc.RequestWithContext(o.ctx, js.apiSubj(apiAccountInfo), nil)
+	if err != nil {
+		return nil, err
+	}
+	var info accountInfoResponse
+	if err := json.Unmarshal(resp.Data, &info); err != nil {
+		return nil, err
+	}
+	if info.Error != nil {
+		var err error
+		if strings.Contains(info.Error.Description, "not enabled for") {
+			err = ErrJetStreamNotEnabled
+		} else {
+			err = errors.New(info.Error.Description)
+		}
+		return nil, err
+	}
+
+	return &info.AccountInfo, nil
+}
+
+type createConsumerRequest struct {
+	Stream string          `json:"stream_name"`
+	Config *ConsumerConfig `json:"config"`
+}
+
+type consumerResponse struct {
+	apiResponse
+	*ConsumerInfo
+}
+
+// AddConsumer will add a JetStream consumer.
+func (js *js) AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if stream == _EMPTY_ {
+		return nil, ErrStreamNameRequired
+	}
+	req, err := json.Marshal(&createConsumerRequest{Stream: stream, Config: cfg})
+	if err != nil {
+		return nil, err
+	}
+
+	var ccSubj string
+	if cfg != nil && cfg.Durable != _EMPTY_ {
+		if strings.Contains(cfg.Durable, ".") {
+			return nil, ErrInvalidDurableName
+		}
+		ccSubj = fmt.Sprintf(apiDurableCreateT, stream, cfg.Durable)
+	} else {
+		ccSubj = fmt.Sprintf(apiConsumerCreateT, stream)
+	}
+
+	resp, err := js.nc.RequestWithContext(o.ctx, js.apiSubj(ccSubj), req)
+	if err != nil {
+		if err == ErrNoResponders {
+			err = ErrJetStreamNotEnabled
+		}
+		return nil, err
+	}
+	var info consumerResponse
+	err = json.Unmarshal(resp.Data, &info)
+	if err != nil {
+		return nil, err
+	}
+	if info.Error != nil {
+		return nil, errors.New(info.Error.Description)
+	}
+	return info.ConsumerInfo, nil
+}
+
+// consumerDeleteResponse is the response for a Consumer delete request.
+type consumerDeleteResponse struct {
+	apiResponse
+	Success bool `json:"success,omitempty"`
+}
+
+// DeleteConsumer deletes a Consumer.
+func (js *js) DeleteConsumer(stream, consumer string, opts ...JSOpt) error {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if stream == _EMPTY_ {
+		return ErrStreamNameRequired
+	}
+
+	dcSubj := js.apiSubj(fmt.Sprintf(apiConsumerDeleteT, stream, consumer))
+	r, err := js.nc.RequestWithContext(o.ctx, dcSubj, nil)
+	if err != nil {
+		return err
+	}
+	var resp consumerDeleteResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return err
+	}
+	if resp.Error != nil {
+		return errors.New(resp.Error.Description)
+	}
+	return nil
+}
+
+// ConsumerInfo returns information about a Consumer.
+func (js *js) ConsumerInfo(stream, consumer string, opts ...JSOpt) (*ConsumerInfo, error) {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+	return js.getConsumerInfoContext(o.ctx, stream, consumer)
+}
+
+// consumerLister fetches pages of ConsumerInfo objects. This object is not
+// safe to use for multiple threads.
+type consumerLister struct {
+	stream string
+	js     *js
+
+	err      error
+	offset   int
+	page     []*ConsumerInfo
+	pageInfo *apiPaged
+}
+
+// consumersRequest is the type used for Consumers requests.
+type consumersRequest struct {
+	apiPagedRequest
+}
+
+// consumerListResponse is the response for a Consumers List request.
+type consumerListResponse struct {
+	apiResponse
+	apiPaged
+	Consumers []*ConsumerInfo `json:"consumers"`
+}
+
+// Next fetches the next ConsumerInfo page.
+func (c *consumerLister) Next() bool {
+	if c.err != nil {
+		return false
+	}
+	if c.stream == _EMPTY_ {
+		c.err = ErrStreamNameRequired
+		return false
+	}
+	if c.pageInfo != nil && c.offset >= c.pageInfo.Total {
+		return false
+	}
+
+	req, err := json.Marshal(consumersRequest{
+		apiPagedRequest: apiPagedRequest{Offset: c.offset},
+	})
+	if err != nil {
+		c.err = err
+		return false
+	}
+
+	var cancel context.CancelFunc
+	ctx := c.js.opts.ctx
+	if ctx == nil {
+		ctx, cancel = context.WithTimeout(context.Background(), c.js.opts.wait)
+		defer cancel()
+	}
+
+	clSubj := c.js.apiSubj(fmt.Sprintf(apiConsumerListT, c.stream))
+	r, err := c.js.nc.RequestWithContext(ctx, clSubj, req)
+	if err != nil {
+		c.err = err
+		return false
+	}
+	var resp consumerListResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		c.err = err
+		return false
+	}
+	if resp.Error != nil {
+		c.err = errors.New(resp.Error.Description)
+		return false
+	}
+
+	c.pageInfo = &resp.apiPaged
+	c.page = resp.Consumers
+	c.offset += len(c.page)
+	return true
+}
+
+// Page returns the current ConsumerInfo page.
+func (c *consumerLister) Page() []*ConsumerInfo {
+	return c.page
+}
+
+// Err returns any errors found while fetching pages.
+func (c *consumerLister) Err() error {
+	return c.err
+}
+
+// ConsumersInfo is used to retrieve a list of ConsumerInfo objects.
+func (jsc *js) ConsumersInfo(stream string, opts ...JSOpt) <-chan *ConsumerInfo {
+	o, cancel, err := getJSContextOpts(jsc.opts, opts...)
+	if err != nil {
+		return nil
+	}
+
+	ch := make(chan *ConsumerInfo)
+	l := &consumerLister{js: &js{nc: jsc.nc, opts: o}, stream: stream}
+	go func() {
+		if cancel != nil {
+			defer cancel()
+		}
+		defer close(ch)
+		for l.Next() {
+			for _, info := range l.Page() {
+				select {
+				case ch <- info:
+				case <-o.ctx.Done():
+					return
+				}
+			}
+		}
+	}()
+
+	return ch
+}
+
+type consumerNamesLister struct {
+	stream string
+	js     *js
+
+	err      error
+	offset   int
+	page     []string
+	pageInfo *apiPaged
+}
+
+// consumerNamesListResponse is the response for a Consumers Names List request.
+type consumerNamesListResponse struct {
+	apiResponse
+	apiPaged
+	Consumers []string `json:"consumers"`
+}
+
+// Next fetches the next ConsumerInfo page.
+func (c *consumerNamesLister) Next() bool {
+	if c.err != nil {
+		return false
+	}
+	if c.stream == _EMPTY_ {
+		c.err = ErrStreamNameRequired
+		return false
+	}
+	if c.pageInfo != nil && c.offset >= c.pageInfo.Total {
+		return false
+	}
+
+	var cancel context.CancelFunc
+	ctx := c.js.opts.ctx
+	if ctx == nil {
+		ctx, cancel = context.WithTimeout(context.Background(), c.js.opts.wait)
+		defer cancel()
+	}
+
+	clSubj := c.js.apiSubj(fmt.Sprintf(apiConsumerNamesT, c.stream))
+	r, err := c.js.nc.RequestWithContext(ctx, clSubj, nil)
+	if err != nil {
+		c.err = err
+		return false
+	}
+	var resp consumerNamesListResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		c.err = err
+		return false
+	}
+	if resp.Error != nil {
+		c.err = errors.New(resp.Error.Description)
+		return false
+	}
+
+	c.pageInfo = &resp.apiPaged
+	c.page = resp.Consumers
+	c.offset += len(c.page)
+	return true
+}
+
+// Page returns the current ConsumerInfo page.
+func (c *consumerNamesLister) Page() []string {
+	return c.page
+}
+
+// Err returns any errors found while fetching pages.
+func (c *consumerNamesLister) Err() error {
+	return c.err
+}
+
+// ConsumerNames is used to retrieve a list of Consumer names.
+func (jsc *js) ConsumerNames(stream string, opts ...JSOpt) <-chan string {
+	o, cancel, err := getJSContextOpts(jsc.opts, opts...)
+	if err != nil {
+		return nil
+	}
+
+	ch := make(chan string)
+	l := &consumerNamesLister{stream: stream, js: &js{nc: jsc.nc, opts: o}}
+	go func() {
+		if cancel != nil {
+			defer cancel()
+		}
+		defer close(ch)
+		for l.Next() {
+			for _, info := range l.Page() {
+				select {
+				case ch <- info:
+				case <-o.ctx.Done():
+					return
+				}
+			}
+		}
+	}()
+
+	return ch
+}
+
+// streamCreateResponse stream creation.
+type streamCreateResponse struct {
+	apiResponse
+	*StreamInfo
+}
+
+func (js *js) AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if cfg == nil || cfg.Name == _EMPTY_ {
+		return nil, ErrStreamNameRequired
+	}
+
+	if strings.Contains(cfg.Name, ".") {
+		return nil, ErrInvalidStreamName
+	}
+
+	req, err := json.Marshal(cfg)
+	if err != nil {
+		return nil, err
+	}
+
+	csSubj := js.apiSubj(fmt.Sprintf(apiStreamCreateT, cfg.Name))
+	r, err := js.nc.RequestWithContext(o.ctx, csSubj, req)
+	if err != nil {
+		return nil, err
+	}
+	var resp streamCreateResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return nil, err
+	}
+	if resp.Error != nil {
+		return nil, errors.New(resp.Error.Description)
+	}
+	return resp.StreamInfo, nil
+}
+
+type streamInfoResponse = streamCreateResponse
+
+func (js *js) StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error) {
+	if strings.Contains(stream, ".") {
+		return nil, ErrInvalidStreamName
+	}
+
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	csSubj := js.apiSubj(fmt.Sprintf(apiStreamInfoT, stream))
+	r, err := js.nc.RequestWithContext(o.ctx, csSubj, nil)
+	if err != nil {
+		return nil, err
+	}
+	var resp streamInfoResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return nil, err
+	}
+	if resp.Error != nil {
+		return nil, errors.New(resp.Error.Description)
+	}
+	return resp.StreamInfo, nil
+}
+
+// StreamInfo shows config and current state for this stream.
+type StreamInfo struct {
+	Config  StreamConfig        `json:"config"`
+	Created time.Time           `json:"created"`
+	State   StreamState         `json:"state"`
+	Cluster *ClusterInfo        `json:"cluster,omitempty"`
+	Mirror  *StreamSourceInfo   `json:"mirror,omitempty"`
+	Sources []*StreamSourceInfo `json:"sources,omitempty"`
+}
+
+// StreamSourceInfo shows information about an upstream stream source.
+type StreamSourceInfo struct {
+	Name   string        `json:"name"`
+	Lag    uint64        `json:"lag"`
+	Active time.Duration `json:"active"`
+}
+
+// StreamState is information about the given stream.
+type StreamState struct {
+	Msgs      uint64    `json:"messages"`
+	Bytes     uint64    `json:"bytes"`
+	FirstSeq  uint64    `json:"first_seq"`
+	FirstTime time.Time `json:"first_ts"`
+	LastSeq   uint64    `json:"last_seq"`
+	LastTime  time.Time `json:"last_ts"`
+	Consumers int       `json:"consumer_count"`
+}
+
+// ClusterInfo shows information about the underlying set of servers
+// that make up the stream or consumer.
+type ClusterInfo struct {
+	Name     string      `json:"name,omitempty"`
+	Leader   string      `json:"leader,omitempty"`
+	Replicas []*PeerInfo `json:"replicas,omitempty"`
+}
+
+// PeerInfo shows information about all the peers in the cluster that
+// are supporting the stream or consumer.
+type PeerInfo struct {
+	Name    string        `json:"name"`
+	Current bool          `json:"current"`
+	Offline bool          `json:"offline,omitempty"`
+	Active  time.Duration `json:"active"`
+	Lag     uint64        `json:"lag,omitempty"`
+}
+
+// UpdateStream updates a Stream.
+func (js *js) UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if cfg == nil || cfg.Name == _EMPTY_ {
+		return nil, ErrStreamNameRequired
+	}
+
+	req, err := json.Marshal(cfg)
+	if err != nil {
+		return nil, err
+	}
+
+	usSubj := js.apiSubj(fmt.Sprintf(apiStreamUpdateT, cfg.Name))
+	r, err := js.nc.RequestWithContext(o.ctx, usSubj, req)
+	if err != nil {
+		return nil, err
+	}
+	var resp streamInfoResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return nil, err
+	}
+	if resp.Error != nil {
+		return nil, errors.New(resp.Error.Description)
+	}
+	return resp.StreamInfo, nil
+}
+
+// streamDeleteResponse is the response for a Stream delete request.
+type streamDeleteResponse struct {
+	apiResponse
+	Success bool `json:"success,omitempty"`
+}
+
+// DeleteStream deletes a Stream.
+func (js *js) DeleteStream(name string, opts ...JSOpt) error {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if name == _EMPTY_ {
+		return ErrStreamNameRequired
+	}
+
+	dsSubj := js.apiSubj(fmt.Sprintf(apiStreamDeleteT, name))
+	r, err := js.nc.RequestWithContext(o.ctx, dsSubj, nil)
+	if err != nil {
+		return err
+	}
+	var resp streamDeleteResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return err
+	}
+	if resp.Error != nil {
+		return errors.New(resp.Error.Description)
+	}
+	return nil
+}
+
+type apiMsgGetRequest struct {
+	Seq uint64 `json:"seq"`
+}
+
+// RawStreamMsg is a raw message stored in JetStream.
+type RawStreamMsg struct {
+	Subject  string
+	Sequence uint64
+	Header   Header
+	Data     []byte
+	Time     time.Time
+}
+
+// storedMsg is a raw message stored in JetStream.
+type storedMsg struct {
+	Subject  string    `json:"subject"`
+	Sequence uint64    `json:"seq"`
+	Header   []byte    `json:"hdrs,omitempty"`
+	Data     []byte    `json:"data,omitempty"`
+	Time     time.Time `json:"time"`
+}
+
+// apiMsgGetResponse is the response for a Stream get request.
+type apiMsgGetResponse struct {
+	apiResponse
+	Message *storedMsg `json:"message,omitempty"`
+	Success bool       `json:"success,omitempty"`
+}
+
+// GetMsg retrieves a raw stream message stored in JetStream by sequence number.
+func (js *js) GetMsg(name string, seq uint64, opts ...JSOpt) (*RawStreamMsg, error) {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return nil, err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if name == _EMPTY_ {
+		return nil, ErrStreamNameRequired
+	}
+
+	req, err := json.Marshal(&apiMsgGetRequest{Seq: seq})
+	if err != nil {
+		return nil, err
+	}
+
+	dsSubj := js.apiSubj(fmt.Sprintf(apiMsgGetT, name))
+	r, err := js.nc.RequestWithContext(o.ctx, dsSubj, req)
+	if err != nil {
+		return nil, err
+	}
+
+	var resp apiMsgGetResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return nil, err
+	}
+	if resp.Error != nil {
+		return nil, errors.New(resp.Error.Description)
+	}
+
+	msg := resp.Message
+
+	var hdr Header
+	if msg.Header != nil {
+		hdr, err = decodeHeadersMsg(msg.Header)
+		if err != nil {
+			return nil, err
+		}
+	}
+
+	return &RawStreamMsg{
+		Subject:  msg.Subject,
+		Sequence: msg.Sequence,
+		Header:   hdr,
+		Data:     msg.Data,
+		Time:     msg.Time,
+	}, nil
+}
+
+type msgDeleteRequest struct {
+	Seq uint64 `json:"seq"`
+}
+
+// msgDeleteResponse is the response for a Stream delete request.
+type msgDeleteResponse struct {
+	apiResponse
+	Success bool `json:"success,omitempty"`
+}
+
+// DeleteMsg deletes a message from a stream.
+func (js *js) DeleteMsg(name string, seq uint64, opts ...JSOpt) error {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	if name == _EMPTY_ {
+		return ErrStreamNameRequired
+	}
+
+	req, err := json.Marshal(&msgDeleteRequest{Seq: seq})
+	if err != nil {
+		return err
+	}
+
+	dsSubj := js.apiSubj(fmt.Sprintf(apiMsgDeleteT, name))
+	r, err := js.nc.RequestWithContext(o.ctx, dsSubj, req)
+	if err != nil {
+		return err
+	}
+	var resp msgDeleteResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return err
+	}
+	if resp.Error != nil {
+		return errors.New(resp.Error.Description)
+	}
+	return nil
+}
+
+type streamPurgeResponse struct {
+	apiResponse
+	Success bool   `json:"success,omitempty"`
+	Purged  uint64 `json:"purged"`
+}
+
+// PurgeStream purges messages on a Stream.
+func (js *js) PurgeStream(name string, opts ...JSOpt) error {
+	o, cancel, err := getJSContextOpts(js.opts, opts...)
+	if err != nil {
+		return err
+	}
+	if cancel != nil {
+		defer cancel()
+	}
+
+	psSubj := js.apiSubj(fmt.Sprintf(apiStreamPurgeT, name))
+	r, err := js.nc.RequestWithContext(o.ctx, psSubj, nil)
+	if err != nil {
+		return err
+	}
+	var resp streamPurgeResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		return err
+	}
+	if resp.Error != nil {
+		return errors.New(resp.Error.Description)
+	}
+	return nil
+}
+
+// streamLister fetches pages of StreamInfo objects. This object is not safe
+// to use for multiple threads.
+type streamLister struct {
+	js   *js
+	page []*StreamInfo
+	err  error
+
+	offset   int
+	pageInfo *apiPaged
+}
+
+// streamListResponse list of detailed stream information.
+// A nil request is valid and means all streams.
+type streamListResponse struct {
+	apiResponse
+	apiPaged
+	Streams []*StreamInfo `json:"streams"`
+}
+
+// streamNamesRequest is used for Stream Name requests.
+type streamNamesRequest struct {
+	apiPagedRequest
+	// These are filters that can be applied to the list.
+	Subject string `json:"subject,omitempty"`
+}
+
+// Next fetches the next StreamInfo page.
+func (s *streamLister) Next() bool {
+	if s.err != nil {
+		return false
+	}
+	if s.pageInfo != nil && s.offset >= s.pageInfo.Total {
+		return false
+	}
+
+	req, err := json.Marshal(streamNamesRequest{
+		apiPagedRequest: apiPagedRequest{Offset: s.offset},
+	})
+	if err != nil {
+		s.err = err
+		return false
+	}
+
+	var cancel context.CancelFunc
+	ctx := s.js.opts.ctx
+	if ctx == nil {
+		ctx, cancel = context.WithTimeout(context.Background(), s.js.opts.wait)
+		defer cancel()
+	}
+
+	slSubj := s.js.apiSubj(apiStreamList)
+	r, err := s.js.nc.RequestWithContext(ctx, slSubj, req)
+	if err != nil {
+		s.err = err
+		return false
+	}
+	var resp streamListResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		s.err = err
+		return false
+	}
+	if resp.Error != nil {
+		s.err = errors.New(resp.Error.Description)
+		return false
+	}
+
+	s.pageInfo = &resp.apiPaged
+	s.page = resp.Streams
+	s.offset += len(s.page)
+	return true
+}
+
+// Page returns the current StreamInfo page.
+func (s *streamLister) Page() []*StreamInfo {
+	return s.page
+}
+
+// Err returns any errors found while fetching pages.
+func (s *streamLister) Err() error {
+	return s.err
+}
+
+// StreamsInfo can be used to retrieve a list of StreamInfo objects.
+func (jsc *js) StreamsInfo(opts ...JSOpt) <-chan *StreamInfo {
+	o, cancel, err := getJSContextOpts(jsc.opts, opts...)
+	if err != nil {
+		return nil
+	}
+
+	ch := make(chan *StreamInfo)
+	l := &streamLister{js: &js{nc: jsc.nc, opts: o}}
+	go func() {
+		if cancel != nil {
+			defer cancel()
+		}
+		defer close(ch)
+		for l.Next() {
+			for _, info := range l.Page() {
+				select {
+				case ch <- info:
+				case <-o.ctx.Done():
+					return
+				}
+			}
+		}
+	}()
+
+	return ch
+}
+
+type streamNamesLister struct {
+	js *js
+
+	err      error
+	offset   int
+	page     []string
+	pageInfo *apiPaged
+}
+
+// Next fetches the next ConsumerInfo page.
+func (l *streamNamesLister) Next() bool {
+	if l.err != nil {
+		return false
+	}
+	if l.pageInfo != nil && l.offset >= l.pageInfo.Total {
+		return false
+	}
+
+	var cancel context.CancelFunc
+	ctx := l.js.opts.ctx
+	if ctx == nil {
+		ctx, cancel = context.WithTimeout(context.Background(), l.js.opts.wait)
+		defer cancel()
+	}
+
+	r, err := l.js.nc.RequestWithContext(ctx, l.js.apiSubj(apiStreams), nil)
+	if err != nil {
+		l.err = err
+		return false
+	}
+	var resp streamNamesResponse
+	if err := json.Unmarshal(r.Data, &resp); err != nil {
+		l.err = err
+		return false
+	}
+	if resp.Error != nil {
+		l.err = errors.New(resp.Error.Description)
+		return false
+	}
+
+	l.pageInfo = &resp.apiPaged
+	l.page = resp.Streams
+	l.offset += len(l.page)
+	return true
+}
+
+// Page returns the current ConsumerInfo page.
+func (l *streamNamesLister) Page() []string {
+	return l.page
+}
+
+// Err returns any errors found while fetching pages.
+func (l *streamNamesLister) Err() error {
+	return l.err
+}
+
+// StreamNames is used to retrieve a list of Stream names.
+func (jsc *js) StreamNames(opts ...JSOpt) <-chan string {
+	o, cancel, err := getJSContextOpts(jsc.opts, opts...)
+	if err != nil {
+		return nil
+	}
+
+	ch := make(chan string)
+	l := &streamNamesLister{js: &js{nc: jsc.nc, opts: o}}
+	go func() {
+		if cancel != nil {
+			defer cancel()
+		}
+		defer close(ch)
+		for l.Next() {
+			for _, info := range l.Page() {
+				select {
+				case ch <- info:
+				case <-o.ctx.Done():
+					return
+				}
+			}
+		}
+	}()
+
+	return ch
+}
+
+func getJSContextOpts(defs *jsOpts, opts ...JSOpt) (*jsOpts, context.CancelFunc, error) {
+	var o jsOpts
+	for _, opt := range opts {
+		if err := opt.configureJSContext(&o); err != nil {
+			return nil, nil, err
+		}
+	}
+
+	// Check for option collisions. Right now just timeout and context.
+	if o.ctx != nil && o.wait != 0 {
+		return nil, nil, ErrContextAndTimeout
+	}
+	if o.wait == 0 && o.ctx == nil {
+		o.wait = defs.wait
+	}
+	var cancel context.CancelFunc
+	if o.ctx == nil && o.wait > 0 {
+		o.ctx, cancel = context.WithTimeout(context.Background(), o.wait)
+	}
+	if o.pre == "" {
+		o.pre = defs.pre
+	}
+
+	return &o, cancel, nil
+}

File diff suppressed because it is too large
+ 576 - 131
vendor/github.com/nats-io/nats.go/nats.go


+ 1 - 1
vendor/github.com/nats-io/nats/netchan.go → vendor/github.com/nats-io/nats.go/netchan.go

@@ -107,5 +107,5 @@ func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (
 		chVal.Send(oPtr)
 	}
 
-	return c.Conn.subscribe(subject, queue, cb, nil)
+	return c.Conn.subscribe(subject, queue, cb, nil, false, nil)
 }

+ 75 - 4
vendor/github.com/nats-io/nats/parser.go → vendor/github.com/nats-io/nats.go/parser.go

@@ -1,4 +1,4 @@
-// Copyright 2012-2018 The NATS Authors
+// Copyright 2012-2020 The NATS Authors
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
@@ -21,15 +21,17 @@ type msgArg struct {
 	subject []byte
 	reply   []byte
 	sid     int64
+	hdr     int
 	size    int
 }
 
-const MAX_CONTROL_LINE_SIZE = 1024
+const MAX_CONTROL_LINE_SIZE = 4096
 
 type parseState struct {
 	state   int
 	as      int
 	drop    int
+	hdr     int
 	ma      msgArg
 	argBuf  []byte
 	msgBuf  []byte
@@ -54,6 +56,7 @@ const (
 	MSG_ARG
 	MSG_PAYLOAD
 	MSG_END
+	OP_H
 	OP_P
 	OP_PI
 	OP_PIN
@@ -83,6 +86,12 @@ func (nc *Conn) parse(buf []byte) error {
 			switch b {
 			case 'M', 'm':
 				nc.ps.state = OP_M
+				nc.ps.hdr = -1
+				nc.ps.ma.hdr = -1
+			case 'H', 'h':
+				nc.ps.state = OP_H
+				nc.ps.hdr = 0
+				nc.ps.ma.hdr = 0
 			case 'P', 'p':
 				nc.ps.state = OP_P
 			case '+':
@@ -94,6 +103,13 @@ func (nc *Conn) parse(buf []byte) error {
 			default:
 				goto parseErr
 			}
+		case OP_H:
+			switch b {
+			case 'M', 'm':
+				nc.ps.state = OP_M
+			default:
+				goto parseErr
+			}
 		case OP_M:
 			switch b {
 			case 'S', 's':
@@ -140,8 +156,7 @@ func (nc *Conn) parse(buf []byte) error {
 				nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, MSG_PAYLOAD
 
 				// jump ahead with the index. If this overruns
-				// what is left we fall out and process split
-				// buffer.
+				// what is left we fall out and process a split buffer.
 				i = nc.ps.as + nc.ps.ma.size - 1
 			default:
 				if nc.ps.argBuf != nil {
@@ -415,6 +430,11 @@ func (nc *Conn) cloneMsgArg() {
 const argsLenMax = 4
 
 func (nc *Conn) processMsgArgs(arg []byte) error {
+	// Use separate function for header based messages.
+	if nc.ps.hdr >= 0 {
+		return nc.processHeaderMsgArgs(arg)
+	}
+
 	// Unroll splitArgs to avoid runtime/heap issues
 	a := [argsLenMax][]byte{}
 	args := a[:0]
@@ -459,6 +479,57 @@ func (nc *Conn) processMsgArgs(arg []byte) error {
 	return nil
 }
 
+// processHeaderMsgArgs is for a header based message.
+func (nc *Conn) processHeaderMsgArgs(arg []byte) error {
+	// Unroll splitArgs to avoid runtime/heap issues
+	a := [argsLenMax][]byte{}
+	args := a[:0]
+	start := -1
+	for i, b := range arg {
+		switch b {
+		case ' ', '\t', '\r', '\n':
+			if start >= 0 {
+				args = append(args, arg[start:i])
+				start = -1
+			}
+		default:
+			if start < 0 {
+				start = i
+			}
+		}
+	}
+	if start >= 0 {
+		args = append(args, arg[start:])
+	}
+
+	switch len(args) {
+	case 4:
+		nc.ps.ma.subject = args[0]
+		nc.ps.ma.sid = parseInt64(args[1])
+		nc.ps.ma.reply = nil
+		nc.ps.ma.hdr = int(parseInt64(args[2]))
+		nc.ps.ma.size = int(parseInt64(args[3]))
+	case 5:
+		nc.ps.ma.subject = args[0]
+		nc.ps.ma.sid = parseInt64(args[1])
+		nc.ps.ma.reply = args[2]
+		nc.ps.ma.hdr = int(parseInt64(args[3]))
+		nc.ps.ma.size = int(parseInt64(args[4]))
+	default:
+		return fmt.Errorf("nats: processHeaderMsgArgs Parse Error: '%s'", arg)
+	}
+	if nc.ps.ma.sid < 0 {
+		return fmt.Errorf("nats: processHeaderMsgArgs Bad or Missing Sid: '%s'", arg)
+	}
+	if nc.ps.ma.hdr < 0 || nc.ps.ma.hdr > nc.ps.ma.size {
+		return fmt.Errorf("nats: processHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
+	}
+	if nc.ps.ma.size < 0 {
+		return fmt.Errorf("nats: processHeaderMsgArgs Bad or Missing Size: '%s'", arg)
+	}
+	return nil
+}
+
 // Ascii numbers 0-9
 const (
 	ascii_0 = 48

+ 0 - 0
vendor/github.com/nats-io/nats/timer.go → vendor/github.com/nats-io/nats.go/timer.go


+ 27 - 0
vendor/github.com/nats-io/nats.go/util/tls.go

@@ -0,0 +1,27 @@
+// Copyright 2017-2018 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build go1.8
+
+package util
+
+import "crypto/tls"
+
+// CloneTLSConfig returns a copy of c.
+func CloneTLSConfig(c *tls.Config) *tls.Config {
+	if c == nil {
+		return &tls.Config{}
+	}
+
+	return c.Clone()
+}

+ 49 - 0
vendor/github.com/nats-io/nats.go/util/tls_go17.go

@@ -0,0 +1,49 @@
+// Copyright 2016-2018 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build go1.7,!go1.8
+
+package util
+
+import (
+	"crypto/tls"
+)
+
+// CloneTLSConfig returns a copy of c. Only the exported fields are copied.
+// This is temporary, until this is provided by the language.
+// https://go-review.googlesource.com/#/c/28075/
+func CloneTLSConfig(c *tls.Config) *tls.Config {
+	return &tls.Config{
+		Rand:                        c.Rand,
+		Time:                        c.Time,
+		Certificates:                c.Certificates,
+		NameToCertificate:           c.NameToCertificate,
+		GetCertificate:              c.GetCertificate,
+		RootCAs:                     c.RootCAs,
+		NextProtos:                  c.NextProtos,
+		ServerName:                  c.ServerName,
+		ClientAuth:                  c.ClientAuth,
+		ClientCAs:                   c.ClientCAs,
+		InsecureSkipVerify:          c.InsecureSkipVerify,
+		CipherSuites:                c.CipherSuites,
+		PreferServerCipherSuites:    c.PreferServerCipherSuites,
+		SessionTicketsDisabled:      c.SessionTicketsDisabled,
+		SessionTicketKey:            c.SessionTicketKey,
+		ClientSessionCache:          c.ClientSessionCache,
+		MinVersion:                  c.MinVersion,
+		MaxVersion:                  c.MaxVersion,
+		CurvePreferences:            c.CurvePreferences,
+		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
+		Renegotiation:               c.Renegotiation,
+	}
+}

+ 700 - 0
vendor/github.com/nats-io/nats.go/ws.go

@@ -0,0 +1,700 @@
+// Copyright 2021 The NATS Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package nats
+
+import (
+	"bufio"
+	"bytes"
+	"compress/flate"
+	"crypto/rand"
+	"crypto/sha1"
+	"encoding/base64"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/ioutil"
+	mrand "math/rand"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+	"unicode/utf8"
+)
+
+type wsOpCode int
+
+const (
+	// From https://tools.ietf.org/html/rfc6455#section-5.2
+	wsTextMessage   = wsOpCode(1)
+	wsBinaryMessage = wsOpCode(2)
+	wsCloseMessage  = wsOpCode(8)
+	wsPingMessage   = wsOpCode(9)
+	wsPongMessage   = wsOpCode(10)
+
+	wsFinalBit = 1 << 7
+	wsRsv1Bit  = 1 << 6 // Used for compression, from https://tools.ietf.org/html/rfc7692#section-6
+	wsRsv2Bit  = 1 << 5
+	wsRsv3Bit  = 1 << 4
+
+	wsMaskBit = 1 << 7
+
+	wsContinuationFrame     = 0
+	wsMaxFrameHeaderSize    = 14
+	wsMaxControlPayloadSize = 125
+
+	// From https://tools.ietf.org/html/rfc6455#section-11.7
+	wsCloseStatusNormalClosure      = 1000
+	wsCloseStatusNoStatusReceived   = 1005
+	wsCloseStatusAbnormalClosure    = 1006
+	wsCloseStatusInvalidPayloadData = 1007
+
+	wsScheme    = "ws"
+	wsSchemeTLS = "wss"
+
+	wsPMCExtension      = "permessage-deflate" // per-message compression
+	wsPMCSrvNoCtx       = "server_no_context_takeover"
+	wsPMCCliNoCtx       = "client_no_context_takeover"
+	wsPMCReqHeaderValue = wsPMCExtension + "; " + wsPMCSrvNoCtx + "; " + wsPMCCliNoCtx
+)
+
+// From https://tools.ietf.org/html/rfc6455#section-1.3
+var wsGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
+
+// As per https://tools.ietf.org/html/rfc7692#section-7.2.2
+// add 0x00, 0x00, 0xff, 0xff and then a final block so that flate reader
+// does not report unexpected EOF.
+var compressFinalBlock = []byte{0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff}
+
+type websocketReader struct {
+	r       io.Reader
+	pending [][]byte
+	ib      []byte
+	ff      bool
+	fc      bool
+	dc      io.ReadCloser
+	nc      *Conn
+}
+
+type websocketWriter struct {
+	w          io.Writer
+	compress   bool
+	compressor *flate.Writer
+	ctrlFrames [][]byte // pending frames that should be sent at the next Write()
+	cm         []byte   // close message that needs to be sent when everything else has been sent
+	cmDone     bool     // a close message has been added or sent (never going back to false)
+	noMoreSend bool     // if true, even if there is a Write() call, we should not send anything
+}
+
+type decompressorBuffer struct {
+	buf   []byte
+	rem   int
+	off   int
+	final bool
+}
+
+func newDecompressorBuffer(buf []byte) *decompressorBuffer {
+	return &decompressorBuffer{buf: buf, rem: len(buf)}
+}
+
+func (d *decompressorBuffer) Read(p []byte) (int, error) {
+	if d.buf == nil {
+		return 0, io.EOF
+	}
+	lim := d.rem
+	if len(p) < lim {
+		lim = len(p)
+	}
+	n := copy(p, d.buf[d.off:d.off+lim])
+	d.off += n
+	d.rem -= n
+	d.checkRem()
+	return n, nil
+}
+
+func (d *decompressorBuffer) checkRem() {
+	if d.rem != 0 {
+		return
+	}
+	if !d.final {
+		d.buf = compressFinalBlock
+		d.off = 0
+		d.rem = len(d.buf)
+		d.final = true
+	} else {
+		d.buf = nil
+	}
+}
+
+func (d *decompressorBuffer) ReadByte() (byte, error) {
+	if d.buf == nil {
+		return 0, io.EOF
+	}
+	b := d.buf[d.off]
+	d.off++
+	d.rem--
+	d.checkRem()
+	return b, nil
+}
+
+func wsNewReader(r io.Reader) *websocketReader {
+	return &websocketReader{r: r, ff: true}
+}
+
+func (r *websocketReader) Read(p []byte) (int, error) {
+	var err error
+	var buf []byte
+
+	if l := len(r.ib); l > 0 {
+		buf = r.ib
+		r.ib = nil
+	} else {
+		if len(r.pending) > 0 {
+			return r.drainPending(p), nil
+		}
+
+		// Get some data from the underlying reader.
+		n, err := r.r.Read(p)
+		if err != nil {
+			return 0, err
+		}
+		buf = p[:n]
+	}
+
+	// Now parse this and decode frames. We will possibly read more to
+	// ensure that we get a full frame.
+	var (
+		tmpBuf []byte
+		pos    int
+		max    = len(buf)
+		rem    = 0
+	)
+	for pos < max {
+		b0 := buf[pos]
+		frameType := wsOpCode(b0 & 0xF)
+		final := b0&wsFinalBit != 0
+		compressed := b0&wsRsv1Bit != 0
+		pos++
+
+		tmpBuf, pos, err = wsGet(r.r, buf, pos, 1)
+		if err != nil {
+			return 0, err
+		}
+		b1 := tmpBuf[0]
+
+		// Store size in case it is < 125
+		rem = int(b1 & 0x7F)
+
+		switch frameType {
+		case wsPingMessage, wsPongMessage, wsCloseMessage:
+			if rem > wsMaxControlPayloadSize {
+				return 0, fmt.Errorf(
+					fmt.Sprintf("control frame length bigger than maximum allowed of %v bytes",
+						wsMaxControlPayloadSize))
+			}
+			if compressed {
+				return 0, errors.New("control frame should not be compressed")
+			}
+			if !final {
+				return 0, errors.New("control frame does not have final bit set")
+			}
+		case wsTextMessage, wsBinaryMessage:
+			if !r.ff {
+				return 0, errors.New("new message started before final frame for previous message was received")
+			}
+			r.ff = final
+			r.fc = compressed
+		case wsContinuationFrame:
+			// Compressed bit must be only set in the first frame
+			if r.ff || compressed {
+				return 0, errors.New("invalid continuation frame")
+			}
+			r.ff = final
+		default:
+			return 0, fmt.Errorf("unknown opcode %v", frameType)
+		}
+
+		// If the encoded size is <= 125, then `rem` is simply the remainder size of the
+		// frame. If it is 126, then the actual size is encoded as a uint16. For larger
+		// frames, `rem` will initially be 127 and the actual size is encoded as a uint64.
+		switch rem {
+		case 126:
+			tmpBuf, pos, err = wsGet(r.r, buf, pos, 2)
+			if err != nil {
+				return 0, err
+			}
+			rem = int(binary.BigEndian.Uint16(tmpBuf))
+		case 127:
+			tmpBuf, pos, err = wsGet(r.r, buf, pos, 8)
+			if err != nil {
+				return 0, err
+			}
+			rem = int(binary.BigEndian.Uint64(tmpBuf))
+		}
+
+		// Handle control messages in place...
+		if wsIsControlFrame(frameType) {
+			pos, err = r.handleControlFrame(frameType, buf, pos, rem)
+			if err != nil {
+				return 0, err
+			}
+			rem = 0
+			continue
+		}
+
+		var b []byte
+		b, pos, err = wsGet(r.r, buf, pos, rem)
+		if err != nil {
+			return 0, err
+		}
+		rem = 0
+		if r.fc {
+			br := newDecompressorBuffer(b)
+			if r.dc == nil {
+				r.dc = flate.NewReader(br)
+			} else {
+				r.dc.(flate.Resetter).Reset(br, nil)
+			}
+			// TODO: When Go 1.15 support is dropped, replace with io.ReadAll()
+			b, err = ioutil.ReadAll(r.dc)
+			if err != nil {
+				return 0, err
+			}
+			r.fc = false
+		}
+		r.pending = append(r.pending, b)
+	}
+	// At this point we should have pending slices.
+	return r.drainPending(p), nil
+}
+
+func (r *websocketReader) drainPending(p []byte) int {
+	var n int
+	var max = len(p)
+
+	for i, buf := range r.pending {
+		if n+len(buf) <= max {
+			copy(p[n:], buf)
+			n += len(buf)
+		} else {
+			// Is there room left?
+			if n < max {
+				// Write the partial and update this slice.
+				rem := max - n
+				copy(p[n:], buf[:rem])
+				n += rem
+				r.pending[i] = buf[rem:]
+			}
+			// These are the remaining slices that will need to be used at
+			// the next Read() call.
+			r.pending = r.pending[i:]
+			return n
+		}
+	}
+	r.pending = r.pending[:0]
+	return n
+}
+
+func wsGet(r io.Reader, buf []byte, pos, needed int) ([]byte, int, error) {
+	avail := len(buf) - pos
+	if avail >= needed {
+		return buf[pos : pos+needed], pos + needed, nil
+	}
+	b := make([]byte, needed)
+	start := copy(b, buf[pos:])
+	for start != needed {
+		n, err := r.Read(b[start:cap(b)])
+		start += n
+		if err != nil {
+			return b, start, err
+		}
+	}
+	return b, pos + avail, nil
+}
+
+func (r *websocketReader) handleControlFrame(frameType wsOpCode, buf []byte, pos, rem int) (int, error) {
+	var payload []byte
+	var err error
+
+	statusPos := pos
+	if rem > 0 {
+		payload, pos, err = wsGet(r.r, buf, pos, rem)
+		if err != nil {
+			return pos, err
+		}
+	}
+	switch frameType {
+	case wsCloseMessage:
+		status := wsCloseStatusNoStatusReceived
+		body := ""
+		// If there is a payload, it should contain 2 unsigned bytes
+		// that represent the status code and then optional payload.
+		if len(payload) >= 2 {
+			status = int(binary.BigEndian.Uint16(buf[statusPos : statusPos+2]))
+			body = string(buf[statusPos+2 : statusPos+len(payload)])
+			if body != "" && !utf8.ValidString(body) {
+				// https://tools.ietf.org/html/rfc6455#section-5.5.1
+				// If body is present, it must be a valid utf8
+				status = wsCloseStatusInvalidPayloadData
+				body = "invalid utf8 body in close frame"
+			}
+		}
+		r.nc.wsEnqueueCloseMsg(status, body)
+		// Return io.EOF so that readLoop will close the connection as ClientClosed
+		// after processing pending buffers.
+		return pos, io.EOF
+	case wsPingMessage:
+		r.nc.wsEnqueueControlMsg(wsPongMessage, payload)
+	case wsPongMessage:
+		// Nothing to do..
+	}
+	return pos, nil
+}
+
+func (w *websocketWriter) Write(p []byte) (int, error) {
+	if w.noMoreSend {
+		return 0, nil
+	}
+	var total int
+	var n int
+	var err error
+	// If there are control frames, they can be sent now. Actually spec says
+	// that they should be sent ASAP, so we will send before any application data.
+	if len(w.ctrlFrames) > 0 {
+		n, err = w.writeCtrlFrames()
+		if err != nil {
+			return n, err
+		}
+		total += n
+	}
+	// Do the following only if there is something to send.
+	// We will end with checking for need to send close message.
+	if len(p) > 0 {
+		if w.compress {
+			buf := &bytes.Buffer{}
+			if w.compressor == nil {
+				w.compressor, _ = flate.NewWriter(buf, flate.BestSpeed)
+			} else {
+				w.compressor.Reset(buf)
+			}
+			w.compressor.Write(p)
+			w.compressor.Close()
+			b := buf.Bytes()
+			p = b[:len(b)-4]
+		}
+		fh, key := wsCreateFrameHeader(w.compress, wsBinaryMessage, len(p))
+		wsMaskBuf(key, p)
+		n, err = w.w.Write(fh)
+		total += n
+		if err == nil {
+			n, err = w.w.Write(p)
+			total += n
+		}
+	}
+	if err == nil && w.cm != nil {
+		n, err = w.writeCloseMsg()
+		total += n
+	}
+	return total, err
+}
+
+func (w *websocketWriter) writeCtrlFrames() (int, error) {
+	var (
+		n     int
+		total int
+		i     int
+		err   error
+	)
+	for ; i < len(w.ctrlFrames); i++ {
+		buf := w.ctrlFrames[i]
+		n, err = w.w.Write(buf)
+		total += n
+		if err != nil {
+			break
+		}
+	}
+	if i != len(w.ctrlFrames) {
+		w.ctrlFrames = w.ctrlFrames[i+1:]
+	} else {
+		w.ctrlFrames = w.ctrlFrames[:0]
+	}
+	return total, err
+}
+
+func (w *websocketWriter) writeCloseMsg() (int, error) {
+	n, err := w.w.Write(w.cm)
+	w.cm, w.noMoreSend = nil, true
+	return n, err
+}
+
+func wsMaskBuf(key, buf []byte) {
+	for i := 0; i < len(buf); i++ {
+		buf[i] ^= key[i&3]
+	}
+}
+
+// Create the frame header.
+// Encodes the frame type and optional compression flag, and the size of the payload.
+func wsCreateFrameHeader(compressed bool, frameType wsOpCode, l int) ([]byte, []byte) {
+	fh := make([]byte, wsMaxFrameHeaderSize)
+	n, key := wsFillFrameHeader(fh, compressed, frameType, l)
+	return fh[:n], key
+}
+
+func wsFillFrameHeader(fh []byte, compressed bool, frameType wsOpCode, l int) (int, []byte) {
+	var n int
+	b := byte(frameType)
+	b |= wsFinalBit
+	if compressed {
+		b |= wsRsv1Bit
+	}
+	b1 := byte(wsMaskBit)
+	switch {
+	case l <= 125:
+		n = 2
+		fh[0] = b
+		fh[1] = b1 | byte(l)
+	case l < 65536:
+		n = 4
+		fh[0] = b
+		fh[1] = b1 | 126
+		binary.BigEndian.PutUint16(fh[2:], uint16(l))
+	default:
+		n = 10
+		fh[0] = b
+		fh[1] = b1 | 127
+		binary.BigEndian.PutUint64(fh[2:], uint64(l))
+	}
+	var key []byte
+	var keyBuf [4]byte
+	if _, err := io.ReadFull(rand.Reader, keyBuf[:4]); err != nil {
+		kv := mrand.Int31()
+		binary.LittleEndian.PutUint32(keyBuf[:4], uint32(kv))
+	}
+	copy(fh[n:], keyBuf[:4])
+	key = fh[n : n+4]
+	n += 4
+	return n, key
+}
+
+func (nc *Conn) wsInitHandshake(u *url.URL) error {
+	compress := nc.Opts.Compression
+	tlsRequired := u.Scheme == wsSchemeTLS || nc.Opts.Secure || nc.Opts.TLSConfig != nil
+	// Do TLS here as needed.
+	if tlsRequired {
+		if err := nc.makeTLSConn(); err != nil {
+			return err
+		}
+	} else {
+		nc.bindToNewConn()
+	}
+
+	var err error
+
+	// For http request, we need the passed URL to contain either http or https scheme.
+	scheme := "http"
+	if tlsRequired {
+		scheme = "https"
+	}
+	ustr := fmt.Sprintf("%s://%s", scheme, u.Host)
+	u, err = url.Parse(ustr)
+	if err != nil {
+		return err
+	}
+	req := &http.Request{
+		Method:     "GET",
+		URL:        u,
+		Proto:      "HTTP/1.1",
+		ProtoMajor: 1,
+		ProtoMinor: 1,
+		Header:     make(http.Header),
+		Host:       u.Host,
+	}
+	wsKey, err := wsMakeChallengeKey()
+	if err != nil {
+		return err
+	}
+
+	req.Header["Upgrade"] = []string{"websocket"}
+	req.Header["Connection"] = []string{"Upgrade"}
+	req.Header["Sec-WebSocket-Key"] = []string{wsKey}
+	req.Header["Sec-WebSocket-Version"] = []string{"13"}
+	if compress {
+		req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
+	}
+	if err := req.Write(nc.conn); err != nil {
+		return err
+	}
+
+	var resp *http.Response
+
+	br := bufio.NewReaderSize(nc.conn, 4096)
+	nc.conn.SetReadDeadline(time.Now().Add(nc.Opts.Timeout))
+	resp, err = http.ReadResponse(br, req)
+	if err == nil &&
+		(resp.StatusCode != 101 ||
+			!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
+			!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
+			resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
+
+		err = fmt.Errorf("invalid websocket connection")
+	}
+	// Check compression extension...
+	if err == nil && compress {
+		// Check that not only permessage-deflate extension is present, but that
+		// we also have server and client no context take over.
+		srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header)
+
+		// If server does not support compression, then simply disable it in our side.
+		if !srvCompress {
+			compress = false
+		} else if !noCtxTakeover {
+			err = fmt.Errorf("compression negotiation error")
+		}
+	}
+	if resp != nil {
+		resp.Body.Close()
+	}
+	nc.conn.SetReadDeadline(time.Time{})
+	if err != nil {
+		return err
+	}
+
+	wsr := wsNewReader(nc.br.r)
+	wsr.nc = nc
+	// We have to slurp whatever is in the bufio reader and copy to br.r
+	if n := br.Buffered(); n != 0 {
+		wsr.ib, _ = br.Peek(n)
+	}
+	nc.br.r = wsr
+	nc.bw.w = &websocketWriter{w: nc.bw.w, compress: compress}
+	nc.ws = true
+	return nil
+}
+
+func (nc *Conn) wsClose() {
+	nc.mu.Lock()
+	defer nc.mu.Unlock()
+	if !nc.ws {
+		return
+	}
+	nc.wsEnqueueCloseMsgLocked(wsCloseStatusNormalClosure, _EMPTY_)
+}
+
+func (nc *Conn) wsEnqueueCloseMsg(status int, payload string) {
+	// In some low-level unit tests it will happen...
+	if nc == nil {
+		return
+	}
+	nc.mu.Lock()
+	nc.wsEnqueueCloseMsgLocked(status, payload)
+	nc.mu.Unlock()
+}
+
+func (nc *Conn) wsEnqueueCloseMsgLocked(status int, payload string) {
+	wr, ok := nc.bw.w.(*websocketWriter)
+	if !ok || wr.cmDone {
+		return
+	}
+	statusAndPayloadLen := 2 + len(payload)
+	frame := make([]byte, 2+4+statusAndPayloadLen)
+	n, key := wsFillFrameHeader(frame, false, wsCloseMessage, statusAndPayloadLen)
+	// Set the status
+	binary.BigEndian.PutUint16(frame[n:], uint16(status))
+	// If there is a payload, copy
+	if len(payload) > 0 {
+		copy(frame[n+2:], payload)
+	}
+	// Mask status + payload
+	wsMaskBuf(key, frame[n:n+statusAndPayloadLen])
+	wr.cm = frame
+	wr.cmDone = true
+	nc.bw.flush()
+}
+
+func (nc *Conn) wsEnqueueControlMsg(frameType wsOpCode, payload []byte) {
+	// In some low-level unit tests it will happen...
+	if nc == nil {
+		return
+	}
+	fh, key := wsCreateFrameHeader(false, frameType, len(payload))
+	nc.mu.Lock()
+	wr, ok := nc.bw.w.(*websocketWriter)
+	if !ok {
+		nc.mu.Unlock()
+		return
+	}
+	wr.ctrlFrames = append(wr.ctrlFrames, fh)
+	if len(payload) > 0 {
+		wsMaskBuf(key, payload)
+		wr.ctrlFrames = append(wr.ctrlFrames, payload)
+	}
+	nc.bw.flush()
+	nc.mu.Unlock()
+}
+
+func wsPMCExtensionSupport(header http.Header) (bool, bool) {
+	for _, extensionList := range header["Sec-Websocket-Extensions"] {
+		extensions := strings.Split(extensionList, ",")
+		for _, extension := range extensions {
+			extension = strings.Trim(extension, " \t")
+			params := strings.Split(extension, ";")
+			for i, p := range params {
+				p = strings.Trim(p, " \t")
+				if strings.EqualFold(p, wsPMCExtension) {
+					var snc bool
+					var cnc bool
+					for j := i + 1; j < len(params); j++ {
+						p = params[j]
+						p = strings.Trim(p, " \t")
+						if strings.EqualFold(p, wsPMCSrvNoCtx) {
+							snc = true
+						} else if strings.EqualFold(p, wsPMCCliNoCtx) {
+							cnc = true
+						}
+						if snc && cnc {
+							return true, true
+						}
+					}
+					return true, false
+				}
+			}
+		}
+	}
+	return false, false
+}
+
+func wsMakeChallengeKey() (string, error) {
+	p := make([]byte, 16)
+	if _, err := io.ReadFull(rand.Reader, p); err != nil {
+		return "", err
+	}
+	return base64.StdEncoding.EncodeToString(p), nil
+}
+
+func wsAcceptKey(key string) string {
+	h := sha1.New()
+	h.Write([]byte(key))
+	h.Write(wsGUID)
+	return base64.StdEncoding.EncodeToString(h.Sum(nil))
+}
+
+// Returns true if the op code corresponds to a control frame.
+func wsIsControlFrame(frameType wsOpCode) bool {
+	return frameType >= wsCloseMessage
+}
+
+func isWebsocketScheme(u *url.URL) bool {
+	return u.Scheme == wsScheme || u.Scheme == wsSchemeTLS
+}

+ 0 - 21
vendor/github.com/nats-io/nats/.travis.yml

@@ -1,21 +0,0 @@
-language: go
-sudo: false
-go:
-- 1.11.x
-- 1.10.x
-go_import_path: github.com/nats-io/go-nats
-install:
-- go get -t ./...
-- go get github.com/nats-io/gnatsd
-- go get github.com/mattn/goveralls
-- go get github.com/wadey/gocovmerge
-- go get -u honnef.co/go/tools/cmd/staticcheck
-- go get -u github.com/client9/misspell/cmd/misspell
-before_script:
-- $(exit $(go fmt ./... | wc -l))
-- go vet ./...
-- misspell -error -locale US .
-- staticcheck -ignore "$(cat staticcheck.ignore)" ./...
-script:
-- go test -i -race ./...
-- if [[ "$TRAVIS_GO_VERSION" =~ 1.11 ]]; then ./scripts/cov.sh TRAVIS; else go test -race ./...; fi

+ 0 - 4
vendor/github.com/nats-io/nats/staticcheck.ignore

@@ -1,4 +0,0 @@
-github.com/nats-io/go-nats/*_test.go:SA2002
-github.com/nats-io/go-nats/*/*_test.go:SA2002
-github.com/nats-io/go-nats/test/context_test.go:SA1012
-github.com/nats-io/go-nats/nats.go:SA6000

+ 9 - 6
vendor/github.com/nats-io/nkeys/.travis.yml

@@ -1,21 +1,24 @@
 language: go
 sudo: false
+
+arch:
+- amd64
+- ppc64le
 go:
-- 1.11
-- 1.10.x
-- 1.9.x
+- 1.16.x
+- 1.15.x
 
 install:
 - go get -t ./...
 - go get github.com/mattn/goveralls
-- go get -u honnef.co/go/tools/cmd/megacheck
+- go get -u honnef.co/go/tools/cmd/staticcheck
 - go get -u github.com/client9/misspell/cmd/misspell
 
 before_script:
 - $(exit $(go fmt ./... | wc -l))
 - go vet ./...
 - misspell -error -locale US .
-- megacheck -ignore "$(cat staticcheck.ignore)" ./...
+- staticcheck ./...
 
 script:
 - go test -v
@@ -29,4 +32,4 @@ script:
 #  script: curl -sL http://git.io/goreleaser | bash
 #  on:
 #    tags: true
-#    condition: $TRAVIS_OS_NAME = linux
+#    condition: $TRAVIS_OS_NAME = linux

+ 4 - 2
vendor/github.com/nats-io/nkeys/MAINTAINERS.md

@@ -2,5 +2,7 @@
 
 Maintainership is on a per project basis.
 
-### Core-maintainers
-  - Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)
+### Maintainers
+  - Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)
+  - Ivan Kozlovic <ivan@nats.io> [@kozlovic](https://github.com/kozlovic)
+  - Waldemar Quevedo <wally@nats.io> [@wallyqs](https://github.com/wallyqs)

+ 2 - 5
vendor/github.com/nats-io/nkeys/README.md

@@ -2,10 +2,9 @@
 
 [![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
 [![ReportCard](http://goreportcard.com/badge/nats-io/nkeys)](http://goreportcard.com/report/nats-io/nkeys)
-[![Build Status](https://travis-ci.org/nats-io/nkeys.svg?branch=master)](http://travis-ci.org/nats-io/nkeys)
+[![Build Status](https://travis-ci.com/nats-io/nkeys.svg?branch=master)](http://travis-ci.com/nats-io/nkeys)
 [![GoDoc](http://godoc.org/github.com/nats-io/nkeys?status.svg)](http://godoc.org/github.com/nats-io/nkeys)
 [![Coverage Status](https://coveralls.io/repos/github/nats-io/nkeys/badge.svg?branch=master&service=github)](https://coveralls.io/github/nats-io/nkeys?branch=master)
-[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys?ref=badge_shield)
 
 A public-key signature system based on [Ed25519](https://ed25519.cr.yp.to/) for the NATS ecosystem.
 
@@ -17,7 +16,7 @@ Ed25519 is fast and resistant to side channel attacks. Generation of a seed key
 
 The NATS system will utilize Ed25519 keys, meaning that NATS systems will never store or even have access to any private keys. Authentication will utilize a random challenge response mechanism.
 
-Dealing with 32 byte and 64 byte raw keys can be challenging. NKEYS is designed to formulate keys in a much friendlier fashion and references work done in cryptocurrencies, specifically [Stellar](https://www.stellar.org/).	Bitcoin and others used a form of Base58 (or Base58Check) to endode raw keys. Stellar utilized a more traditonal Base32 with a CRC16 and a version or prefix byte. NKEYS utilizes a similar format where the prefix will be 1 byte for public and private keys and will be 2 bytes for seeds. The base32 encoding of these prefixes will yield friendly human readbable prefixes, e.g. '**N**' = server, '**C**' = cluster, '**O**' = operator, '**A**' = account, and '**U**' = user. '**P**' is used for private keys. For seeds, the first encoded prefix is '**S**', and the second character will be the type for the public key, e.g. "**SU**" is a seed for a user key pair, "**SA**" is a seed for an account key pair.
+Dealing with 32 byte and 64 byte raw keys can be challenging. NKEYS is designed to formulate keys in a much friendlier fashion and references work done in cryptocurrencies, specifically [Stellar](https://www.stellar.org/).	Bitcoin and others used a form of Base58 (or Base58Check) to encode raw keys. Stellar utilized a more traditional Base32 with a CRC16 and a version or prefix byte. NKEYS utilizes a similar format where the prefix will be 1 byte for public and private keys and will be 2 bytes for seeds. The base32 encoding of these prefixes will yield friendly human readable prefixes, e.g. '**N**' = server, '**C**' = cluster, '**O**' = operator, '**A**' = account, and '**U**' = user. '**P**' is used for private keys. For seeds, the first encoded prefix is '**S**', and the second character will be the type for the public key, e.g. "**SU**" is a seed for a user key pair, "**SA**" is a seed for an account key pair.
 
 ## Installation
 
@@ -68,5 +67,3 @@ user2, _ := nkeys.FromRawSeed(PrefixByteUser, rawSeed)
 Unless otherwise noted, the NATS source files are distributed
 under the Apache Version 2.0 license found in the LICENSE file.
 
-
-[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys?ref=badge_large)

+ 78 - 0
vendor/github.com/nats-io/nkeys/creds_utils.go

@@ -0,0 +1,78 @@
+package nkeys
+
+import (
+	"bytes"
+	"errors"
+	"regexp"
+)
+
+var userConfigRE = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}\r?\n))`)
+
+// ParseDecoratedJWT takes a creds file and returns the JWT portion.
+func ParseDecoratedJWT(contents []byte) (string, error) {
+	items := userConfigRE.FindAllSubmatch(contents, -1)
+	if len(items) == 0 {
+		return string(contents), nil
+	}
+	// First result should be the user JWT.
+	// We copy here so that if the file contained a seed file too we wipe appropriately.
+	raw := items[0][1]
+	tmp := make([]byte, len(raw))
+	copy(tmp, raw)
+	return string(tmp), nil
+}
+
+// ParseDecoratedNKey takes a creds file, finds the NKey portion and creates a
+// key pair from it.
+func ParseDecoratedNKey(contents []byte) (KeyPair, error) {
+	var seed []byte
+
+	items := userConfigRE.FindAllSubmatch(contents, -1)
+	if len(items) > 1 {
+		seed = items[1][1]
+	} else {
+		lines := bytes.Split(contents, []byte("\n"))
+		for _, line := range lines {
+			if bytes.HasPrefix(bytes.TrimSpace(line), []byte("SO")) ||
+				bytes.HasPrefix(bytes.TrimSpace(line), []byte("SA")) ||
+				bytes.HasPrefix(bytes.TrimSpace(line), []byte("SU")) {
+				seed = line
+				break
+			}
+		}
+	}
+	if seed == nil {
+		return nil, errors.New("no nkey seed found")
+	}
+	if !bytes.HasPrefix(seed, []byte("SO")) &&
+		!bytes.HasPrefix(seed, []byte("SA")) &&
+		!bytes.HasPrefix(seed, []byte("SU")) {
+		return nil, errors.New("doesn't contain a seed nkey")
+	}
+	kp, err := FromSeed(seed)
+	if err != nil {
+		return nil, err
+	}
+	return kp, nil
+}
+
+// ParseDecoratedUserNKey takes a creds file, finds the NKey portion and creates a
+// key pair from it. Similar to ParseDecoratedNKey but fails for non-user keys.
+func ParseDecoratedUserNKey(contents []byte) (KeyPair, error) {
+	nk, err := ParseDecoratedNKey(contents)
+	if err != nil {
+		return nil, err
+	}
+	seed, err := nk.Seed()
+	if err != nil {
+		return nil, err
+	}
+	if !bytes.HasPrefix(seed, []byte("SU")) {
+		return nil, errors.New("doesn't contain an user seed nkey")
+	}
+	kp, err := FromSeed(seed)
+	if err != nil {
+		return nil, err
+	}
+	return kp, nil
+}

+ 3 - 1
vendor/github.com/nats-io/nkeys/go.mod

@@ -1,3 +1,5 @@
 module github.com/nats-io/nkeys
 
-require golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9
+go 1.16
+
+require golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b

+ 7 - 2
vendor/github.com/nats-io/nkeys/go.sum

@@ -1,2 +1,7 @@
-golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0=
-golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
+golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b h1:wSOdpTq0/eI46Ez/LkDwIsAKA71YP2SRKBODiRWM0as=
+golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

+ 5 - 4
vendor/github.com/nats-io/nkeys/main.go

@@ -1,4 +1,4 @@
-// Copyright 2018 The NATS Authors
+// Copyright 2018-2019 The NATS Authors
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
@@ -19,8 +19,8 @@ import (
 	"errors"
 )
 
-// Version
-const Version = "0.0.2"
+// Version is our current version
+const Version = "0.3.0"
 
 // Errors
 var (
@@ -33,6 +33,7 @@ var (
 	ErrInvalidSignature  = errors.New("nkeys: signature verification failed")
 	ErrCannotSign        = errors.New("nkeys: can not sign, no private key available")
 	ErrPublicKeyOnly     = errors.New("nkeys: no seed or private key available")
+	ErrIncompatibleKey   = errors.New("nkeys: incompatible key")
 )
 
 // KeyPair provides the central interface to nkeys.
@@ -93,7 +94,7 @@ func FromSeed(seed []byte) (KeyPair, error) {
 	return &kp{copy}, nil
 }
 
-// Create a KeyPair from the raw 32 byte seed for a given type.
+// FromRawSeed will create a KeyPair from the raw 32 byte seed for a given type.
 func FromRawSeed(prefix PrefixByte, rawSeed []byte) (KeyPair, error) {
 	seed, err := EncodeSeed(prefix, rawSeed)
 	if err != nil {

+ 21 - 5
vendor/github.com/nats-io/nkeys/strkey.go

@@ -17,7 +17,6 @@ import (
 	"bytes"
 	"encoding/base32"
 	"encoding/binary"
-
 	"golang.org/x/crypto/ed25519"
 )
 
@@ -47,7 +46,7 @@ const (
 	PrefixByteUser PrefixByte = 20 << 3 // Base32-encodes to 'U...'
 
 	// PrefixByteUnknown is for unknown prefixes.
-	PrefixByteUknown PrefixByte = 23 << 3 // Base32-encodes to 'X...'
+	PrefixByteUnknown PrefixByte = 23 << 3 // Base32-encodes to 'X...'
 )
 
 // Set our encoding to not include padding '=='
@@ -128,7 +127,7 @@ func IsValidEncoding(src []byte) bool {
 
 // decode will decode the base32 and check crc16 and the prefix for validity.
 func decode(src []byte) ([]byte, error) {
-	raw := make([]byte, b32Enc.EncodedLen(len(src)))
+	raw := make([]byte, b32Enc.DecodedLen(len(src)))
 	n, err := b32Enc.Decode(raw, src)
 	if err != nil {
 		return nil, err
@@ -188,10 +187,11 @@ func DecodeSeed(src []byte) (PrefixByte, []byte, error) {
 	return PrefixByte(b2), raw[2:], nil
 }
 
+// Prefix returns PrefixBytes of its input
 func Prefix(src string) PrefixByte {
 	b, err := decode([]byte(src))
 	if err != nil {
-		return PrefixByteUknown
+		return PrefixByteUnknown
 	}
 	prefix := PrefixByte(b[0])
 	err = checkValidPrefixByte(prefix)
@@ -203,7 +203,7 @@ func Prefix(src string) PrefixByte {
 	if PrefixByte(b1) == PrefixByteSeed {
 		return PrefixByteSeed
 	}
-	return PrefixByteUknown
+	return PrefixByteUnknown
 }
 
 // IsValidPublicKey will decode and verify that the string is a valid encoded public key.
@@ -288,3 +288,19 @@ func (p PrefixByte) String() string {
 	}
 	return "unknown"
 }
+
+// CompatibleKeyPair returns an error if the KeyPair doesn't match expected PrefixByte(s)
+func CompatibleKeyPair(kp KeyPair, expected ...PrefixByte) error {
+	pk, err := kp.PublicKey()
+	if err != nil {
+		return err
+	}
+	pkType := Prefix(pk)
+	for _, k := range expected {
+		if pkType == k {
+			return nil
+		}
+	}
+
+	return ErrIncompatibleKey
+}

+ 6 - 0
vendor/golang.org/x/crypto/ed25519/ed25519.go

@@ -2,6 +2,12 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
+// In Go 1.13, the ed25519 package was promoted to the standard library as
+// crypto/ed25519, and this package became a wrapper for the standard library one.
+//
+//go:build !go1.13
+// +build !go1.13
+
 // Package ed25519 implements the Ed25519 signature algorithm. See
 // https://ed25519.cr.yp.to/.
 //

+ 74 - 0
vendor/golang.org/x/crypto/ed25519/ed25519_go113.go

@@ -0,0 +1,74 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build go1.13
+// +build go1.13
+
+// Package ed25519 implements the Ed25519 signature algorithm. See
+// https://ed25519.cr.yp.to/.
+//
+// These functions are also compatible with the “Ed25519” function defined in
+// RFC 8032. However, unlike RFC 8032's formulation, this package's private key
+// representation includes a public key suffix to make multiple signing
+// operations with the same key more efficient. This package refers to the RFC
+// 8032 private key as the “seed”.
+//
+// Beginning with Go 1.13, the functionality of this package was moved to the
+// standard library as crypto/ed25519. This package only acts as a compatibility
+// wrapper.
+package ed25519
+
+import (
+	"crypto/ed25519"
+	"io"
+)
+
+const (
+	// PublicKeySize is the size, in bytes, of public keys as used in this package.
+	PublicKeySize = 32
+	// PrivateKeySize is the size, in bytes, of private keys as used in this package.
+	PrivateKeySize = 64
+	// SignatureSize is the size, in bytes, of signatures generated and verified by this package.
+	SignatureSize = 64
+	// SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
+	SeedSize = 32
+)
+
+// PublicKey is the type of Ed25519 public keys.
+//
+// This type is an alias for crypto/ed25519's PublicKey type.
+// See the crypto/ed25519 package for the methods on this type.
+type PublicKey = ed25519.PublicKey
+
+// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.
+//
+// This type is an alias for crypto/ed25519's PrivateKey type.
+// See the crypto/ed25519 package for the methods on this type.
+type PrivateKey = ed25519.PrivateKey
+
+// GenerateKey generates a public/private key pair using entropy from rand.
+// If rand is nil, crypto/rand.Reader will be used.
+func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) {
+	return ed25519.GenerateKey(rand)
+}
+
+// NewKeyFromSeed calculates a private key from a seed. It will panic if
+// len(seed) is not SeedSize. This function is provided for interoperability
+// with RFC 8032. RFC 8032's private keys correspond to seeds in this
+// package.
+func NewKeyFromSeed(seed []byte) PrivateKey {
+	return ed25519.NewKeyFromSeed(seed)
+}
+
+// Sign signs the message with privateKey and returns a signature. It will
+// panic if len(privateKey) is not PrivateKeySize.
+func Sign(privateKey PrivateKey, message []byte) []byte {
+	return ed25519.Sign(privateKey, message)
+}
+
+// Verify reports whether sig is a valid signature of message by publicKey. It
+// will panic if len(publicKey) is not PublicKeySize.
+func Verify(publicKey PublicKey, message, sig []byte) bool {
+	return ed25519.Verify(publicKey, message, sig)
+}

+ 30 - 0
vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go

@@ -0,0 +1,30 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package unsafeheader contains header declarations for the Go runtime's
+// slice and string implementations.
+//
+// This package allows x/sys to use types equivalent to
+// reflect.SliceHeader and reflect.StringHeader without introducing
+// a dependency on the (relatively heavy) "reflect" package.
+package unsafeheader
+
+import (
+	"unsafe"
+)
+
+// Slice is the runtime representation of a slice.
+// It cannot be used safely or portably and its representation may change in a later release.
+type Slice struct {
+	Data unsafe.Pointer
+	Len  int
+	Cap  int
+}
+
+// String is the runtime representation of a string.
+// It cannot be used safely or portably and its representation may change in a later release.
+type String struct {
+	Data unsafe.Pointer
+	Len  int
+}

+ 13 - 2
vendor/golang.org/x/sys/unix/README.md

@@ -89,7 +89,7 @@ constants.
 
 Adding new syscall numbers is mostly done by running the build on a sufficiently
 new installation of the target OS (or updating the source checkouts for the
-new build system). However, depending on the OS, you make need to update the
+new build system). However, depending on the OS, you may need to update the
 parsing in mksysnum.
 
 ### mksyscall.go
@@ -149,10 +149,21 @@ To add a constant, add the header that includes it to the appropriate variable.
 Then, edit the regex (if necessary) to match the desired constant. Avoid making
 the regex too broad to avoid matching unintended constants.
 
+### mkmerge.go
+
+This program is used to extract duplicate const, func, and type declarations
+from the generated architecture-specific files listed below, and merge these
+into a common file for each OS.
+
+The merge is performed in the following steps:
+1. Construct the set of common code that is idential in all architecture-specific files.
+2. Write this common code to the merged file.
+3. Remove the common code from all architecture-specific files.
+
 
 ## Generated files
 
-### `zerror_${GOOS}_${GOARCH}.go`
+### `zerrors_${GOOS}_${GOARCH}.go`
 
 A file containing all of the system's generated error numbers, error strings,
 signal numbers, and constants. Generated by `mkerrors.sh` (see above).

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_aix_ppc64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_darwin_386.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_darwin_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_darwin_arm.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 // +build arm,darwin
 
 #include "textflag.h"

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_darwin_arm64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 // +build arm64,darwin
 
 #include "textflag.h"

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_freebsd_386.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_freebsd_arm.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_freebsd_arm64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_386.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_arm.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_arm64.s

@@ -4,7 +4,7 @@
 
 // +build linux
 // +build arm64
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_mips64x.s

@@ -4,7 +4,7 @@
 
 // +build linux
 // +build mips64 mips64le
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_mipsx.s

@@ -4,7 +4,7 @@
 
 // +build linux
 // +build mips mipsle
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s

@@ -4,7 +4,7 @@
 
 // +build linux
 // +build ppc64 ppc64le
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 8
vendor/golang.org/x/sys/unix/asm_linux_riscv64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build riscv64,!gccgo
+// +build riscv64,gc
 
 #include "textflag.h"
 
@@ -23,10 +23,6 @@ TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
 	MOV	a1+8(FP), A0
 	MOV	a2+16(FP), A1
 	MOV	a3+24(FP), A2
-	MOV	$0, A3
-	MOV	$0, A4
-	MOV	$0, A5
-	MOV	$0, A6
 	MOV	trap+0(FP), A7	// syscall entry
 	ECALL
 	MOV	A0, r1+32(FP)	// r1
@@ -44,9 +40,6 @@ TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
 	MOV	a1+8(FP), A0
 	MOV	a2+16(FP), A1
 	MOV	a3+24(FP), A2
-	MOV	ZERO, A3
-	MOV	ZERO, A4
-	MOV	ZERO, A5
 	MOV	trap+0(FP), A7	// syscall entry
 	ECALL
 	MOV	A0, r1+32(FP)

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_linux_s390x.s

@@ -4,7 +4,7 @@
 
 // +build s390x
 // +build linux
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_netbsd_386.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_netbsd_arm.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_netbsd_arm64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_openbsd_386.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_openbsd_arm.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_openbsd_arm64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 29 - 0
vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s

@@ -0,0 +1,29 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build gc
+
+#include "textflag.h"
+
+//
+// System call support for mips64, OpenBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT	·Syscall(SB),NOSPLIT,$0-56
+	JMP	syscall·Syscall(SB)
+
+TEXT	·Syscall6(SB),NOSPLIT,$0-80
+	JMP	syscall·Syscall6(SB)
+
+TEXT	·Syscall9(SB),NOSPLIT,$0-104
+	JMP	syscall·Syscall9(SB)
+
+TEXT	·RawSyscall(SB),NOSPLIT,$0-56
+	JMP	syscall·RawSyscall(SB)
+
+TEXT	·RawSyscall6(SB),NOSPLIT,$0-80
+	JMP	syscall·RawSyscall6(SB)

+ 1 - 1
vendor/golang.org/x/sys/unix/asm_solaris_amd64.s

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-// +build !gccgo
+// +build gc
 
 #include "textflag.h"
 

+ 1 - 0
vendor/golang.org/x/sys/unix/bluetooth_linux.go

@@ -23,6 +23,7 @@ const (
 	HCI_CHANNEL_USER    = 1
 	HCI_CHANNEL_MONITOR = 2
 	HCI_CHANNEL_CONTROL = 3
+	HCI_CHANNEL_LOGGING = 4
 )
 
 // Socketoption Level

+ 1 - 1
vendor/golang.org/x/sys/unix/endian_big.go

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 //
-// +build ppc64 s390x mips mips64
+// +build armbe arm64be m68k mips mips64 mips64p32 ppc ppc64 s390 s390x shbe sparc sparc64
 
 package unix
 

+ 1 - 1
vendor/golang.org/x/sys/unix/endian_little.go

@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 //
-// +build 386 amd64 amd64p32 arm arm64 ppc64le mipsle mips64le riscv64
+// +build 386 amd64 amd64p32 alpha arm arm64 mipsle mips64le mips64p32le nios2 ppc64le riscv riscv64 sh
 
 package unix
 

+ 6 - 0
vendor/golang.org/x/sys/unix/errors_freebsd_386.go

@@ -8,6 +8,7 @@
 package unix
 
 const (
+	DLT_HHDLC                         = 0x79
 	IFF_SMART                         = 0x20
 	IFT_1822                          = 0x2
 	IFT_A12MPPSWITCH                  = 0x82
@@ -210,13 +211,18 @@ const (
 	IFT_XETHER                        = 0x1a
 	IPPROTO_MAXID                     = 0x34
 	IPV6_FAITH                        = 0x1d
+	IPV6_MIN_MEMBERSHIPS              = 0x1f
 	IP_FAITH                          = 0x16
+	IP_MAX_SOURCE_FILTER              = 0x400
+	IP_MIN_MEMBERSHIPS                = 0x1f
 	MAP_NORESERVE                     = 0x40
 	MAP_RENAME                        = 0x20
 	NET_RT_MAXID                      = 0x6
 	RTF_PRCLONING                     = 0x10000
 	RTM_OLDADD                        = 0x9
 	RTM_OLDDEL                        = 0xa
+	RT_CACHING_CONTEXT                = 0x1
+	RT_NORTREF                        = 0x2
 	SIOCADDRT                         = 0x8030720a
 	SIOCALIFADDR                      = 0x8118691b
 	SIOCDELRT                         = 0x8030720b

+ 6 - 0
vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go

@@ -8,6 +8,7 @@
 package unix
 
 const (
+	DLT_HHDLC                         = 0x79
 	IFF_SMART                         = 0x20
 	IFT_1822                          = 0x2
 	IFT_A12MPPSWITCH                  = 0x82
@@ -210,13 +211,18 @@ const (
 	IFT_XETHER                        = 0x1a
 	IPPROTO_MAXID                     = 0x34
 	IPV6_FAITH                        = 0x1d
+	IPV6_MIN_MEMBERSHIPS              = 0x1f
 	IP_FAITH                          = 0x16
+	IP_MAX_SOURCE_FILTER              = 0x400
+	IP_MIN_MEMBERSHIPS                = 0x1f
 	MAP_NORESERVE                     = 0x40
 	MAP_RENAME                        = 0x20
 	NET_RT_MAXID                      = 0x6
 	RTF_PRCLONING                     = 0x10000
 	RTM_OLDADD                        = 0x9
 	RTM_OLDDEL                        = 0xa
+	RT_CACHING_CONTEXT                = 0x1
+	RT_NORTREF                        = 0x2
 	SIOCADDRT                         = 0x8040720a
 	SIOCALIFADDR                      = 0x8118691b
 	SIOCDELRT                         = 0x8040720b

+ 17 - 0
vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go

@@ -0,0 +1,17 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep
+// them here for backwards compatibility.
+
+package unix
+
+const (
+	DLT_HHDLC            = 0x79
+	IPV6_MIN_MEMBERSHIPS = 0x1f
+	IP_MAX_SOURCE_FILTER = 0x400
+	IP_MIN_MEMBERSHIPS   = 0x1f
+	RT_CACHING_CONTEXT   = 0x1
+	RT_NORTREF           = 0x2
+)

+ 8 - 4
vendor/golang.org/x/sys/unix/fcntl.go

@@ -9,12 +9,11 @@ package unix
 import "unsafe"
 
 // fcntl64Syscall is usually SYS_FCNTL, but is overridden on 32-bit Linux
-// systems by flock_linux_32bit.go to be SYS_FCNTL64.
+// systems by fcntl_linux_32bit.go to be SYS_FCNTL64.
 var fcntl64Syscall uintptr = SYS_FCNTL
 
-// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
-func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
-	valptr, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg))
+func fcntl(fd int, cmd, arg int) (int, error) {
+	valptr, _, errno := Syscall(fcntl64Syscall, uintptr(fd), uintptr(cmd), uintptr(arg))
 	var err error
 	if errno != 0 {
 		err = errno
@@ -22,6 +21,11 @@ func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
 	return int(valptr), err
 }
 
+// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
+func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
+	return fcntl(int(fd), cmd, arg)
+}
+
 // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
 func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
 	_, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))

+ 6 - 0
vendor/golang.org/x/sys/unix/fcntl_darwin.go

@@ -16,3 +16,9 @@ func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
 	_, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(lk))))
 	return err
 }
+
+// FcntlFstore performs a fcntl syscall for the F_PREALLOCATE command.
+func FcntlFstore(fd uintptr, cmd int, fstore *Fstore_t) error {
+	_, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(fstore))))
+	return err
+}

+ 2 - 2
vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go

@@ -1,9 +1,9 @@
-// +build linux,386 linux,arm linux,mips linux,mipsle
-
 // Copyright 2014 The Go Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
+// +build linux,386 linux,arm linux,mips linux,mipsle
+
 package unix
 
 func init() {

+ 29 - 0
vendor/golang.org/x/sys/unix/fdset.go

@@ -0,0 +1,29 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
+
+package unix
+
+// Set adds fd to the set fds.
+func (fds *FdSet) Set(fd int) {
+	fds.Bits[fd/NFDBITS] |= (1 << (uintptr(fd) % NFDBITS))
+}
+
+// Clear removes fd from the set fds.
+func (fds *FdSet) Clear(fd int) {
+	fds.Bits[fd/NFDBITS] &^= (1 << (uintptr(fd) % NFDBITS))
+}
+
+// IsSet returns whether fd is in the set fds.
+func (fds *FdSet) IsSet(fd int) bool {
+	return fds.Bits[fd/NFDBITS]&(1<<(uintptr(fd)%NFDBITS)) != 0
+}
+
+// Zero clears the set fds.
+func (fds *FdSet) Zero() {
+	for i := range fds.Bits {
+		fds.Bits[i] = 0
+	}
+}

+ 0 - 2
vendor/golang.org/x/sys/unix/gccgo.go

@@ -12,10 +12,8 @@ import "syscall"
 // We can't use the gc-syntax .s files for gccgo. On the plus side
 // much of the functionality can be written directly in Go.
 
-//extern gccgoRealSyscallNoError
 func realSyscallNoError(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r uintptr)
 
-//extern gccgoRealSyscall
 func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr)
 
 func SyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) {

+ 6 - 0
vendor/golang.org/x/sys/unix/gccgo_c.c

@@ -21,6 +21,9 @@ struct ret {
 	uintptr_t err;
 };
 
+struct ret gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
+  __asm__(GOSYM_PREFIX GOPKGPATH ".realSyscall");
+
 struct ret
 gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
 {
@@ -32,6 +35,9 @@ gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintp
 	return r;
 }
 
+uintptr_t gccgoRealSyscallNoError(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
+  __asm__(GOSYM_PREFIX GOPKGPATH ".realSyscallNoError");
+
 uintptr_t
 gccgoRealSyscallNoError(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
 {

+ 9 - 0
vendor/golang.org/x/sys/unix/ioctl.go

@@ -20,6 +20,15 @@ func IoctlSetInt(fd int, req uint, value int) error {
 	return ioctl(fd, req, uintptr(value))
 }
 
+// IoctlSetPointerInt performs an ioctl operation which sets an
+// integer value on fd, using the specified request number. The ioctl
+// argument is called with a pointer to the integer value, rather than
+// passing the integer value directly.
+func IoctlSetPointerInt(fd int, req uint, value int) error {
+	v := int32(value)
+	return ioctl(fd, req, uintptr(unsafe.Pointer(&v)))
+}
+
 // IoctlSetWinsize performs an ioctl on fd with a *Winsize argument.
 //
 // To change fd's window size, the req argument should be TIOCSWINSZ.

+ 24 - 8
vendor/golang.org/x/sys/unix/mkall.sh

@@ -50,7 +50,7 @@ if [[ "$GOOS" = "linux" ]]; then
 	# Use the Docker-based build system
 	# Files generated through docker (use $cmd so you can Ctl-C the build or run)
 	$cmd docker build --tag generate:$GOOS $GOOS
-	$cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS
+	$cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")" && /bin/pwd):/build generate:$GOOS
 	exit
 fi
 
@@ -73,26 +73,22 @@ aix_ppc64)
 darwin_386)
 	mkerrors="$mkerrors -m32"
 	mksyscall="go run mksyscall.go -l32"
-	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
 	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
 	mkasm="go run mkasm_darwin.go"
 	;;
 darwin_amd64)
 	mkerrors="$mkerrors -m64"
-	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
 	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
 	mkasm="go run mkasm_darwin.go"
 	;;
 darwin_arm)
 	mkerrors="$mkerrors"
 	mksyscall="go run mksyscall.go -l32"
-	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
 	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
 	mkasm="go run mkasm_darwin.go"
 	;;
 darwin_arm64)
 	mkerrors="$mkerrors -m64"
-	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
 	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
 	mkasm="go run mkasm_darwin.go"
 	;;
@@ -124,7 +120,7 @@ freebsd_arm)
 freebsd_arm64)
 	mkerrors="$mkerrors -m64"
 	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
-	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
+	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
 	;;
 netbsd_386)
 	mkerrors="$mkerrors -m32"
@@ -184,12 +180,27 @@ openbsd_arm64)
 	# API consistent across platforms.
 	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
 	;;
+openbsd_mips64)
+	mkerrors="$mkerrors -m64"
+	mksyscall="go run mksyscall.go -openbsd"
+	mksysctl="go run mksysctl_openbsd.go"
+	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
+	# Let the type of C char be signed for making the bare syscall
+	# API consistent across platforms.
+	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
+	;;
 solaris_amd64)
 	mksyscall="go run mksyscall_solaris.go"
 	mkerrors="$mkerrors -m64"
 	mksysnum=
 	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
 	;;
+illumos_amd64)
+        mksyscall="go run mksyscall_solaris.go"
+	mkerrors=
+	mksysnum=
+	mktypes=
+	;;
 *)
 	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
 	exit 1
@@ -211,10 +222,15 @@ esac
 				# aix/ppc64 script generates files instead of writing to stdin.
 				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
 			elif [ "$GOOS" == "darwin" ]; then
-			        # pre-1.12, direct syscalls
-			        echo "$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go";
 			        # 1.12 and later, syscalls via libSystem
 				echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
+				# 1.13 and later, syscalls via libSystem (including syscallPtr)
+				echo "$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go";
+			elif [ "$GOOS" == "illumos" ]; then
+			        # illumos code generation requires a --illumos switch
+			        echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go";
+			        # illumos implies solaris, so solaris code generation is also required
+				echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go";
 			else
 				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
 			fi

+ 44 - 5
vendor/golang.org/x/sys/unix/mkerrors.sh

@@ -44,6 +44,7 @@ includes_AIX='
 #include <sys/stropts.h>
 #include <sys/mman.h>
 #include <sys/poll.h>
+#include <sys/select.h>
 #include <sys/termio.h>
 #include <termios.h>
 #include <fcntl.h>
@@ -57,12 +58,15 @@ includes_Darwin='
 #define _DARWIN_USE_64_BIT_INODE
 #include <stdint.h>
 #include <sys/attr.h>
+#include <sys/clonefile.h>
+#include <sys/kern_control.h>
 #include <sys/types.h>
 #include <sys/event.h>
 #include <sys/ptrace.h>
 #include <sys/select.h>
 #include <sys/socket.h>
 #include <sys/sockio.h>
+#include <sys/sys_domain.h>
 #include <sys/sysctl.h>
 #include <sys/mman.h>
 #include <sys/mount.h>
@@ -92,6 +96,7 @@ includes_DragonFly='
 #include <sys/ioctl.h>
 #include <net/bpf.h>
 #include <net/if.h>
+#include <net/if_clone.h>
 #include <net/if_types.h>
 #include <net/route.h>
 #include <netinet/in.h>
@@ -104,7 +109,9 @@ includes_FreeBSD='
 #include <sys/capsicum.h>
 #include <sys/param.h>
 #include <sys/types.h>
+#include <sys/disk.h>
 #include <sys/event.h>
+#include <sys/sched.h>
 #include <sys/select.h>
 #include <sys/socket.h>
 #include <sys/sockio.h>
@@ -185,16 +192,24 @@ struct ltchars {
 #include <sys/select.h>
 #include <sys/signalfd.h>
 #include <sys/socket.h>
+#include <sys/timerfd.h>
+#include <sys/uio.h>
 #include <sys/xattr.h>
 #include <linux/bpf.h>
 #include <linux/can.h>
+#include <linux/can/error.h>
+#include <linux/can/raw.h>
 #include <linux/capability.h>
 #include <linux/cryptouser.h>
+#include <linux/devlink.h>
+#include <linux/dm-ioctl.h>
 #include <linux/errqueue.h>
 #include <linux/falloc.h>
 #include <linux/fanotify.h>
 #include <linux/filter.h>
 #include <linux/fs.h>
+#include <linux/fscrypt.h>
+#include <linux/fsverity.h>
 #include <linux/genetlink.h>
 #include <linux/hdreg.h>
 #include <linux/icmpv6.h>
@@ -210,6 +225,7 @@ struct ltchars {
 #include <linux/kexec.h>
 #include <linux/keyctl.h>
 #include <linux/loop.h>
+#include <linux/lwtunnel.h>
 #include <linux/magic.h>
 #include <linux/memfd.h>
 #include <linux/module.h>
@@ -218,6 +234,7 @@ struct ltchars {
 #include <linux/net_namespace.h>
 #include <linux/nsfs.h>
 #include <linux/perf_event.h>
+#include <linux/pps.h>
 #include <linux/ptrace.h>
 #include <linux/random.h>
 #include <linux/reboot.h>
@@ -276,6 +293,11 @@ struct ltchars {
 // for the tipc_subscr timeout __u32 field.
 #undef TIPC_WAIT_FOREVER
 #define TIPC_WAIT_FOREVER 0xffffffff
+
+// Copied from linux/l2tp.h
+// Including linux/l2tp.h here causes conflicts between linux/in.h
+// and netinet/in.h included via net/route.h above.
+#define IPPROTO_L2TP		115
 '
 
 includes_NetBSD='
@@ -285,6 +307,7 @@ includes_NetBSD='
 #include <sys/extattr.h>
 #include <sys/mman.h>
 #include <sys/mount.h>
+#include <sys/sched.h>
 #include <sys/select.h>
 #include <sys/socket.h>
 #include <sys/sockio.h>
@@ -313,6 +336,7 @@ includes_OpenBSD='
 #include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/select.h>
+#include <sys/sched.h>
 #include <sys/socket.h>
 #include <sys/sockio.h>
 #include <sys/stat.h>
@@ -353,6 +377,7 @@ includes_SunOS='
 #include <sys/socket.h>
 #include <sys/sockio.h>
 #include <sys/stat.h>
+#include <sys/stream.h>
 #include <sys/mman.h>
 #include <sys/wait.h>
 #include <sys/ioctl.h>
@@ -469,21 +494,24 @@ ccflags="$@"
 		$2 ~ /^(MS|MNT|UMOUNT)_/ ||
 		$2 ~ /^NS_GET_/ ||
 		$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
-		$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||
+		$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|TFD)_/ ||
 		$2 ~ /^KEXEC_/ ||
 		$2 ~ /^LINUX_REBOOT_CMD_/ ||
 		$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
 		$2 ~ /^MODULE_INIT_/ ||
 		$2 !~ "NLA_TYPE_MASK" &&
+		$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&
 		$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||
+		$2 ~ /^FIORDCHK$/ ||
 		$2 ~ /^SIOC/ ||
 		$2 ~ /^TIOC/ ||
 		$2 ~ /^TCGET/ ||
 		$2 ~ /^TCSET/ ||
 		$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||
 		$2 !~ "RTF_BITS" &&
-		$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
+		$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||
 		$2 ~ /^BIOC/ ||
+		$2 ~ /^DIOC/ ||
 		$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
 		$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||
 		$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
@@ -493,13 +521,21 @@ ccflags="$@"
 		$2 ~ /^(CLOCK|TIMER)_/ ||
 		$2 ~ /^CAN_/ ||
 		$2 ~ /^CAP_/ ||
+		$2 ~ /^CP_/ ||
+		$2 ~ /^CPUSTATES$/ ||
+		$2 ~ /^CTLIOCGINFO$/ ||
 		$2 ~ /^ALG_/ ||
-		$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||
+		$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||
+		$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||
+		$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||
+		$2 ~ /^FS_VERITY_/ ||
+		$2 ~ /^FSCRYPT_/ ||
+		$2 ~ /^DM_/ ||
 		$2 ~ /^GRND_/ ||
 		$2 ~ /^RND/ ||
 		$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
 		$2 ~ /^KEYCTL_/ ||
-		$2 ~ /^PERF_EVENT_IOC_/ ||
+		$2 ~ /^PERF_/ ||
 		$2 ~ /^SECCOMP_MODE_/ ||
 		$2 ~ /^SPLICE_/ ||
 		$2 ~ /^SYNC_FILE_RANGE_/ ||
@@ -518,12 +554,15 @@ ccflags="$@"
 		$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||
 		$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||
 		$2 ~ /^FSOPT_/ ||
-		$2 ~ /^WDIOC_/ ||
+		$2 ~ /^WDIO[CFS]_/ ||
 		$2 ~ /^NFN/ ||
 		$2 ~ /^XDP_/ ||
+		$2 ~ /^RWF_/ ||
 		$2 ~ /^(HDIO|WIN|SMART)_/ ||
 		$2 ~ /^CRYPTO_/ ||
 		$2 ~ /^TIPC_/ ||
+		$2 ~ /^DEVLINK_/ ||
+		$2 ~ /^LWTUNNEL_IP/ ||
 		$2 !~ "WMESGLEN" &&
 		$2 ~ /^W[A-Z0-9]+$/ ||
 		$2 ~/^PPPIOC/ ||

+ 16 - 0
vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go

@@ -0,0 +1,16 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package unix
+
+// Round the length of a raw sockaddr up to align it properly.
+func cmsgAlignOf(salen int) int {
+	salign := SizeofPtr
+	if SizeofPtr == 8 && !supportsABI(_dragonflyABIChangeVersion) {
+		// 64-bit Dragonfly before the September 2019 ABI changes still requires
+		// 32-bit aligned access to network subsystem.
+		salign = 4
+	}
+	return (salen + salign - 1) & ^(salign - 1)
+}

+ 1 - 1
vendor/golang.org/x/sys/unix/sockcmsg_linux.go

@@ -17,7 +17,7 @@ func UnixCredentials(ucred *Ucred) []byte {
 	h.Level = SOL_SOCKET
 	h.Type = SCM_CREDENTIALS
 	h.SetLen(CmsgLen(SizeofUcred))
-	*((*Ucred)(cmsgData(h))) = *ucred
+	*(*Ucred)(h.data(0)) = *ucred
 	return b
 }
 

+ 4 - 32
vendor/golang.org/x/sys/unix/sockcmsg_unix.go

@@ -9,35 +9,9 @@
 package unix
 
 import (
-	"runtime"
 	"unsafe"
 )
 
-// Round the length of a raw sockaddr up to align it properly.
-func cmsgAlignOf(salen int) int {
-	salign := SizeofPtr
-
-	switch runtime.GOOS {
-	case "aix":
-		// There is no alignment on AIX.
-		salign = 1
-	case "darwin", "dragonfly", "solaris", "illumos":
-		// NOTE: It seems like 64-bit Darwin, DragonFly BSD,
-		// illumos, and Solaris kernels still require 32-bit
-		// aligned access to network subsystem.
-		if SizeofPtr == 8 {
-			salign = 4
-		}
-	case "netbsd", "openbsd":
-		// NetBSD and OpenBSD armv7 require 64-bit alignment.
-		if runtime.GOARCH == "arm" {
-			salign = 8
-		}
-	}
-
-	return (salen + salign - 1) & ^(salign - 1)
-}
-
 // CmsgLen returns the value to store in the Len field of the Cmsghdr
 // structure, taking into account any necessary alignment.
 func CmsgLen(datalen int) int {
@@ -50,8 +24,8 @@ func CmsgSpace(datalen int) int {
 	return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf(datalen)
 }
 
-func cmsgData(h *Cmsghdr) unsafe.Pointer {
-	return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr)))
+func (h *Cmsghdr) data(offset uintptr) unsafe.Pointer {
+	return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr)) + offset)
 }
 
 // SocketControlMessage represents a socket control message.
@@ -94,10 +68,8 @@ func UnixRights(fds ...int) []byte {
 	h.Level = SOL_SOCKET
 	h.Type = SCM_RIGHTS
 	h.SetLen(CmsgLen(datalen))
-	data := cmsgData(h)
-	for _, fd := range fds {
-		*(*int32)(data) = int32(fd)
-		data = unsafe.Pointer(uintptr(data) + 4)
+	for i, fd := range fds {
+		*(*int32)(h.data(4 * uintptr(i))) = int32(fd)
 	}
 	return b
 }

+ 42 - 0
vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go

@@ -0,0 +1,42 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build aix darwin freebsd linux netbsd openbsd solaris
+
+package unix
+
+import (
+	"runtime"
+)
+
+// Round the length of a raw sockaddr up to align it properly.
+func cmsgAlignOf(salen int) int {
+	salign := SizeofPtr
+
+	// dragonfly needs to check ABI version at runtime, see cmsgAlignOf in
+	// sockcmsg_dragonfly.go
+	switch runtime.GOOS {
+	case "aix":
+		// There is no alignment on AIX.
+		salign = 1
+	case "darwin", "ios", "illumos", "solaris":
+		// NOTE: It seems like 64-bit Darwin, Illumos and Solaris
+		// kernels still require 32-bit aligned access to network
+		// subsystem.
+		if SizeofPtr == 8 {
+			salign = 4
+		}
+	case "netbsd", "openbsd":
+		// NetBSD and OpenBSD armv7 require 64-bit alignment.
+		if runtime.GOARCH == "arm" {
+			salign = 8
+		}
+		// NetBSD aarch64 requires 128-bit alignment.
+		if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm64" {
+			salign = 16
+		}
+	}
+
+	return (salen + salign - 1) & ^(salign - 1)
+}

+ 42 - 1
vendor/golang.org/x/sys/unix/syscall.go

@@ -24,7 +24,13 @@
 // holds a value of type syscall.Errno.
 package unix // import "golang.org/x/sys/unix"
 
-import "strings"
+import (
+	"bytes"
+	"strings"
+	"unsafe"
+
+	"golang.org/x/sys/internal/unsafeheader"
+)
 
 // ByteSliceFromString returns a NUL-terminated slice of bytes
 // containing the text of s. If s contains a NUL byte at any
@@ -49,5 +55,40 @@ func BytePtrFromString(s string) (*byte, error) {
 	return &a[0], nil
 }
 
+// ByteSliceToString returns a string form of the text represented by the slice s, with a terminating NUL and any
+// bytes after the NUL removed.
+func ByteSliceToString(s []byte) string {
+	if i := bytes.IndexByte(s, 0); i != -1 {
+		s = s[:i]
+	}
+	return string(s)
+}
+
+// BytePtrToString takes a pointer to a sequence of text and returns the corresponding string.
+// If the pointer is nil, it returns the empty string. It assumes that the text sequence is terminated
+// at a zero byte; if the zero byte is not present, the program may crash.
+func BytePtrToString(p *byte) string {
+	if p == nil {
+		return ""
+	}
+	if *p == 0 {
+		return ""
+	}
+
+	// Find NUL terminator.
+	n := 0
+	for ptr := unsafe.Pointer(p); *(*byte)(ptr) != 0; n++ {
+		ptr = unsafe.Pointer(uintptr(ptr) + 1)
+	}
+
+	var s []byte
+	h := (*unsafeheader.Slice)(unsafe.Pointer(&s))
+	h.Data = unsafe.Pointer(p)
+	h.Len = n
+	h.Cap = n
+
+	return string(s)
+}
+
 // Single-word zero for use when we need a valid pointer to 0 bytes.
 var _zero uintptr

+ 16 - 0
vendor/golang.org/x/sys/unix/syscall_aix.go

@@ -19,6 +19,22 @@ import "unsafe"
  * Wrapped
  */
 
+func Access(path string, mode uint32) (err error) {
+	return Faccessat(AT_FDCWD, path, mode, 0)
+}
+
+func Chmod(path string, mode uint32) (err error) {
+	return Fchmodat(AT_FDCWD, path, mode, 0)
+}
+
+func Chown(path string, uid int, gid int) (err error) {
+	return Fchownat(AT_FDCWD, path, uid, gid, 0)
+}
+
+func Creat(path string, mode uint32) (fd int, err error) {
+	return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
+}
+
 //sys	utimes(path string, times *[2]Timeval) (err error)
 func Utimes(path string, tv []Timeval) error {
 	if len(tv) != 2 {

+ 52 - 5
vendor/golang.org/x/sys/unix/syscall_bsd.go

@@ -18,6 +18,21 @@ import (
 	"unsafe"
 )
 
+const ImplementsGetwd = true
+
+func Getwd() (string, error) {
+	var buf [PathMax]byte
+	_, err := Getcwd(buf[0:])
+	if err != nil {
+		return "", err
+	}
+	n := clen(buf[:])
+	if n < 1 {
+		return "", EINVAL
+	}
+	return string(buf[:n]), nil
+}
+
 /*
  * Wrapped
  */
@@ -237,7 +252,7 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
 				break
 			}
 		}
-		bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
+		bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
 		sa.Name = string(bytes)
 		return sa, nil
 
@@ -262,7 +277,7 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
 		}
 		return sa, nil
 	}
-	return nil, EAFNOSUPPORT
+	return anyToSockaddrGOOS(fd, rsa)
 }
 
 func Accept(fd int) (nfd int, sa Sockaddr, err error) {
@@ -272,7 +287,7 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) {
 	if err != nil {
 		return
 	}
-	if runtime.GOOS == "darwin" && len == 0 {
+	if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && len == 0 {
 		// Accepted socket has no address.
 		// This is likely due to a bug in xnu kernels,
 		// where instead of ECONNABORTED error socket
@@ -510,6 +525,40 @@ func SysctlRaw(name string, args ...int) ([]byte, error) {
 	return buf[:n], nil
 }
 
+func SysctlClockinfo(name string) (*Clockinfo, error) {
+	mib, err := sysctlmib(name)
+	if err != nil {
+		return nil, err
+	}
+
+	n := uintptr(SizeofClockinfo)
+	var ci Clockinfo
+	if err := sysctl(mib, (*byte)(unsafe.Pointer(&ci)), &n, nil, 0); err != nil {
+		return nil, err
+	}
+	if n != SizeofClockinfo {
+		return nil, EIO
+	}
+	return &ci, nil
+}
+
+func SysctlTimeval(name string) (*Timeval, error) {
+	mib, err := sysctlmib(name)
+	if err != nil {
+		return nil, err
+	}
+
+	var tv Timeval
+	n := uintptr(unsafe.Sizeof(tv))
+	if err := sysctl(mib, (*byte)(unsafe.Pointer(&tv)), &n, nil, 0); err != nil {
+		return nil, err
+	}
+	if n != unsafe.Sizeof(tv) {
+		return nil, EIO
+	}
+	return &tv, nil
+}
+
 //sys	utimes(path string, timeval *[2]Timeval) (err error)
 
 func Utimes(path string, tv []Timeval) error {
@@ -577,8 +626,6 @@ func Futimes(fd int, tv []Timeval) error {
 	return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
 }
 
-//sys	fcntl(fd int, cmd int, arg int) (val int, err error)
-
 //sys   poll(fds *PollFd, nfds int, timeout int) (n int, err error)
 
 func Poll(fds []PollFd, timeout int) (n int, err error) {

+ 31 - 0
vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go

@@ -0,0 +1,31 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,go1.12,!go1.13
+
+package unix
+
+import (
+	"unsafe"
+)
+
+const _SYS_GETDIRENTRIES64 = 344
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+	// To implement this using libSystem we'd need syscall_syscallPtr for
+	// fdopendir. However, syscallPtr was only added in Go 1.13, so we fall
+	// back to raw syscalls for this func on Go 1.12.
+	var p unsafe.Pointer
+	if len(buf) > 0 {
+		p = unsafe.Pointer(&buf[0])
+	} else {
+		p = unsafe.Pointer(&_zero)
+	}
+	r0, _, e1 := Syscall6(_SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
+	n = int(r0)
+	if e1 != 0 {
+		return n, errnoErr(e1)
+	}
+	return n, nil
+}

+ 108 - 0
vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go

@@ -0,0 +1,108 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,go1.13
+
+package unix
+
+import (
+	"unsafe"
+
+	"golang.org/x/sys/internal/unsafeheader"
+)
+
+//sys	closedir(dir uintptr) (err error)
+//sys	readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
+
+func fdopendir(fd int) (dir uintptr, err error) {
+	r0, _, e1 := syscall_syscallPtr(funcPC(libc_fdopendir_trampoline), uintptr(fd), 0, 0)
+	dir = uintptr(r0)
+	if e1 != 0 {
+		err = errnoErr(e1)
+	}
+	return
+}
+
+func libc_fdopendir_trampoline()
+
+//go:linkname libc_fdopendir libc_fdopendir
+//go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib"
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+	// Simulate Getdirentries using fdopendir/readdir_r/closedir.
+	// We store the number of entries to skip in the seek
+	// offset of fd. See issue #31368.
+	// It's not the full required semantics, but should handle the case
+	// of calling Getdirentries or ReadDirent repeatedly.
+	// It won't handle assigning the results of lseek to *basep, or handle
+	// the directory being edited underfoot.
+	skip, err := Seek(fd, 0, 1 /* SEEK_CUR */)
+	if err != nil {
+		return 0, err
+	}
+
+	// We need to duplicate the incoming file descriptor
+	// because the caller expects to retain control of it, but
+	// fdopendir expects to take control of its argument.
+	// Just Dup'ing the file descriptor is not enough, as the
+	// result shares underlying state. Use Openat to make a really
+	// new file descriptor referring to the same directory.
+	fd2, err := Openat(fd, ".", O_RDONLY, 0)
+	if err != nil {
+		return 0, err
+	}
+	d, err := fdopendir(fd2)
+	if err != nil {
+		Close(fd2)
+		return 0, err
+	}
+	defer closedir(d)
+
+	var cnt int64
+	for {
+		var entry Dirent
+		var entryp *Dirent
+		e := readdir_r(d, &entry, &entryp)
+		if e != 0 {
+			return n, errnoErr(e)
+		}
+		if entryp == nil {
+			break
+		}
+		if skip > 0 {
+			skip--
+			cnt++
+			continue
+		}
+
+		reclen := int(entry.Reclen)
+		if reclen > len(buf) {
+			// Not enough room. Return for now.
+			// The counter will let us know where we should start up again.
+			// Note: this strategy for suspending in the middle and
+			// restarting is O(n^2) in the length of the directory. Oh well.
+			break
+		}
+
+		// Copy entry into return buffer.
+		var s []byte
+		hdr := (*unsafeheader.Slice)(unsafe.Pointer(&s))
+		hdr.Data = unsafe.Pointer(&entry)
+		hdr.Cap = reclen
+		hdr.Len = reclen
+		copy(buf, s)
+
+		buf = buf[reclen:]
+		n += reclen
+		cnt++
+	}
+	// Set the seek offset of the input fd to record
+	// how many files we've already returned.
+	_, err = Seek(fd, cnt, 0 /* SEEK_SET */)
+	if err != nil {
+		return n, err
+	}
+
+	return n, nil
+}

+ 74 - 89
vendor/golang.org/x/sys/unix/syscall_darwin.go

@@ -13,29 +13,11 @@
 package unix
 
 import (
-	"errors"
+	"runtime"
 	"syscall"
 	"unsafe"
 )
 
-const ImplementsGetwd = true
-
-func Getwd() (string, error) {
-	buf := make([]byte, 2048)
-	attrs, err := getAttrList(".", attrList{CommonAttr: attrCmnFullpath}, buf, 0)
-	if err == nil && len(attrs) == 1 && len(attrs[0]) >= 2 {
-		wd := string(attrs[0])
-		// Sanity check that it's an absolute path and ends
-		// in a null byte, which we then strip.
-		if wd[0] == '/' && wd[len(wd)-1] == 0 {
-			return wd[:len(wd)-1], nil
-		}
-	}
-	// If pkg/os/getwd.go gets ENOTSUP, it will fall back to the
-	// slow algorithm.
-	return "", ENOTSUP
-}
-
 // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets.
 type SockaddrDatalink struct {
 	Len    uint8
@@ -49,6 +31,41 @@ type SockaddrDatalink struct {
 	raw    RawSockaddrDatalink
 }
 
+// SockaddrCtl implements the Sockaddr interface for AF_SYSTEM type sockets.
+type SockaddrCtl struct {
+	ID   uint32
+	Unit uint32
+	raw  RawSockaddrCtl
+}
+
+func (sa *SockaddrCtl) sockaddr() (unsafe.Pointer, _Socklen, error) {
+	sa.raw.Sc_len = SizeofSockaddrCtl
+	sa.raw.Sc_family = AF_SYSTEM
+	sa.raw.Ss_sysaddr = AF_SYS_CONTROL
+	sa.raw.Sc_id = sa.ID
+	sa.raw.Sc_unit = sa.Unit
+	return unsafe.Pointer(&sa.raw), SizeofSockaddrCtl, nil
+}
+
+func anyToSockaddrGOOS(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
+	switch rsa.Addr.Family {
+	case AF_SYSTEM:
+		pp := (*RawSockaddrCtl)(unsafe.Pointer(rsa))
+		if pp.Ss_sysaddr == AF_SYS_CONTROL {
+			sa := new(SockaddrCtl)
+			sa.ID = pp.Sc_id
+			sa.Unit = pp.Sc_unit
+			return sa, nil
+		}
+	}
+	return nil, EAFNOSUPPORT
+}
+
+// Some external packages rely on SYS___SYSCTL being defined to implement their
+// own sysctl wrappers. Provide it here, even though direct syscalls are no
+// longer supported on darwin.
+const SYS___SYSCTL = SYS_SYSCTL
+
 // Translate "kern.hostname" to []_C_int{0,1,2,3}.
 func nametomib(name string) (mib []_C_int, err error) {
 	const siz = unsafe.Sizeof(mib[0])
@@ -92,11 +109,6 @@ func direntNamlen(buf []byte) (uint64, bool) {
 func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) }
 func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) }
 
-const (
-	attrBitMapCount = 5
-	attrCmnFullpath = 0x08000000
-)
-
 type attrList struct {
 	bitmapCount uint16
 	_           uint16
@@ -107,71 +119,6 @@ type attrList struct {
 	Forkattr    uint32
 }
 
-func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) {
-	if len(attrBuf) < 4 {
-		return nil, errors.New("attrBuf too small")
-	}
-	attrList.bitmapCount = attrBitMapCount
-
-	var _p0 *byte
-	_p0, err = BytePtrFromString(path)
-	if err != nil {
-		return nil, err
-	}
-
-	if err := getattrlist(_p0, unsafe.Pointer(&attrList), unsafe.Pointer(&attrBuf[0]), uintptr(len(attrBuf)), int(options)); err != nil {
-		return nil, err
-	}
-	size := *(*uint32)(unsafe.Pointer(&attrBuf[0]))
-
-	// dat is the section of attrBuf that contains valid data,
-	// without the 4 byte length header. All attribute offsets
-	// are relative to dat.
-	dat := attrBuf
-	if int(size) < len(attrBuf) {
-		dat = dat[:size]
-	}
-	dat = dat[4:] // remove length prefix
-
-	for i := uint32(0); int(i) < len(dat); {
-		header := dat[i:]
-		if len(header) < 8 {
-			return attrs, errors.New("truncated attribute header")
-		}
-		datOff := *(*int32)(unsafe.Pointer(&header[0]))
-		attrLen := *(*uint32)(unsafe.Pointer(&header[4]))
-		if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) {
-			return attrs, errors.New("truncated results; attrBuf too small")
-		}
-		end := uint32(datOff) + attrLen
-		attrs = append(attrs, dat[datOff:end])
-		i = end
-		if r := i % 4; r != 0 {
-			i += (4 - r)
-		}
-	}
-	return
-}
-
-//sys getattrlist(path *byte, list unsafe.Pointer, buf unsafe.Pointer, size uintptr, options int) (err error)
-
-func SysctlClockinfo(name string) (*Clockinfo, error) {
-	mib, err := sysctlmib(name)
-	if err != nil {
-		return nil, err
-	}
-
-	n := uintptr(SizeofClockinfo)
-	var ci Clockinfo
-	if err := sysctl(mib, (*byte)(unsafe.Pointer(&ci)), &n, nil, 0); err != nil {
-		return nil, err
-	}
-	if n != SizeofClockinfo {
-		return nil, EIO
-	}
-	return &ci, nil
-}
-
 //sysnb pipe() (r int, w int, err error)
 
 func Pipe(p []int) (err error) {
@@ -333,12 +280,45 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) error {
  * Wrapped
  */
 
+//sys	fcntl(fd int, cmd int, arg int) (val int, err error)
+
 //sys	kill(pid int, signum int, posix int) (err error)
 
 func Kill(pid int, signum syscall.Signal) (err error) { return kill(pid, int(signum), 1) }
 
 //sys	ioctl(fd int, req uint, arg uintptr) (err error)
 
+func IoctlCtlInfo(fd int, ctlInfo *CtlInfo) error {
+	err := ioctl(fd, CTLIOCGINFO, uintptr(unsafe.Pointer(ctlInfo)))
+	runtime.KeepAlive(ctlInfo)
+	return err
+}
+
+// IfreqMTU is struct ifreq used to get or set a network device's MTU.
+type IfreqMTU struct {
+	Name [IFNAMSIZ]byte
+	MTU  int32
+}
+
+// IoctlGetIfreqMTU performs the SIOCGIFMTU ioctl operation on fd to get the MTU
+// of the network device specified by ifname.
+func IoctlGetIfreqMTU(fd int, ifname string) (*IfreqMTU, error) {
+	var ifreq IfreqMTU
+	copy(ifreq.Name[:], ifname)
+	err := ioctl(fd, SIOCGIFMTU, uintptr(unsafe.Pointer(&ifreq)))
+	return &ifreq, err
+}
+
+// IoctlSetIfreqMTU performs the SIOCSIFMTU ioctl operation on fd to set the MTU
+// of the network device specified by ifreq.Name.
+func IoctlSetIfreqMTU(fd int, ifreq *IfreqMTU) error {
+	err := ioctl(fd, SIOCSIFMTU, uintptr(unsafe.Pointer(ifreq)))
+	runtime.KeepAlive(ifreq)
+	return err
+}
+
+//sys   sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS_SYSCTL
+
 func Uname(uname *Utsname) error {
 	mib := []_C_int{CTL_KERN, KERN_OSTYPE}
 	n := unsafe.Sizeof(uname.Sysname)
@@ -409,6 +389,8 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
 //sys	Chroot(path string) (err error)
 //sys	ClockGettime(clockid int32, time *Timespec) (err error)
 //sys	Close(fd int) (err error)
+//sys	Clonefile(src string, dst string, flags int) (err error)
+//sys	Clonefileat(srcDirfd int, src string, dstDirfd int, dst string, flags int) (err error)
 //sys	Dup(fd int) (nfd int, err error)
 //sys	Dup2(from int, to int) (err error)
 //sys	Exchangedata(path1 string, path2 string, options int) (err error)
@@ -420,10 +402,12 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
 //sys	Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
 //sys	Fchown(fd int, uid int, gid int) (err error)
 //sys	Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
+//sys	Fclonefileat(srcDirfd int, dstDirfd int, dst string, flags int) (err error)
 //sys	Flock(fd int, how int) (err error)
 //sys	Fpathconf(fd int, name int) (val int, err error)
 //sys	Fsync(fd int) (err error)
 //sys	Ftruncate(fd int, length int64) (err error)
+//sys	Getcwd(buf []byte) (n int, err error)
 //sys	Getdtablesize() (size int)
 //sysnb	Getegid() (egid int)
 //sysnb	Geteuid() (uid int)
@@ -436,6 +420,7 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
 //sysnb	Getrlimit(which int, lim *Rlimit) (err error)
 //sysnb	Getrusage(who int, rusage *Rusage) (err error)
 //sysnb	Getsid(pid int) (sid int, err error)
+//sysnb	Gettimeofday(tp *Timeval) (err error)
 //sysnb	Getuid() (uid int)
 //sysnb	Issetugid() (tainted bool)
 //sys	Kqueue() (fd int, err error)

+ 2 - 22
vendor/golang.org/x/sys/unix/syscall_darwin_386.go

@@ -6,12 +6,7 @@
 
 package unix
 
-import (
-	"syscall"
-)
-
-//sys	sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL
-//sys   ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
+import "syscall"
 
 func setTimespec(sec, nsec int64) Timespec {
 	return Timespec{Sec: int32(sec), Nsec: int32(nsec)}
@@ -21,17 +16,6 @@ func setTimeval(sec, usec int64) Timeval {
 	return Timeval{Sec: int32(sec), Usec: int32(usec)}
 }
 
-//sysnb	gettimeofday(tp *Timeval) (sec int32, usec int32, err error)
-func Gettimeofday(tv *Timeval) (err error) {
-	// The tv passed to gettimeofday must be non-nil
-	// but is otherwise unused. The answers come back
-	// in the two registers.
-	sec, usec, err := gettimeofday(tv)
-	tv.Sec = int32(sec)
-	tv.Usec = int32(usec)
-	return err
-}
-
 func SetKevent(k *Kevent_t, fd, mode, flags int) {
 	k.Ident = uint32(fd)
 	k.Filter = int16(mode)
@@ -56,15 +40,11 @@ func (cmsg *Cmsghdr) SetLen(length int) {
 
 func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
 
-// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
-// of darwin/386 the syscall is called sysctl instead of __sysctl.
-const SYS___SYSCTL = SYS_SYSCTL
-
 //sys	Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
 //sys	Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
 //sys	Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
-//sys	Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
 //sys	getfsstat(buf unsafe.Pointer, size uintptr, flags int) (n int, err error) = SYS_GETFSSTAT64
 //sys	Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
+//sys	ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
 //sys	Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
 //sys	Statfs(path string, stat *Statfs_t) (err error) = SYS_STATFS64

+ 2 - 22
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go

@@ -6,12 +6,7 @@
 
 package unix
 
-import (
-	"syscall"
-)
-
-//sys	sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL
-//sys   ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
+import "syscall"
 
 func setTimespec(sec, nsec int64) Timespec {
 	return Timespec{Sec: sec, Nsec: nsec}
@@ -21,17 +16,6 @@ func setTimeval(sec, usec int64) Timeval {
 	return Timeval{Sec: sec, Usec: int32(usec)}
 }
 
-//sysnb	gettimeofday(tp *Timeval) (sec int64, usec int32, err error)
-func Gettimeofday(tv *Timeval) (err error) {
-	// The tv passed to gettimeofday must be non-nil
-	// but is otherwise unused. The answers come back
-	// in the two registers.
-	sec, usec, err := gettimeofday(tv)
-	tv.Sec = sec
-	tv.Usec = usec
-	return err
-}
-
 func SetKevent(k *Kevent_t, fd, mode, flags int) {
 	k.Ident = uint64(fd)
 	k.Filter = int16(mode)
@@ -56,15 +40,11 @@ func (cmsg *Cmsghdr) SetLen(length int) {
 
 func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
 
-// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
-// of darwin/amd64 the syscall is called sysctl instead of __sysctl.
-const SYS___SYSCTL = SYS_SYSCTL
-
 //sys	Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
 //sys	Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
 //sys	Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
-//sys	Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
 //sys	getfsstat(buf unsafe.Pointer, size uintptr, flags int) (n int, err error) = SYS_GETFSSTAT64
 //sys	Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
+//sys	ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
 //sys	Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
 //sys	Statfs(path string, stat *Statfs_t) (err error) = SYS_STATFS64

Some files were not shown because too many files changed in this diff